answer
stringlengths
17
10.2M
import com.licel.jcardsim.base.Simulator; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Arrays; import java.util.Date; import javacard.framework.AID; import javacard.framework.Util; import javax.smartcardio.CommandAPDU; import javax.smartcardio.ResponseAPDU; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSAPublicKey; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Certificate; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.asn1.x509.V1TBSCertificateGenerator; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.TBSCertificate; import org.cryptonit.CryptonitApplet; /** * @author Mathias Brossard */ class piv { private static String toHex(String prefix, byte[] bytes) { StringBuilder sb = new StringBuilder(); sb.append(prefix); for (int i = 0; i < bytes.length; i++) { sb.append(String.format("%02x ", bytes[i])); } return sb.toString(); } private static ResponseAPDU sendAPDU(Simulator simulator, CommandAPDU command) { ResponseAPDU response; System.out.println(toHex(" > ", command.getBytes())); response = new ResponseAPDU(simulator.transmitCommand(command.getBytes())); System.out.println(toHex(" < ", response.getData()) + String.format("[sw=%04X l=%d]", response.getSW(), response.getData().length)); return response; } public static void main(String[] args) { ResponseAPDU response; Simulator simulator = new Simulator(); byte[] arg; byte[] appletAIDBytes = new byte[]{ (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00 }; short sw, le; AID appletAID = new AID(appletAIDBytes, (short) 0, (byte) appletAIDBytes.length); simulator.installApplet(appletAID, CryptonitApplet.class); System.out.println("Select Applet"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xA4, 0x04, 0x00, new byte[]{ (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08 })); System.out.println("Management key authentication (part 1)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x03, 0x9B, new byte[]{ (byte) 0x7C, (byte) 0x02, (byte) 0x80, (byte) 0x00 })); arg = new byte[]{ (byte) 0x7C, (byte) 0x14, (byte) 0x80, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x81, (byte) 0x08, (byte) 0x2B, (byte) 0x65, (byte) 0x4B, (byte) 0x22, (byte) 0xB2, (byte) 0x2D, (byte) 0x99, (byte) 0x7F }; SecretKey key = new SecretKeySpec(new byte[]{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }, "DESede"); try { Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, key); cipher.doFinal(response.getData(), 4, 8, arg, 4); } catch (Exception ex) { ex.printStackTrace(System.out); } System.out.println("Management key authentication (part 2)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x03, 0x9B, arg)); System.out.println("Generate RSA key (9A)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x47, 0x00, 0x9A, new byte[]{ (byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x07 })); arg = response.getData(); if (arg.length < 9 || arg[7] != 0x1 || arg[8] != 0x0) { System.err.println("Error modulus"); return; } byte[] n = new byte[257]; byte[] e = new byte[3]; short s = (short) (arg.length - 9); Util.arrayCopy(arg, (short) 9, n, (short) 1, s); sw = (short) response.getSW(); le = (short) (sw & 0xFF); System.out.println("Call GET RESPONSE"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le)); arg = response.getData(); if(arg.length < (256 - s)) { System.err.println("Error remaining modulus"); return; } Util.arrayCopy(arg, (short) 0, n, (short) (s + 1), (short) (256 - s)); s = (short) (256 - s); if (arg[s] != (byte) 0x82 || arg[s + 1] != (byte) 0x3) { System.err.println("Error exponent"); return; } Util.arrayCopy(arg, (short) (s + 2), e, (short) 0, (short) 3); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); TBSCertificate tbs; try { RSAPublicKey rsa_pub = new RSAPublicKey(new BigInteger(n), new BigInteger(e)); AlgorithmIdentifier palgo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); V1TBSCertificateGenerator tbsGen = new V1TBSCertificateGenerator(); tbsGen.setSerialNumber(new ASN1Integer(0x1)); tbsGen.setStartDate(new Time(new Date(100, 01, 01, 00, 00, 00))); tbsGen.setEndDate(new Time(new Date(130, 12, 31, 23, 59, 59))); tbsGen.setIssuer(new X500Name("CN=Cryptonit")); tbsGen.setSubject(new X500Name("CN=Cryptonit")); tbsGen.setSignature(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE)); tbsGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(palgo, rsa_pub)); tbs = tbsGen.generateTBSCertificate(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(tbs); } catch (Exception ex) { ex.printStackTrace(System.err); return; } byte[] digest = null; try { MessageDigest md; md = MessageDigest.getInstance("SHA-256"); md.update(bOut.toByteArray()); digest = md.digest(); } catch (Exception ex) { ex.printStackTrace(System.err); return; } System.out.println("Verify PIN"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x20, 0x00, 0x80, new byte[]{ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 })); /* RSA signature request */ byte[] sig_request = new byte[266], sig_prefix = new byte[]{ (byte) 0x7C, (byte) 0x82, (byte) 0x01, (byte) 0x06, (byte) 0x82, (byte) 0x00, (byte) 0x81, (byte) 0x82, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; Util.arrayFillNonAtomic(sig_request, (short) 0, (short) sig_request.length, (byte) 0xFF); Util.arrayCopy(sig_prefix, (short) 0, sig_request, (short) 0, (short) sig_prefix.length); sig_request[sig_request.length - digest.length - 1] = 0x0; Util.arrayCopy(digest, (short) 0, sig_request, (short) (sig_request.length - digest.length), (short) (digest.length)); System.out.println("RSA signature file (chained APDUs) first command"); arg = Arrays.copyOfRange(sig_request, 0, 255); response = sendAPDU(simulator, new CommandAPDU(0x10, 0x87, 0x07, 0x9A, arg)); System.out.println("RSA signature file (chained APDUs) second command"); arg = Arrays.copyOfRange(sig_request, 255, sig_request.length); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x07, 0x9A, arg)); arg = response.getData(); byte[] sig = new byte[256]; if (arg.length > 8 && arg[6] == 0x1 && arg[7] == 0x0) { s = (short) (arg.length - 8); Util.arrayCopy(arg, (short) 8, sig, (short) 0, s); } else { System.err.println("Error in signature"); return; } sw = (short) response.getSW(); le = (short) (sw & 0xFF); System.out.println("Call GET RESPONSE"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le)); arg = response.getData(); Util.arrayCopy(arg, (short) 0, sig, s, (short) (256 - s)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbs); v.add(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE)); v.add(new DERBitString(sig)); byte [] crt = null; try { Certificate c = Certificate.getInstance(new DERSequence(v)); crt = c.getEncoded(); } catch (Exception ex) { ex.printStackTrace(System.out); } byte[] prefix = new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x05, (byte) 0x53, (byte) 0x82 }, postfix = new byte[]{ (byte) 0x71, (byte) 0x01, (byte) 0x00, (byte) 0xFE, (byte) 0x00 }; short len = (short) (prefix.length + crt.length + 6 + postfix.length); byte[] buffer = new byte[len]; Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length); int off = prefix.length; buffer[off++] = (byte) (((crt.length + postfix.length + 4) >> 8) & 0xFF); buffer[off++] = (byte) ((crt.length + postfix.length + 4) & 0xFF); buffer[off++] = (byte) 0x70; buffer[off++] = (byte) 0x82; buffer[off++] = (byte) ((crt.length >> 8) & 0xFF); buffer[off++] = (byte) (crt.length & 0xFF); Util.arrayCopy(crt, (short) 0, buffer, (short) off, (short) crt.length); off += crt.length; Util.arrayCopy(postfix, (short) 0, buffer, (short) off, (short) postfix.length); int i = 1, left = buffer.length, sent = 0; while(left > 0) { System.out.println(String.format("Uploading certificate part %d", i++)); int cla = (left <= 255) ? 0x00 : 0x10; int sending = (left <= 255) ? left : 255; arg = Arrays.copyOfRange(buffer, sent, sent + sending); response = sendAPDU(simulator, new CommandAPDU(cla, 0xDB, 0x3F, 0xFF, arg)); sent += sending; left -= sending; } System.out.println("Read 0x5FC105 file (large)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xCB, 0x3F, 0xFF, new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x05 })); while (((sw = (short) response.getSW()) & 0xFF00) == 0x6100) { le = (short) (sw & 0xFF); System.out.println("Call GET RESPONSE"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le)); } System.out.println("Generate EC P256 key (9C)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x47, 0x00, 0x9C, new byte[]{ (byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x11 })); arg = response.getData(); if (arg.length < 9 || arg[3] != (byte) 0x86 || arg[4] != 0x41) { System.err.println("Error EC Public key"); return; } prefix = new byte[]{ (byte) 0x30, (byte) 0x59, (byte) 0x30, (byte) 0x13, (byte) 0x06, (byte) 0x07, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x3D, (byte) 0x02, (byte) 0x01, (byte) 0x06, (byte) 0x08, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x3D, (byte) 0x03, (byte) 0x01, (byte) 0x07, (byte) 0x03, (byte) 0x42, (byte) 0x00 }; buffer = new byte[prefix.length + 65]; Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length); Util.arrayCopy(arg, (short) 5, buffer, (short) prefix.length, (short) 65); System.out.println("Set Card Capabilities Container"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x07, (byte) 0x53, (byte) 0x33, (byte) 0xF0, (byte) 0x15, (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x16, (byte) 0xFF, (byte) 0x02, (byte) 0x30, (byte) 0x1D, (byte) 0x9C, (byte) 0x5D, (byte) 0xB7, (byte) 0xA3, (byte) 0x87, (byte) 0xF1, (byte) 0xBE, (byte) 0x25, (byte) 0x1F, (byte) 0xB9, (byte) 0xFB, (byte) 0x1A, (byte) 0xF1, (byte) 0x01, (byte) 0x21, (byte) 0xF2, (byte) 0x01, (byte) 0x21, (byte) 0xF3, (byte) 0x00, (byte) 0xF4, (byte) 0x01, (byte) 0x00, (byte) 0xF5, (byte) 0x01, (byte) 0x10, (byte) 0xF6, (byte) 0x00, (byte) 0xF7, (byte) 0x00, (byte) 0xFA, (byte) 0x00, (byte) 0xFB, (byte) 0x00, (byte) 0xFC, (byte) 0x00, (byte) 0xFD, (byte) 0x00, (byte) 0xFE, (byte) 0x00 })); System.out.println("Set CHUID"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x02, (byte) 0x53, (byte) 0x3B, (byte) 0x30, (byte) 0x19, (byte) 0xD4, (byte) 0xE7, (byte) 0x39, (byte) 0xDA, (byte) 0x73, (byte) 0x9C, (byte) 0xED, (byte) 0x39, (byte) 0xCE, (byte) 0x73, (byte) 0x9D, (byte) 0x83, (byte) 0x68, (byte) 0x58, (byte) 0x21, (byte) 0x08, (byte) 0x42, (byte) 0x10, (byte) 0x84, (byte) 0x21, (byte) 0x38, (byte) 0x42, (byte) 0x10, (byte) 0xC3, (byte) 0xF5, (byte) 0x34, (byte) 0x10, (byte) 0xFB, (byte) 0x0C, (byte) 0xB0, (byte) 0x46, (byte) 0x75, (byte) 0x85, (byte) 0xD3, (byte) 0x8D, (byte) 0xE2, (byte) 0xA4, (byte) 0x96, (byte) 0x83, (byte) 0x5E, (byte) 0x0D, (byte) 0xA7, (byte) 0x78, (byte) 0x35, (byte) 0x08, (byte) 0x32, (byte) 0x30, (byte) 0x33, (byte) 0x30, (byte) 0x30, (byte) 0x31, (byte) 0x30, (byte) 0x31, (byte) 0x3E, (byte) 0x00, (byte) 0xFE, (byte) 0x00 })); } }
package experimentalcode.erich.cache; /** * Class with various utilities for manipulating byte arrays. * * If you find a reusable copy of this in the Java API, please tell me. Using a * {@link java.io.ByteArrayOutputStream} and {@link java.io.DataInputStream} * doesn't seem appropriate. * * @author Erich Schubert */ public final class ByteArrayUtil { /** * Write a short to the byte array at the given offset. * * @param array Array to write to * @param offset Offset to write to * @param v data */ public final static void writeShort(byte[] array, int offset, int v) { array[offset] = (byte) ((v >>> 8) & 0xFF); array[offset + 1] = (byte) ((v >>> 0) & 0xFF); } /** * Write an integer to the byte array at the given offset. * * @param array Array to write to * @param offset Offset to write to * @param v data */ public final static void writeInt(byte[] array, int offset, int v) { array[offset] = (byte) ((v >>> 24) & 0xFF); array[offset + 1] = (byte) ((v >>> 16) & 0xFF); array[offset + 2] = (byte) ((v >>> 8) & 0xFF); array[offset + 3] = (byte) ((v >>> 0) & 0xFF); } /** * Write a long to the byte array at the given offset. * * @param array Array to write to * @param offset Offset to write to * @param v data */ public final static void writeLong(byte[] array, int offset, long v) { array[offset] = (byte) ((v >>> 56) & 0xFF); array[offset + 1] = (byte) ((v >>> 48) & 0xFF); array[offset + 2] = (byte) ((v >>> 40) & 0xFF); array[offset + 3] = (byte) ((v >>> 32) & 0xFF); array[offset + 4] = (byte) ((v >>> 24) & 0xFF); array[offset + 5] = (byte) ((v >>> 16) & 0xFF); array[offset + 6] = (byte) ((v >>> 8) & 0xFF); array[offset + 7] = (byte) ((v >>> 0) & 0xFF); } /** * Write a float to the byte array at the given offset. * * @param array Array to write to * @param offset Offset to write to * @param v data */ public final static void writeFloat(byte[] array, int offset, float v) { writeInt(array, offset, Float.floatToIntBits(v)); } /** * Write a double to the byte array at the given offset. * * @param array Array to write to * @param offset Offset to write to * @param v data */ public final static void writeDouble(byte[] array, int offset, double v) { writeLong(array, offset, Double.doubleToLongBits(v)); } /** * Read a short from the byte array at the given offset. * * @param array Array to read from * @param offset Offset to read at * @return (signed) short */ public final static short readShort(byte[] array, int offset) { // First make integers to resolve signed vs. unsigned issues. int b0 = array[offset] & 0xFF; int b1 = array[offset + 1] & 0xFF; return (short) ((b0 << 8) + (b1 << 0)); } /** * Read an unsigned short from the byte array at the given offset. * * @param array Array to read from * @param offset Offset to read at * @return short */ public final static int readUnsignedShort(byte[] array, int offset) { // First make integers to resolve signed vs. unsigned issues. int b0 = array[offset] & 0xFF; int b1 = array[offset + 1] & 0xFF; return ((b0 << 8) + (b1 << 0)); } /** * Read an integer from the byte array at the given offset. * * @param array Array to read from * @param offset Offset to read at * @return data */ public final static int readInt(byte[] array, int offset) { // First make integers to resolve signed vs. unsigned issues. int b0 = array[offset] & 0xFF; int b1 = array[offset + 1] & 0xFF; int b2 = array[offset + 2] & 0xFF; int b3 = array[offset + 3] & 0xFF; return ((b0 << 24) + (b1 << 16) + (b2 << 8) + (b3 << 0)); } /** * Read a long from the byte array at the given offset. * * @param array Array to read from * @param offset Offset to read at * @return data */ public final static long readLong(byte[] array, int offset) { // First make integers to resolve signed vs. unsigned issues. int b0 = array[offset] & 0xFF; int b1 = array[offset + 1] & 0xFF; int b2 = array[offset + 2] & 0xFF; int b3 = array[offset + 3] & 0xFF; int b4 = array[offset + 4] & 0xFF; int b5 = array[offset + 5] & 0xFF; int b6 = array[offset + 6] & 0xFF; int b7 = array[offset + 7] & 0xFF; return ((b0 << 56) + (b1 << 48) + (b2 << 40) + (b3 << 32) + (b4 << 24) + (b5 << 16) + (b6 << 8) + (b7 << 0)); } /** * Read a float from the byte array at the given offset. * * @param array Array to read from * @param offset Offset to read at * @return data */ public final static float readFloat(byte[] array, int offset) { return Float.intBitsToFloat(readInt(array, offset)); } /** * Read a double from the byte array at the given offset. * * @param array Array to read from * @param offset Offset to read at * @return data */ public final static double readDouble(byte[] array, int offset) { return Double.longBitsToDouble(readLong(array, offset)); } }
package fitnesse.wiki.fs; import fitnesse.ConfigurationParameter; import fitnesse.wiki.*; import org.eclipse.jgit.api.InitCommand; import org.eclipse.jgit.api.errors.GitAPIException; import util.FileUtil; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; public class VersionsControllerFixture { public static final String TEST_DIR = "TestDir"; private FileSystemPageFactory pageFactory; private WikiPage rootPage; private WikiPage lastUsedPage; public VersionsControllerFixture() { } public VersionsControllerFixture(String versionsControllerClassName) { Properties properties = new Properties(); properties.setProperty(ConfigurationParameter.VERSIONS_CONTROLLER_CLASS.getKey(), versionsControllerClassName); pageFactory = new FileSystemPageFactory(properties); } public void createWikiRoot() { rootPage = pageFactory.makePage(new File(TEST_DIR, "RooT"), "RooT", null, new SystemVariableSource()); } public WikiPage getRootPage() { return rootPage; } public void cleanUp() { FileUtil.deleteFileSystemDirectory(TEST_DIR); } public Object savePageWithContent(String pageName, String content) { lastUsedPage = WikiPageUtil.addPage(rootPage, PathParser.parse(pageName)); final PageData data = lastUsedPage.getData(); data.setContent(content); return lastUsedPage.commit(data); } public void deletePage(String pageName) { final PageCrawler pageCrawler = rootPage.getPageCrawler(); lastUsedPage = pageCrawler.getPage(PathParser.parse(pageName)); lastUsedPage.getParent().removeChildPage(lastUsedPage.getName()); } public int historySize() { Collection<VersionInfo> versions = lastUsedPage.getVersions(); return versions.size(); } public String getVersionInfos() { String result = ""; Collection<VersionInfo> versions = lastUsedPage.getVersions(); for (VersionInfo version : versions){ result = result + version.getName() +"-" + version.getAuthor() + "-" + version.getCreationTime() + "\n"; } return result; } public String contentForRevision(int n) { List<VersionInfo> versions = new ArrayList<VersionInfo>(lastUsedPage.getVersions()); WikiPage page = lastUsedPage.getVersion(versions.get(versions.size() - 1 - n).getName()); return page.getData().getContent(); } public String contentForRevisionFromPage(int n, String pageName) { final PageCrawler pageCrawler = rootPage.getPageCrawler(); lastUsedPage = pageCrawler.getPage(PathParser.parse(pageName)); if (lastUsedPage == null) return "[Error: Page doesn't exists]"; else return contentForRevision(n); } public String contentFromPage(String pageName) { final PageCrawler pageCrawler = rootPage.getPageCrawler(); lastUsedPage = pageCrawler.getPage(PathParser.parse(pageName)); if (lastUsedPage == null) return "[Error: Page doesn't exists]"; else return lastUsedPage.getData().getContent(); } public boolean initialiseGitRepository() throws GitAPIException { FileUtil.createDir(TEST_DIR); new InitCommand() .setDirectory(new File(TEST_DIR)) .setBare(false) .call(); return true; } }
package agreementMaker.userInterface; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.UIManager; import agreementMaker.GSM; import agreementMaker.application.Core; import agreementMaker.application.evaluationEngine.OntologyController; import agreementMaker.application.mappingEngine.AbstractMatcher; import agreementMaker.application.mappingEngine.fakeMatchers.UserManualMatcher; import agreementMaker.application.ontology.Ontology; import agreementMaker.application.ontology.ontologyParser.TreeBuilder; import agreementMaker.userInterface.vertex.VertexDescriptionPane; /** * UI Class - * * This class is responsible for creating the menu bar, displaying the canvas, * the buttons, and checkboxes at botton of the screen. * * @author ADVIS Research Laboratory * @version 12/5/2004 */ public class UI { static final long serialVersionUID = 1; private Canvas canvas; /** This class is going to be replaced later*/ private OntologyController ontologyController; private JFrame frame; private JPanel panelCanvas, panelDesc; private MatchersControlPanel matcherControlPanel; private JScrollPane scrollPane; private JSplitPane splitPane; private UIMenu uiMenu; /** * Default constructor for UI class */ public UI() { init(); } /** * @return canvas */ public Canvas getCanvas(){ return this.canvas; } /** * @return the ontologyController, a class containing some methods to work with canvas and ontologies */ public OntologyController getOntologyController(){ return this.ontologyController; } /** * @return */ public JPanel getCanvasPanel(){ return this.panelCanvas; } /** * @return */ public JPanel getDescriptionPanel(){ return this.panelDesc; } public UIMenu getUIMenu(){ return this.uiMenu; } /** * @return */ public JFrame getUIFrame(){ return this.frame; } /** * @return */ public JSplitPane getUISplitPane(){ return this.splitPane; } /** * Init method * This function creates menu, canvas, and checkboxes to be displayed on the screen */ public void init() { //Setting the Look and Feel of the application to that of Windows //try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } //catch (Exception e) { System.out.println(e); } // Setting the Look and Feel of the application to that of Windows //try { javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } //catch (Exception e) { System.out.println(e); } // Create a swing frame frame = new JFrame("Agreement Maker"); frame.getContentPane().setLayout(new BorderLayout()); // Create the Menu Bar and Menu Items uiMenu = new UIMenu(this); // create a new panel for the canvas panelCanvas = new JPanel(); // set the layout of the panel to be grid labyout of 1x1 grid panelCanvas.setLayout(new BorderLayout()); // create a canvas class canvas = new Canvas(this); canvas.setFocusable(true); //canvas.setMinimumSize(new Dimension(0,0)); //canvas.setPreferredSize(new Dimension(480,320)); //add canvas to panel panelCanvas.add(canvas); //Added by Flavio: this class is needed to modularize the big canvas class, basically it contains some methods which could be in canvas class which works with the ontologies //it will be replaced later adding structures and methods inside the Core ontologyController = new OntologyController(canvas); //panelDesc = new VertexDescriptionPane(this); //TODO: Add tabbed panes here for displaying the properties and descriptions scrollPane = new JScrollPane(panelCanvas); scrollPane.setWheelScrollingEnabled(true); scrollPane.getVerticalScrollBar().setUnitIncrement(20); //scrollPane.setPreferredSize(new Dimension((int)scrollPane.getSize().getHeight(), 5)); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPane, null); splitPane.setOneTouchExpandable(true); splitPane.setResizeWeight(1.0); splitPane.setMinimumSize(new Dimension(640,480)); splitPane.setPreferredSize(new Dimension(640,480)); splitPane.getLeftComponent().setPreferredSize(new Dimension(640,480)); // add scrollpane to the panel and add the panel to the frame's content pane frame.getContentPane().add(splitPane, BorderLayout.CENTER); //panelControlPanel = new ControlPanel(this, uiMenu, canvas); matcherControlPanel = new MatchersControlPanel(this, uiMenu, canvas); frame.getContentPane().add(matcherControlPanel, BorderLayout.PAGE_END); //Add the listener to close the frame. frame.addWindowListener(new WindowEventHandler()); // set frame size (width = 1000 height = 700) //frame.setSize(900,600); frame.pack(); frame.setExtendedState(Frame.MAXIMIZED_BOTH); // maximize the window // make sure the frame is visible frame.setVisible(true); } /** * @param jPanel */ public void setDescriptionPanel(JPanel jPanel){ this.panelDesc = jPanel; } /** This function will open a file * Attention syntax and language are placed differently from other functions. * @param ontoType the type of ontology, source or target * * */ public void openFile( String filename, int ontoType, int syntax, int language) { try{ JPanel jPanel = null; if(language == GSM.RDFSFILE)//RDFS jPanel = new VertexDescriptionPane(GSM.RDFSFILE);//takes care of fields for XML files as well else if(language == GSM.ONTFILE)//OWL jPanel = new VertexDescriptionPane(GSM.ONTFILE);//takes care of fields for XML files as well else if(language == GSM.XMLFILE)//XML jPanel = new VertexDescriptionPane(GSM.XMLFILE);//takes care of fields for XML files as well getUISplitPane().setRightComponent(jPanel); setDescriptionPanel(jPanel); //This function manage the whole process of loading, parsing the ontology and building data structures: Ontology to be set in the Core and Tree and to be set in the canvas TreeBuilder t = TreeBuilder.buildTreeBuilder(filename, ontoType, language, syntax); //Set ontology in the Core Ontology ont = t.getOntology(); if(ontoType == GSM.SOURCENODE) { Core.getInstance().setSourceOntology(ont); } else Core.getInstance().setTargetOntology(ont); //Set the tree in the canvas getCanvas().setTree(t); if(Core.getInstance().ontologiesLoaded()) { //Ogni volta che ho caricato un ontologia e le ho entrambe, devo resettare o settare se la prima volta, tutto lo schema dei matchings matcherControlPanel.resetMatchings(); } }catch(Exception ex){ JOptionPane.showConfirmDialog(null,"Can not parse the file '" + filename + "'. Please check the policy.","Parser Error",JOptionPane.PLAIN_MESSAGE); ex.printStackTrace(); } } /** * Class to close the frame and exit the application */ public class WindowEventHandler extends WindowAdapter { /** * Function which closes the window * @param e WindowEvent Object */ public void windowClosing(WindowEvent e) { e.getWindow().dispose(); //System.exit(0); } } public void redisplayCanvas() { canvas.repaint(); } }
package jelectrum; import java.util.Collection; import java.util.LinkedList; import java.security.MessageDigest; import java.util.TreeMap; import java.util.TreeSet; import java.util.Set; import java.util.List; import java.util.StringTokenizer; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.nio.ByteBuffer; import java.util.Scanner; import java.net.URL; import org.bitcoinj.core.Block; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.ScriptException; import org.bitcoinj.core.Address; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptChunk; import java.io.FileInputStream; import java.util.Scanner; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.DataInputStream; import java.util.zip.GZIPOutputStream; import org.apache.commons.codec.binary.Hex; import java.text.DecimalFormat; import java.util.Random; import org.junit.Assert; import com.google.protobuf.ByteString; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import static org.bitcoinj.script.ScriptOpCodes.*; /** * Blocks have to be loaded in order * * @todo - Add shutdown hook to avoid exit during flush * */ public class UtxoTrieMgr { public static final int UTXO_WORKER_THREADS = 12; // A key is 20 bytes of public key, 32 bytes of transaction id and 4 bytes of output index public static final int ADDR_SPACE = 56; public static boolean DEBUG=false; private NetworkParameters params; private Jelectrum jelly; private TXUtil tx_util; private StatData get_block_stat=new StatData(); private StatData add_block_stat=new StatData(); private StatData get_hash_stat=new StatData(); // Maps a partial key prefix to a tree node // The tree node has children, which are other prefixes or full keys protected TreeMap<String, UtxoTrieNode> node_map = new TreeMap<String, UtxoTrieNode>(); protected Map<String, UtxoTrieNode> db_map; protected Sha256Hash last_flush_block_hash; protected Sha256Hash last_added_block_hash; protected Object block_notify= new Object(); protected Object block_done_notify = new Object(); //Not to be trusted, only used for logging protected int block_height; protected volatile boolean caught_up=false; protected static PrintStream debug_out; private boolean enabled=true; private LRUCache<Sha256Hash, Sha256Hash> root_hash_cache = new LRUCache<>(256); private final Semaphore cache_sem = new Semaphore(0); private ThreadPoolExecutor worker_exec; public UtxoTrieMgr(Jelectrum jelly) throws java.io.FileNotFoundException { this.jelly = jelly; this.params = jelly.getNetworkParameters(); tx_util = new TXUtil(jelly.getDB(), params); if (jelly.getConfig().getBoolean("utxo_disabled")) { enabled=false; return; } worker_exec = new ThreadPoolExecutor( UTXO_WORKER_THREADS, UTXO_WORKER_THREADS, 2, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory()); db_map = jelly.getDB().getUtxoTrieMap(); if (jelly.getConfig().isSet("utxo_reset") && jelly.getConfig().getBoolean("utxo_reset")) { jelly.getEventLog().alarm("UTXO reset"); resetEverything(); } if (DEBUG) { debug_out = new PrintStream(new FileOutputStream("utxo-debug.log")); } } public void setTxUtil(TXUtil tx_util) { this.tx_util = tx_util; } public boolean isUpToDate() { return caught_up; } private boolean started=false; public void start() { if (!enabled) return; if (started) return; started=true; new UtxoMgrThread().start(); new UtxoCheckThread().start(); } public void resetEverything() { node_map.clear(); putSaveSet("", new UtxoTrieNode("")); last_flush_block_hash = params.getGenesisBlock().getHash(); last_added_block_hash = params.getGenesisBlock().getHash(); flush(); } /** * Just public for testing, don't call */ public void flush() { DecimalFormat df = new DecimalFormat("0.000"); //get_block_stat.print("get_block", df); //add_block_stat.print("add_block", df); //get_hash_stat.print("get_hash", df); jelly.getEventLog().alarm("UTXO Flushing: " + node_map.size() + " height: " + block_height); saveState(new UtxoStatus(last_added_block_hash, last_flush_block_hash)); db_map.putAll(node_map.descendingMap()); node_map.clear(); saveState(new UtxoStatus(last_added_block_hash)); last_flush_block_hash = last_added_block_hash; jelly.getEventLog().alarm("UTXO Flush complete"); } public void saveState(UtxoStatus status) { jelly.getDB().getSpecialObjectMap().put("utxo_trie_mgr_state", status); } public synchronized void printTree(PrintStream out) { out.println("UTXO TREE:"); getByKey("").printTree(out, 1, this); } public synchronized UtxoStatus getUtxoState() { if (!enabled) return null; try { Object o = jelly.getDB().getSpecialObjectMap().get("utxo_trie_mgr_state"); if (o != null) { return (UtxoStatus)o; } } catch(Throwable t) { t.printStackTrace(); } jelly.getEventLog().alarm("Problem loading UTXO status, starting fresh"); resetEverything(); return getUtxoState(); } public synchronized void addBlock(Block b) { long t1 = System.nanoTime(); LinkedList<String> keys_to_add = new LinkedList<String>(); LinkedList<String> keys_to_remove = new LinkedList<String>(); for(Transaction tx : b.getTransactions()) { long t2 = System.nanoTime(); addTransactionKeys(tx, keys_to_add, keys_to_remove); TimeRecord.record(t2, "utxo_get_tx_keys"); } LinkedList<String> all_keys = new LinkedList<String>(); all_keys.addAll(keys_to_add); all_keys.addAll(keys_to_remove); final UtxoTrieMgr mgr = this; long t1_cache = System.nanoTime(); for(final String key : all_keys) { worker_exec.execute( new Runnable() { public void run() { try { long t2 = System.nanoTime(); getByKey("").cacheNodes(key, mgr); TimeRecord.record(t2, "utxo_cache_nodes"); } catch(Throwable t) { t.printStackTrace(); } finally { cache_sem.release(1); } } } ); } try { cache_sem.acquire(all_keys.size()); } catch(InterruptedException e) { throw new RuntimeException(e); } TimeRecord.record(t1_cache, "utxo_cache_walltime"); for(String key : keys_to_add) { long t2 = System.nanoTime(); getByKey("").addHash(key, this); TimeRecord.record(t2, "utxo_add_hash"); } for(String key : keys_to_remove) { long t2 = System.nanoTime(); getByKey("").removeHash(key, this); TimeRecord.record(t2, "utxo_remove_hash"); } long t2 = System.nanoTime(); last_added_block_hash = b.getHash(); TimeRecord.record(t2, "utxo_gethash"); TimeRecord.record(t1, "utxo_add_block"); } // They see me rollin, they hating public synchronized void rollbackBlock(Block b) { LinkedList<Transaction> back_list = new LinkedList<Transaction>(); for(Transaction tx : b.getTransactions()) { back_list.addFirst(tx); } for(Transaction tx : back_list) { rollTransaction(tx); } } public synchronized void dumpDB(OutputStream out) throws java.io.IOException { UtxoStatus status = getUtxoState(); if (!status.isConsistent()) { throw new RuntimeException("UTXO status inconsistent - unable to dump db"); } System.out.println("Dumping DB at block: " + status.getBlockHash()); //write header out.write(status.getBlockHash().getBytes()); getByKey("").dumpDB(out, this); //write end marker byte[] sz = new byte[4]; out.write(sz); out.flush(); } public synchronized void loadDB(InputStream in) throws java.io.IOException { node_map.clear(); last_added_block_hash = null; last_flush_block_hash = null; byte[] hash_data = new byte[32]; DataInputStream d_in = new DataInputStream(in); d_in.readFully(hash_data); Sha256Hash read_hash = new Sha256Hash(hash_data); System.out.println("Reading block: " + read_hash); int node_count=0; TreeMap<String, UtxoTrieNode> save_map = new TreeMap<>(); StatData size_info = new StatData(); while(true) { int size = d_in.readInt(); if (size == 0) break; byte[] data = new byte[size]; d_in.readFully(data); UtxoTrieNode node = new UtxoTrieNode(ByteString.copyFrom(data)); size_info.addDataPoint(size); save_map.put(node.getPrefix(), node); node_count++; if (node_count % 1000 == 0) { db_map.putAll(save_map); save_map.clear(); System.out.print('.'); } } db_map.putAll(save_map); save_map.clear(); System.out.print('.'); System.out.println(); System.out.println("Saved " + node_count + " nodes"); saveState(new UtxoStatus(read_hash)); System.out.println("UTXO root hash: " + getRootHash(null)); size_info.print("sizes", new DecimalFormat("0.0")); } public void putSaveSet(String prefix, UtxoTrieNode node) { synchronized(node_map) { node_map.put(prefix, node); } } public UtxoTrieNode getByKey(String prefix) { UtxoTrieNode n = null; synchronized(node_map) { n = node_map.get(prefix); if (n != null) return n; } n = db_map.get(prefix); if (n != null) return n; jelly.getEventLog().alarm("UTXO node missing: ." + prefix + "."); return n; } private void checkUtxoHash(int height, Sha256Hash block, Sha256Hash utxo_hash) { UtxoCheckEntry check_entry = new UtxoCheckEntry(height, block, utxo_hash); check_queue.offer(check_entry); } private void addTransactionKeys(Transaction tx, LinkedList<String> keys_to_add, LinkedList<String> keys_to_remove) { int idx=0; for(TransactionOutput tx_out : tx.getOutputs()) { long t1 = System.nanoTime(); String key = getKeyForOutput(tx_out, idx); TimeRecord.record(t1, "utxo_get_key_for_output"); if (key != null) { keys_to_add.add(key); } /*if (DEBUG) debug_out.println("Adding key: " + key); if (key != null) { long t2 = System.nanoTime(); getByKey("").addHash(key, this); TimeRecord.record(t2, "utxo_addhash"); }*/ idx++; } for(TransactionInput tx_in : tx.getInputs()) { if (!tx_in.isCoinBase()) { long t1 = System.nanoTime(); String key = getKeyForInput(tx_in); TimeRecord.record(t1, "utxo_get_key_for_input"); if (key != null) { keys_to_remove.add(key); /*long t2 = System.nanoTime(); getByKey("").removeHash(key, this); TimeRecord.record(t2, "utxo_removehash");*/ } } } } private void rollTransaction(Transaction tx) { int idx=0; for(TransactionOutput tx_out : tx.getOutputs()) { String key = getKeyForOutput(tx_out, idx); if (DEBUG) System.out.println("Adding key: " + key); if (key != null) { getByKey("").removeHash(key, this); } idx++; } for(TransactionInput tx_in : tx.getInputs()) { if (!tx_in.isCoinBase()) { String key = getKeyForInput(tx_in); if (key != null) { getByKey("").addHash(key, this); } } } } public synchronized Collection<TransactionOutPoint> getUnspentForAddress(Address a) { String prefix = getPrefixForAddress(a); Collection<String> keys = getByKey("").getKeysByPrefix(prefix, this); LinkedList<TransactionOutPoint> outs = new LinkedList<TransactionOutPoint>(); try { for(String key : keys) { byte[] key_data=Hex.decodeHex(key.toCharArray()); ByteBuffer bb = ByteBuffer.wrap(key_data); bb.order(java.nio.ByteOrder.LITTLE_ENDIAN); bb.position(20); byte[] tx_data = new byte[32]; bb.get(tx_data); int idx=bb.getInt(); Sha256Hash tx_id = new Sha256Hash(tx_data); TransactionOutPoint o = new TransactionOutPoint(jelly.getNetworkParameters(), idx, tx_id); outs.add(o); } } catch(org.apache.commons.codec.DecoderException e) { throw new RuntimeException(e); } return outs; } public synchronized Sha256Hash getRootHash(Sha256Hash interest_block) { if (!enabled) { byte[] b = new byte[32]; return new Sha256Hash(b); } if (interest_block != null) { synchronized(root_hash_cache) { if (root_hash_cache.containsKey(interest_block)) { return root_hash_cache.get(interest_block); } } } if ((interest_block == null) || (last_added_block_hash == null) || (interest_block.equals(last_added_block_hash))) { Sha256Hash root = getByKey("").getHash("", this); if (DEBUG) debug_out.println("Root is now: " + root); return root; } byte[] b = new byte[32]; return new Sha256Hash(b); } public static int commonLength(String a, String b) { int max = Math.min(a.length(), b.length()); int same = 0; for(int i=0; i<max; i++) { if (a.charAt(i) == b.charAt(i)) same++; else break; } if (same % 2 == 1) same return same; } public static Sha256Hash hashThings(String skip, Collection<Sha256Hash> hash_list) { try { if (DEBUG) debug_out.print("hash("); MessageDigest md = MessageDigest.getInstance("SHA-256"); if ((skip != null) && (skip.length() > 0)) { byte[] skipb = Hex.decodeHex(skip.toCharArray()); md.update(skipb); if (DEBUG) { debug_out.print("skip:"); debug_out.print(skip); debug_out.print(' '); } } for(Sha256Hash h : hash_list) { md.update(h.getBytes()); if (DEBUG) { debug_out.print(h); debug_out.print(" "); } } if (DEBUG) debug_out.print(") - "); byte[] pass = md.digest(); md = MessageDigest.getInstance("SHA-256"); md.update(pass); Sha256Hash out = new Sha256Hash(md.digest()); if (DEBUG) debug_out.println(out); return out; } catch(java.security.NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch(org.apache.commons.codec.DecoderException e) { throw new RuntimeException(e); } } public void notifyBlock(boolean wait_for_it, Sha256Hash wait_for_block) { synchronized(block_notify) { block_notify.notifyAll(); } if (wait_for_it) { long end_wait = System.currentTimeMillis() + 15000; while(end_wait > System.currentTimeMillis()) { long wait_tm = end_wait - System.currentTimeMillis(); if (wait_tm > 0) { try { synchronized(root_hash_cache) { if (root_hash_cache.containsKey(wait_for_block)) return; } synchronized(block_done_notify) { block_done_notify.wait(wait_tm); } } catch(Throwable t){} } } } } public static Sha256Hash getHashFromKey(String key) { String hash = key.substring(40, 40+64); return new Sha256Hash(hash); } public static String getKey(byte[] publicKey, Sha256Hash tx_id, int idx) { String addr_part = Hex.encodeHexString(publicKey); ByteBuffer bb = ByteBuffer.allocate(4); bb.order(java.nio.ByteOrder.LITTLE_ENDIAN); bb.putInt(idx); String idx_str = Hex.encodeHexString(bb.array()); String key = addr_part + tx_id + idx_str; return key; } public String getKeyForInput(TransactionInput in) { if (in.isCoinBase()) return null; try { byte[] public_key=null; Address a = in.getFromAddress(); public_key = a.getHash160(); return getKey(public_key, in.getOutpoint().getHash(), (int)in.getOutpoint().getIndex()); } catch(ScriptException e) { //Lets try this the other way try { TransactionOutPoint out_p = in.getOutpoint(); Transaction src_tx = tx_util.getTransaction(out_p.getHash()); TransactionOutput out = src_tx.getOutput((int)out_p.getIndex()); return getKeyForOutput(out, (int)out_p.getIndex()); } catch(ScriptException e2) { return null; } } } public static String getPrefixForAddress(Address a) { byte[] public_key=a.getHash160(); return Hex.encodeHexString(public_key); } public static byte[] getPublicKeyForTxOut(TransactionOutput out, NetworkParameters params) { byte[] public_key=null; Script script = null; try { script = out.getScriptPubKey(); if (script.isSentToRawPubKey()) { byte[] key = out.getScriptPubKey().getPubKey(); byte[] address_bytes = org.bitcoinj.core.Utils.sha256hash160(key); public_key = address_bytes; } else { Address a = script.getToAddress(params); public_key = a.getHash160(); } } catch(ScriptException e) { public_key = figureOutStrange(script, out, params); } return public_key; } public static byte[] figureOutStrange(Script script, TransactionOutput out, NetworkParameters params) { if (script == null) return null; //org.bitcoinj.core.Utils.sha256hash160 List<ScriptChunk> chunks = script.getChunks(); /*System.out.println("STRANGE: " + out.getParentTransaction().getHash() + " - has strange chunks " + chunks.size()); for(int i =0; i<chunks.size(); i++) { System.out.print("Chunk " + i + " "); System.out.print(Hex.encodeHex(chunks.get(i).data)); System.out.println(" " + getOpCodeName(chunks.get(i).data[0])); }*/ //Remember, java bytes are signed because hate //System.out.println(out); //System.out.println(script); if (chunks.size() == 6) { if (chunks.get(0).equalsOpCode(OP_DUP)) if (chunks.get(1).equalsOpCode(OP_HASH160)) if (chunks.get(3).equalsOpCode(OP_EQUALVERIFY)) if (chunks.get(4).equalsOpCode(OP_CHECKSIG)) if (chunks.get(5).equalsOpCode(OP_NOP)) if (chunks.get(2).isPushData()) if (chunks.get(2).data.length == 20) { return chunks.get(2).data; } } /*if ((chunks.size() == 6) && (chunks.get(2).data.length == 20)) { for(int i=0; i<6; i++) { if (chunks.get(i) == null) return null; if (chunks.get(i).data == null) return null; if (i != 2) { if (chunks.get(i).data.length != 1) return null; } } if (chunks.get(0).data[0] == OP_DUP) if ((int)(chunks.get(1).data[0] & 0xFF) == OP_HASH160) if ((int)(chunks.get(3).data[0] & 0xFF) == OP_EQUALVERIFY) if ((int)(chunks.get(4).data[0] & 0xFF) == OP_CHECKSIG) if (chunks.get(5).data[0] == OP_NOP) { return chunks.get(2).data; } }*/ return null; } public String getKeyForOutput(TransactionOutput out, int idx) { byte[] public_key = getPublicKeyForTxOut(out, params); if (public_key == null) return null; return getKey(public_key, out.getParentTransaction().getHash(), idx); } public class UtxoMgrThread extends Thread { private BlockChainCache block_chain_cache; public UtxoMgrThread() { setName("UtxoMgrThread"); setDaemon(true); block_chain_cache = jelly.getBlockChainCache(); } public void run() { recover(); while(true) { while(catchup()){} waitForBlocks(); } } private void recover() { UtxoStatus status = getUtxoState(); if (!status.isConsistent()) { Sha256Hash start = status.getPrevBlockHash(); Sha256Hash end = status.getBlockHash(); last_flush_block_hash = start; jelly.getEventLog().alarm("UTXO inconsistent, attempting recovery from " + start + " to " + end); LinkedList<Sha256Hash> recover_block_list = new LinkedList<Sha256Hash>(); Sha256Hash ptr = end; while(!ptr.equals(start)) { recover_block_list.addFirst(ptr); //System.out.println("Getting prev of : " + ptr); ptr = jelly.getDB().getBlockStoreMap().get(ptr).getHeader().getPrevBlockHash(); } recover_block_list.addFirst(start); jelly.getEventLog().alarm("UTXO attempting recovery of " + recover_block_list.size() + " blocks"); for(Sha256Hash blk_hash : recover_block_list) { Block b = jelly.getDB().getBlockMap().get(blk_hash).getBlock(jelly.getNetworkParameters()); addBlock(b); } flush(); } else { last_flush_block_hash = status.getBlockHash(); last_added_block_hash = status.getBlockHash(); } } int added_since_flush = 0; long last_flush = 0; private boolean catchup() { while(!block_chain_cache.isBlockInMainChain(last_added_block_hash)) { rollback(); } int curr_height = jelly.getDB().getBlockStoreMap().get(last_added_block_hash).getHeight(); int head_height = jelly.getDB().getBlockStoreMap().get( jelly.getBlockChainCache().getHead()).getHeight(); boolean near_caught_up=caught_up; for(int i=curr_height+1; i<=head_height; i++) { while(jelly.getSpaceLimited()) { try { Thread.sleep(5000); } catch(Throwable t){} } Sha256Hash block_hash = jelly.getBlockChainCache().getBlockHashAtHeight(i); long t1=System.currentTimeMillis(); SerializedBlock sb = jelly.getDB().getBlockMap().get(block_hash); if (sb == null) { try{Thread.sleep(250); return true;}catch(Throwable t){} } caught_up=false; Block b = sb.getBlock(params); long t2=System.currentTimeMillis(); get_block_stat.addDataPoint(t2-t1); if (b.getPrevBlockHash().equals(last_added_block_hash)) { t1=System.currentTimeMillis(); addBlock(b); t2=System.currentTimeMillis(); add_block_stat.addDataPoint(t2-t1); Sha256Hash root_hash = getRootHash(null); synchronized(root_hash_cache) { root_hash_cache.put(block_hash, root_hash); } block_height=i; checkUtxoHash(i, block_hash, root_hash); if ((near_caught_up) && (jelly.isUpToDate())) { jelly.getEventLog().alarm("UTXO added block " + i + " - " + root_hash); } else { jelly.getEventLog().log("UTXO added block " + i + " - " + root_hash); } added_since_flush++; } else { return true; } int flush_mod = 1000; //After the blocks get bigger, flush more often if (block_height > 220000) flush_mod = 100; if (block_height > 320000) flush_mod = 10; if (i % flush_mod == 0) { flush(); added_since_flush=0; last_flush = System.currentTimeMillis(); } } synchronized(block_done_notify) { block_done_notify.notifyAll(); } if ((added_since_flush > 0) && (last_flush +15000L < System.currentTimeMillis())) { flush(); added_since_flush=0; last_flush = System.currentTimeMillis(); } return false; } private void rollback() { jelly.getEventLog().alarm("UTXO rolling back " + last_added_block_hash); Sha256Hash prev = jelly.getDB().getBlockStoreMap().get(last_added_block_hash).getHeader().getPrevBlockHash(); last_flush_block_hash = prev; Block b = jelly.getDB().getBlockMap().get(last_added_block_hash).getBlock(jelly.getNetworkParameters()); rollbackBlock(b); //Setting hashes such that it looks like we are doing prev -> last_added_block_hash //That way on recovery we will re-add the block and then roll back again flush(); last_added_block_hash = prev; } private void waitForBlocks() { caught_up=true; synchronized(block_done_notify) { block_done_notify.notifyAll(); } synchronized(block_notify) { try { block_notify.wait(10000); } catch(InterruptedException e){} } } } private LinkedBlockingQueue<UtxoCheckEntry> check_queue = new LinkedBlockingQueue<UtxoCheckEntry>(4); public class UtxoCheckEntry { int height; Sha256Hash block; Sha256Hash utxo_root; public UtxoCheckEntry(int height, Sha256Hash block, Sha256Hash utxo_root) { this.height = height; this.block = block; this.utxo_root = utxo_root; } } public class UtxoCheckThread extends Thread { String client_name; public UtxoCheckThread() { setName("UtxoCheckThread"); setDaemon(true); client_name = "j_" + StratumConnection.JELECTRUM_VERSION + "_"; if (jelly.getConfig().isSet("irc_advertise_host")) { client_name += jelly.getConfig().get("irc_advertise_host"); } else { client_name += new java.util.Random().nextInt(); } //client_name = "check_file"; } public void run() { while(true) { try { UtxoCheckEntry e = check_queue.take(); String url = "https://jelectrum-1022.appspot.com/utxo?" + "block=" + e.block.toString() + "&utxo=" + e.utxo_root.toString() + "&client="+ client_name; URL u = new URL(url); Scanner scan =new Scanner(u.openStream()); String line = scan.nextLine(); scan.close(); StringTokenizer stok = new StringTokenizer(line, ","); String root_str = stok.nextToken(); if (!root_str.equals("undetermined")) { Sha256Hash concur_root = new Sha256Hash(root_str); int matching = Integer.parseInt(stok.nextToken()); int total = Integer.parseInt(stok.nextToken()); if (!concur_root.equals(e.utxo_root)) { jelly.getEventLog().alarm("UTXO check mismatch at " + e.height + " - me:" + e.utxo_root + " others:" + concur_root + " agreement " + + matching + " of " + total); } else { jelly.getEventLog().log("UTXO check at " + e.height + " - " + concur_root + " - matching " + matching + " of " + total); } } else { jelly.getEventLog().log("UTXO check at " + e.height + " - " + root_str); } } catch(Throwable t) { jelly.getEventLog().alarm("UtxoCheckThread: " + t); t.printStackTrace(); } } } } public static void main(String args[]) throws Exception { String config_path = args[0]; Jelectrum jelly = new Jelectrum(new Config(config_path)); int block_number = Integer.parseInt(args[1]); Sha256Hash block_hash = jelly.getBlockChainCache().getBlockHashAtHeight(block_number); System.out.println("Block hash: " + block_hash); Block b = jelly.getDB().getBlockMap().get(block_hash).getBlock(jelly.getNetworkParameters()); System.out.println("Inspecting " + block_number + " - " + block_hash); int tx_count =0; int out_count =0; for(Transaction tx : b.getTransactions()) { int idx=0; for(TransactionOutput tx_out : tx.getOutputs()) { byte[] pub_key_bytes=getPublicKeyForTxOut(tx_out, jelly.getNetworkParameters()); String public_key = null; if (pub_key_bytes != null) public_key = Hex.encodeHexString(pub_key_bytes); else public_key = "None"; String script_bytes = Hex.encodeHexString(tx_out.getScriptBytes()); String[] cmd=new String[3]; cmd[0]="python"; cmd[1]=jelly.getConfig().get("utxo_check_tool"); cmd[2]=script_bytes; //System.out.println(script_bytes); Process p = Runtime.getRuntime().exec(cmd); Scanner scan = new Scanner(p.getInputStream()); String ele_key = scan.nextLine(); if (!ele_key.equals(public_key)) { System.out.println("Mismatch on " + tx_out.getParentTransaction().getHash() + ":" + idx); System.out.println(" Script: " + script_bytes); System.out.println(" Jelectrum: " + public_key); System.out.println(" Electrum: " + ele_key); } out_count++; idx++; } tx_count++; } System.out.println("TX Count: " + tx_count); System.out.println("Out Count: " + out_count); } }
package jo.alexa.sim.ui.test; import java.awt.BorderLayout; import java.awt.Container; import java.awt.FileDialog; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.List; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import jo.alexa.sim.data.MatchBean; import jo.alexa.sim.logic.MatchLogic; import jo.alexa.sim.ui.TableLayout; import jo.alexa.sim.ui.data.RuntimeBean; import jo.alexa.sim.ui.logic.RuntimeLogic; import jo.alexa.sim.ui.logic.TransactionLogic; public class TestingPanel extends JPanel implements PropertyChangeListener { private static final long serialVersionUID = 2553292711822715257L; private RuntimeBean mRuntime; private JCheckBox mShowInput; private JCheckBox mShowIntent; private JCheckBox mShowOutput; private JCheckBox mShowError; private JCheckBox mShowCards; private JCheckBox mShowReprompt; private JCheckBox mShowVerbose; private JButton mSend; private JButton mStartSession; private JButton mEndSession; private JButton mClear; private JButton mSave; private JButton mLoad; private JTextField mInput; private JTextPane mTranscript; private JTextField mIntent; public TestingPanel(RuntimeBean runtime) { mRuntime = runtime; initInstantiate(); initLayout(); initLink(); doNewSessionID(); doNewHistory(); doNewOpts(); } private void initInstantiate() { mShowInput = new JCheckBox("Inputs"); mShowIntent = new JCheckBox("Intents"); mShowOutput = new JCheckBox("Outputs"); mShowError = new JCheckBox("Errors"); mShowCards = new JCheckBox("Cards"); mShowReprompt = new JCheckBox("Reprompt"); mShowVerbose = new JCheckBox("Misc"); mSend = new JButton("Send"); mSend.setToolTipText("Send an IntentReqeust to the app"); mClear = new JButton("Clear"); mClear.setToolTipText("Clear history"); mStartSession = new JButton("\u25b6"); mStartSession.setToolTipText("Send a LaunchReqeust to the app"); mEndSession = new JButton("\u25a0"); mEndSession.setToolTipText("Send a SessionEndedReqeust to the app"); mSave = new JButton("Save"); mSave.setToolTipText("Save history"); mLoad = new JButton("Load"); mLoad.setToolTipText("Load history"); mInput = new JTextField(40); mIntent = new JTextField(40); mIntent.setEditable(false); mIntent.setToolTipText("This is the intent your text will be translated into"); mTranscript = new JTextPane(); mTranscript.setContentType("text/html"); mTranscript.setEditable(false); } private void initLayout() { setLayout(new BorderLayout()); add("Center", new JScrollPane(mTranscript)); JPanel inputBar = new JPanel(); add("South", inputBar); inputBar.setLayout(new TableLayout()); inputBar.add("1,1", new JLabel("Say:")); inputBar.add("+,. fill=h", mInput); inputBar.add("+,.", mSend); inputBar.add("+,.", mStartSession); inputBar.add("+,.", mEndSession); inputBar.add("+,.", mClear); inputBar.add("1,+", new JLabel("")); inputBar.add("+,. fill=h", mIntent); inputBar.add("+,.", new JLabel("")); inputBar.add("+,.", mSave); inputBar.add("+,.", mLoad); inputBar.add("+,.", new JLabel("")); JPanel optionBar = new JPanel(); add("North", optionBar); optionBar.setLayout(new FlowLayout()); optionBar.add(mShowInput); optionBar.add(mShowIntent); optionBar.add(mShowOutput); optionBar.add(mShowError); optionBar.add(mShowCards); optionBar.add(mShowReprompt); optionBar.add(mShowVerbose); } private void initLink() { mSend.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doSend(); } }); mClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doClear(); } }); mStartSession.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doStart(); } }); mEndSession.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doEnd(); } }); mInput.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent arg0) { doInputUpdate(); } }); mInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doSend(); } }); mShowInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RuntimeLogic.toggleShowInput(mRuntime); } }); mShowIntent.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RuntimeLogic.toggleShowIntent(mRuntime); } }); mShowOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RuntimeLogic.toggleShowOutput(mRuntime); } }); mShowError.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RuntimeLogic.toggleShowError(mRuntime); } }); mShowCards.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RuntimeLogic.toggleShowCards(mRuntime); } }); mShowReprompt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RuntimeLogic.toggleShowReprompt(mRuntime); } }); mShowVerbose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RuntimeLogic.toggleShowVerbose(mRuntime); } }); mSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doSave(); } }); mLoad.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doLoad(); } }); mRuntime.addPropertyChangeListener(this); mRuntime.getApp().addPropertyChangeListener(this); } private void doSend() { RuntimeLogic.send(mRuntime, mInput.getText()); mInput.selectAll(); mInput.requestFocus(); } private void doClear() { RuntimeLogic.clearHistory(mRuntime); } private void doStart() { RuntimeLogic.startSession(mRuntime); } private void doEnd() { // TODO: update reason from UI RuntimeLogic.endSession(mRuntime, "USER_INITIATED"); } private void doSave() { FileDialog fd = new FileDialog(getFrame(), "Save History File", FileDialog.SAVE); fd.setDirectory(RuntimeLogic.getProp("history.file.dir")); fd.setFile(RuntimeLogic.getProp("history.file.file")); fd.setVisible(true); if (fd.getDirectory() == null) return; String historyFile = fd.getDirectory()+System.getProperty("file.separator")+fd.getFile(); if ((historyFile == null) || (historyFile.length() == 0)) return; try { RuntimeLogic.saveHistory(mRuntime, new File(historyFile)); RuntimeLogic.setProp("history.file.dir", fd.getDirectory()); RuntimeLogic.setProp("history.file.file", fd.getFile()); } catch (IOException e) { JOptionPane.showMessageDialog(this, e.getLocalizedMessage(), "Error reading "+historyFile, JOptionPane.ERROR_MESSAGE); } } private void doLoad() { FileDialog fd = new FileDialog(getFrame(), "Load History File", FileDialog.LOAD); fd.setDirectory(RuntimeLogic.getProp("history.file.dir")); fd.setFile(RuntimeLogic.getProp("history.file.file")); fd.setVisible(true); if (fd.getDirectory() == null) return; String historyFile = fd.getDirectory()+System.getProperty("file.separator")+fd.getFile(); if ((historyFile == null) || (historyFile.length() == 0)) return; try { RuntimeLogic.loadHistory(mRuntime, new File(historyFile)); RuntimeLogic.setProp("history.file.dir", fd.getDirectory()); RuntimeLogic.setProp("history.file.file", fd.getFile()); } catch (IOException e) { JOptionPane.showMessageDialog(this, e.getLocalizedMessage(), "Error reading "+historyFile, JOptionPane.ERROR_MESSAGE); } } private void doNewSessionID() { if (mRuntime.getApp().getSessionID() == null) { mStartSession.setEnabled(true); mEndSession.setEnabled(false); } else { mStartSession.setEnabled(false); mEndSession.setEnabled(true); } doInputUpdate(); } private void doNewOpts() { mShowInput.setSelected(mRuntime.getRenderOps().isInputText()); mShowIntent.setSelected(mRuntime.getRenderOps().isIntents()); mShowOutput.setSelected(mRuntime.getRenderOps().isOutputText()); mShowError.setSelected(mRuntime.getRenderOps().isErrors()); mShowCards.setSelected(mRuntime.getRenderOps().isCards()); mShowReprompt.setSelected(mRuntime.getRenderOps().isReprompt()); mShowVerbose.setSelected(mRuntime.getRenderOps().isVerbose()); } private void doInputUpdate() { String txt = mInput.getText(); List<MatchBean> matches = MatchLogic.parseInput(mRuntime.getApp(), txt); if (matches.size() == 0) mIntent.setText(""); else mIntent.setText(matches.get(0).toString()); } private void doNewHistory() { String html = "<html><body>" + TransactionLogic.renderAsHTML(mRuntime.getHistory(), mRuntime.getRenderOps()) + "</body></html>"; mTranscript.setText(html); } @Override public void propertyChange(PropertyChangeEvent evt) { if ("sessionID".equals(evt.getPropertyName())) doNewSessionID(); else if ("history".equals(evt.getPropertyName())) doNewHistory(); else if ("renderOps".equals(evt.getPropertyName())) { doNewOpts(); doNewHistory(); } } private Frame getFrame() { for (Container c = getParent(); c != null; c = c.getParent()) if (c instanceof Frame) return (Frame)c; return null; } }
package org.jpos.security; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.javatuples.Pair; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.iso.ISOUtil; import org.jpos.util.*; import org.jpos.util.NameRegistrar.NotFoundException; /** * <p> * Provides base functionality for the actual Security Module Adapter. * </p> * <p> * You adapter needs to override the methods that end with "Impl" * </p> * @author Hani S. Kirollos * @version $Revision$ $Date$ */ public class BaseSMAdapter implements SMAdapter, Configurable, LogSource { protected Logger logger = null; protected String realm = null; protected Configuration cfg; private String name; public BaseSMAdapter () { super(); } public BaseSMAdapter (Configuration cfg, Logger logger, String realm) throws ConfigurationException { super(); setLogger(logger, realm); setConfiguration(cfg); } public void setConfiguration (Configuration cfg) throws ConfigurationException { this.cfg = cfg; } public void setLogger (Logger logger, String realm) { this.logger = logger; this.realm = realm; } public Logger getLogger () { return logger; } public String getRealm () { return realm; } /** * associates this SMAdapter with a name using NameRegistrar * @param name name to register * @see NameRegistrar */ public void setName (String name) { this.name = name; NameRegistrar.register("s-m-adapter." + name, this); } /** * @return this SMAdapter's name ("" if no name was set) */ public String getName () { return this.name; } /** * @param name * @return SMAdapter instance with given name. * @throws NotFoundException * @see NameRegistrar */ public static SMAdapter getSMAdapter (String name) throws NameRegistrar.NotFoundException { return (SMAdapter)NameRegistrar.get("s-m-adapter." + name); } public SecureDESKey generateKey (short keyLength, String keyType) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "Key Length", keyLength), new SimpleMsg("parameter", "Key Type", keyType) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Generate Key", cmdParameters)); SecureDESKey result = null; try { result = generateKeyImpl(keyLength, keyType); evt.addMessage(new SimpleMsg("result", "Generated Key", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public byte[] generateKeyCheckValue (SecureDESKey kd) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "Key with untrusted check value", kd) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Generate Key Check Value", cmdParameters)); byte[] result = null; try { result = generateKeyCheckValueImpl(kd); evt.addMessage(new SimpleMsg("result", "Generated Key Check Value", ISOUtil.hexString(result))); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public SecureDESKey importKey (short keyLength, String keyType, byte[] encryptedKey, SecureDESKey kek, boolean checkParity) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "Key Length", keyLength), new SimpleMsg("parameter", "Key Type", keyType), new SimpleMsg("parameter", "Encrypted Key", encryptedKey), new SimpleMsg("parameter", "Key-Encrypting Key", kek), new SimpleMsg("parameter", "Check Parity", checkParity) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Import Key", cmdParameters)); SecureDESKey result = null; try { result = importKeyImpl(keyLength, keyType, encryptedKey, kek, checkParity); evt.addMessage(new SimpleMsg("result", "Imported Key", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public byte[] exportKey (SecureDESKey key, SecureDESKey kek) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "Key", key), new SimpleMsg("parameter", "Key-Encrypting Key", kek), }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Export Key", cmdParameters)); byte[] result = null; try { result = exportKeyImpl(key, kek); evt.addMessage(new SimpleMsg("result", "Exported Key", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN encryptPIN (String pin, String accountNumber, boolean extract) throws SMException { accountNumber = extract ? EncryptedPIN.extractAccountNumberPart(accountNumber) : accountNumber; SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "clear pin", pin), new SimpleMsg("parameter", "account number", accountNumber) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Encrypt Clear PIN", cmdParameters)); EncryptedPIN result = null; try { result = encryptPINImpl(pin, accountNumber); evt.addMessage(new SimpleMsg("result", "PIN under LMK", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN encryptPIN (String pin, String accountNumber) throws SMException { return encryptPIN(pin, accountNumber, true); } public String decryptPIN (EncryptedPIN pinUnderLmk) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "PIN under LMK", pinUnderLmk), }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Decrypt PIN", cmdParameters)); String result = null; try { result = decryptPINImpl(pinUnderLmk); evt.addMessage(new SimpleMsg("result", "clear PIN", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN importPIN (EncryptedPIN pinUnderKd1, SecureDESKey kd1) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1), new SimpleMsg("parameter", "Data Key 1", kd1), }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Import PIN", cmdParameters)); EncryptedPIN result = null; try { result = importPINImpl(pinUnderKd1, kd1); evt.addMessage(new SimpleMsg("result", "PIN under LMK", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN translatePIN (EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1), new SimpleMsg("parameter", "Data Key 1", kd1), new SimpleMsg("parameter", "Data Key 2", kd2), new SimpleMsg("parameter", "Destination PIN Block Format", destinationPINBlockFormat) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Translate PIN from Data Key 1 to Data Key 2", cmdParameters)); EncryptedPIN result = null; try { result = translatePINImpl(pinUnderKd1, kd1, kd2, destinationPINBlockFormat); evt.addMessage(new SimpleMsg("result", "PIN under Data Key 2", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN importPIN (EncryptedPIN pinUnderDuk, KeySerialNumber ksn, SecureDESKey bdk) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "PIN under Derived Unique Key", pinUnderDuk), new SimpleMsg("parameter", "Key Serial Number", ksn), new SimpleMsg("parameter", "Base Derivation Key", bdk) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Import PIN", cmdParameters)); EncryptedPIN result = null; try { result = importPINImpl(pinUnderDuk, ksn, bdk); evt.addMessage(new SimpleMsg("result", "PIN under LMK", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN translatePIN (EncryptedPIN pinUnderDuk, KeySerialNumber ksn, SecureDESKey bdk, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "PIN under Derived Unique Key", pinUnderDuk), new SimpleMsg("parameter", "Key Serial Number", ksn), new SimpleMsg("parameter", "Base Derivation Key", bdk), new SimpleMsg("parameter", "Data Key 2", kd2), new SimpleMsg("parameter", "Destination PIN Block Format", destinationPINBlockFormat) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Translate PIN", cmdParameters)); EncryptedPIN result = null; try { result = translatePINImpl(pinUnderDuk, ksn, bdk, kd2, destinationPINBlockFormat); evt.addMessage(new SimpleMsg("result", "PIN under Data Key 2", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN exportPIN (EncryptedPIN pinUnderLmk, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "PIN under LMK", pinUnderLmk), new SimpleMsg("parameter", "Data Key 2", kd2), new SimpleMsg("parameter", "Destination PIN Block Format", destinationPINBlockFormat) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Export PIN", cmdParameters)); EncryptedPIN result = null; try { result = exportPINImpl(pinUnderLmk, kd2, destinationPINBlockFormat); evt.addMessage(new SimpleMsg("result", "PIN under Data Key 2", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public EncryptedPIN generatePIN(String accountNumber, int pinLen) throws SMException { return generatePIN(accountNumber, pinLen, null); } public EncryptedPIN generatePIN(String accountNumber, int pinLen, List<String> excludes) throws SMException { List<Loggeable> cmdParameters = new ArrayList<Loggeable>(); cmdParameters.add(new SimpleMsg("parameter", "account number", accountNumber)); cmdParameters.add(new SimpleMsg("parameter", "PIN length", pinLen)); if(excludes != null && !excludes.isEmpty()) cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes)); LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Generate PIN", cmdParameters.toArray(new Loggeable[cmdParameters.size()]))); EncryptedPIN result = null; try { result = generatePINImpl(accountNumber, pinLen, excludes); evt.addMessage(new SimpleMsg("result", "Generated PIN", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public String calculatePVV(EncryptedPIN pinUnderLMK, SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx) throws SMException { return calculatePVV(pinUnderLMK, pvkA, pvkB, pvkIdx, null); } public String calculatePVV(EncryptedPIN pinUnderLMK, SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx, List<String> excludes) throws SMException { List<Loggeable> cmdParameters = new ArrayList<Loggeable>(); cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderLMK.getAccountNumber())); cmdParameters.add(new SimpleMsg("parameter", "PIN under LMK", pinUnderLMK)); cmdParameters.add(new SimpleMsg("parameter", "PVK-A", pvkA == null ? "" : pvkA)); cmdParameters.add(new SimpleMsg("parameter", "PVK-B", pvkB == null ? "" : pvkB)); cmdParameters.add(new SimpleMsg("parameter", "PVK index", pvkIdx)); if(excludes != null && !excludes.isEmpty()) cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes)); LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Calculate PVV", cmdParameters.toArray(new Loggeable[cmdParameters.size()]))); String result = null; try { result = calculatePVVImpl(pinUnderLMK, pvkA, pvkB, pvkIdx, excludes); evt.addMessage(new SimpleMsg("result", "Calculated PVV", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public String calculatePVV(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx) throws SMException { return calculatePVV(pinUnderKd1, kd1, pvkA, pvkB, pvkIdx, null); } public String calculatePVV(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx, List<String> excludes) throws SMException { List<Loggeable> cmdParameters = new ArrayList<Loggeable>(); cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber())); cmdParameters.add(new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1)); cmdParameters.add(new SimpleMsg("parameter", "Data Key 1", kd1)); cmdParameters.add(new SimpleMsg("parameter", "PVK-A", pvkA == null ? "" : pvkA)); cmdParameters.add(new SimpleMsg("parameter", "PVK-B", pvkB == null ? "" : pvkB)); cmdParameters.add(new SimpleMsg("parameter", "PVK index", pvkIdx)); if(excludes != null && !excludes.isEmpty()) cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes)); LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Calculate PVV", cmdParameters.toArray(new Loggeable[cmdParameters.size()]))); String result = null; try { result = calculatePVVImpl(pinUnderKd1, kd1, pvkA, pvkB, pvkIdx, excludes); evt.addMessage(new SimpleMsg("result", "Calculated PVV", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public boolean verifyPVV(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvkA, SecureDESKey pvkB, int pvki, String pvv) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber()), new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1), new SimpleMsg("parameter", "Data Key 1", kd1), new SimpleMsg("parameter", "PVK-A", pvkA == null ? "" : pvkA), new SimpleMsg("parameter", "PVK-B", pvkB == null ? "" : pvkB), new SimpleMsg("parameter", "pvki", pvki), new SimpleMsg("parameter", "pvv", pvv) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Verify a PIN Using the VISA Method", cmdParameters)); try { boolean r = verifyPVVImpl(pinUnderKd1, kd1, pvkA, pvkB, pvki, pvv); evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid")); return r; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public String calculateIBMPINOffset(EncryptedPIN pinUnderLmk, SecureDESKey pvk, String decTab, String pinValData, int minPinLen) throws SMException { return calculateIBMPINOffset(pinUnderLmk, pvk, decTab, pinValData, minPinLen, null); } public String calculateIBMPINOffset(EncryptedPIN pinUnderLmk, SecureDESKey pvk, String decTab, String pinValData, int minPinLen, List<String> excludes) throws SMException { List<Loggeable> cmdParameters = new ArrayList<Loggeable>(); cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderLmk.getAccountNumber())); cmdParameters.add(new SimpleMsg("parameter", "PIN under LMK", pinUnderLmk)); cmdParameters.add(new SimpleMsg("parameter", "PVK", pvk)); cmdParameters.add(new SimpleMsg("parameter", "decimalisation table", decTab)); cmdParameters.add(new SimpleMsg("parameter", "PIN validation data", pinValData)); cmdParameters.add(new SimpleMsg("parameter", "minimum PIN length", minPinLen)); if(excludes != null && !excludes.isEmpty()) cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes)); LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Calculate PIN offset", cmdParameters.toArray(new Loggeable[cmdParameters.size()]))); String result = null; try { result = calculateIBMPINOffsetImpl(pinUnderLmk, pvk, decTab, pinValData, minPinLen, excludes); evt.addMessage(new SimpleMsg("result", "Calculated PIN offset", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public String calculateIBMPINOffset(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvk, String decTab, String pinValData, int minPinLen) throws SMException { return calculateIBMPINOffset(pinUnderKd1, kd1, pvk, decTab, pinValData, minPinLen, null); } public String calculateIBMPINOffset(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvk, String decTab, String pinValData, int minPinLen, List<String> excludes) throws SMException { List<Loggeable> cmdParameters = new ArrayList<Loggeable>(); cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber())); cmdParameters.add(new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1)); cmdParameters.add(new SimpleMsg("parameter", "Data Key 1", kd1)); cmdParameters.add(new SimpleMsg("parameter", "PVK", pvk)); cmdParameters.add(new SimpleMsg("parameter", "decimalisation table", decTab)); cmdParameters.add(new SimpleMsg("parameter", "PIN validation data", pinValData)); cmdParameters.add(new SimpleMsg("parameter", "minimum PIN length", minPinLen)); if(excludes != null && !excludes.isEmpty()) cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes)); LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Calculate PIN offset", cmdParameters.toArray(new Loggeable[cmdParameters.size()]))); String result = null; try { result = calculateIBMPINOffsetImpl(pinUnderKd1, kd1, pvk, decTab, pinValData, minPinLen, excludes); evt.addMessage(new SimpleMsg("result", "Calculated PIN offset", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public boolean verifyIBMPINOffset(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvk, String offset, String decTab, String pinValData, int minPinLen) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber()), new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1), new SimpleMsg("parameter", "Data Key 1", kd1), new SimpleMsg("parameter", "PVK", pvk), new SimpleMsg("parameter", "Pin block format", pinUnderKd1.getPINBlockFormat()), new SimpleMsg("parameter", "decimalisation table", decTab), new SimpleMsg("parameter", "PIN validation data", pinValData), new SimpleMsg("parameter", "minimum PIN length", minPinLen), new SimpleMsg("parameter", "offset", offset) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Verify PIN offset", cmdParameters)); try { boolean r = verifyIBMPINOffsetImpl(pinUnderKd1, kd1, pvk, offset, decTab, pinValData, minPinLen); evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid")); return r; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public EncryptedPIN deriveIBMPIN(String accountNo, SecureDESKey pvk, String decTab, String pinValData, int minPinLen, String offset) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "account number", accountNo), new SimpleMsg("parameter", "Offset", offset), new SimpleMsg("parameter", "PVK", pvk), new SimpleMsg("parameter", "Decimalisation table", decTab), new SimpleMsg("parameter", "PIN validation data", pinValData), new SimpleMsg("parameter", "Minimum PIN length", minPinLen) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Derive a PIN Using the IBM Method", cmdParameters)); EncryptedPIN result = null; try { result = deriveIBMPINImpl(accountNo, pvk, decTab, pinValData, minPinLen, offset); evt.addMessage(new SimpleMsg("result", "Derived PIN", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public String calculateCVV(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB, Date expDate, String serviceCode) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "account number", accountNo), new SimpleMsg("parameter", "cvk-a", cvkA == null ? "" : cvkA), new SimpleMsg("parameter", "cvk-b", cvkB == null ? "" : cvkB), new SimpleMsg("parameter", "Exp date", expDate), new SimpleMsg("parameter", "Service code", serviceCode) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Calculate CVV/CVC", cmdParameters)); String result = null; try { result = calculateCVVImpl(accountNo, cvkA, cvkB, expDate, serviceCode); evt.addMessage(new SimpleMsg("result", "Calculated CVV/CVC", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public boolean verifyCVV(String accountNo , SecureDESKey cvkA, SecureDESKey cvkB, String cvv, Date expDate, String serviceCode) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "account number", accountNo), new SimpleMsg("parameter", "cvk-a", cvkA == null ? "" : cvkA), new SimpleMsg("parameter", "cvk-b", cvkB == null ? "" : cvkB), new SimpleMsg("parameter", "CVV/CVC", cvv), new SimpleMsg("parameter", "Exp date", expDate), new SimpleMsg("parameter", "Service code", serviceCode) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Verify CVV/CVC", cmdParameters)); try { boolean r = verifyCVVImpl(accountNo, cvkA, cvkB, cvv, expDate, serviceCode); evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid")); return r; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public boolean verifydCVV(String accountNo, SecureDESKey imkac, String dcvv, Date expDate, String serviceCode, byte[] atc, MKDMethod mkdm) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "account number", accountNo), new SimpleMsg("parameter", "imk-ac", imkac == null ? "" : imkac), new SimpleMsg("parameter", "dCVV", dcvv), new SimpleMsg("parameter", "Exp date", expDate), new SimpleMsg("parameter", "Service code", serviceCode), new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)), new SimpleMsg("parameter", "mkd method", mkdm) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Verify dCVV", cmdParameters)); try { boolean r = verifydCVVImpl(accountNo, imkac, dcvv, expDate, serviceCode, atc, mkdm); evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid")); return r; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } /** * @param imkcvc3 the issuer master key for generating and verifying CVC3 * @param accountNo The account number including BIN and the check digit * @param acctSeqNo account sequence number, 2 decimal digits * @param atc application transactin counter. This is used for ICC Master * Key derivation. A 2 byte value must be supplied. * @param upn unpredictable number. This is used for Session Key Generation * A 4 byte value must be supplied. * @param data track data * @param mkdm ICC Master Key Derivation Method. If {@code null} specified * is assumed {@see MKDMethod#OPTION_A} * @param cvc3 dynamic Card Verification Code 3 * @return * @throws SMException */ public boolean verifyCVC3(SecureDESKey imkcvc3, String accountNo, String acctSeqNo, byte[] atc, byte[] upn, byte[] data, MKDMethod mkdm, String cvc3) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "imk-cvc3", imkcvc3 == null ? "" : imkcvc3), new SimpleMsg("parameter", "account number", accountNo), new SimpleMsg("parameter", "accnt seq no", acctSeqNo), new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)), new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)), new SimpleMsg("parameter", "data", data == null ? "" : ISOUtil.hexString(data)), new SimpleMsg("parameter", "mkd method", mkdm), new SimpleMsg("parameter", "cvc3", cvc3) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Verify CVC3", cmdParameters)); try { boolean r = verifyCVC3Impl( imkcvc3, accountNo, acctSeqNo, atc, upn, data, mkdm, cvc3); evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid")); return r; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public boolean verifyARQC(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac ,String accoutNo, String acctSeqNo, byte[] arqc, byte[] atc ,byte[] upn, byte[] transData) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "mkd method", mkdm), new SimpleMsg("parameter", "skd method", skdm), new SimpleMsg("parameter", "imk-ac", imkac), new SimpleMsg("parameter", "account number", accoutNo), new SimpleMsg("parameter", "accnt seq no", acctSeqNo), new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)), new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)), new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)), new SimpleMsg("parameter", "trans. data", transData == null ? "" : ISOUtil.hexString(transData)) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Verify ARQC/TC/AAC", cmdParameters)); try { boolean r = verifyARQCImpl( mkdm, skdm, imkac, accoutNo, acctSeqNo, arqc, atc, upn, transData); evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid")); return r; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public byte[] generateARPC(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac ,String accoutNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn ,ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "mkd method", mkdm), new SimpleMsg("parameter", "skd method", skdm), new SimpleMsg("parameter", "imk-ac", imkac), new SimpleMsg("parameter", "account number", accoutNo), new SimpleMsg("parameter", "accnt seq no", acctSeqNo), new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)), new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)), new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)), new SimpleMsg("parameter", "arpc gen. method", arpcMethod), new SimpleMsg("parameter", "auth. rc", arc == null ? "" : ISOUtil.hexString(arc)), new SimpleMsg("parameter", "prop auth. data", propAuthData == null ? "" : ISOUtil.hexString(propAuthData)) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Genarate ARPC", cmdParameters)); try { byte[] result = generateARPCImpl( mkdm, skdm, imkac, accoutNo, acctSeqNo ,arqc, atc, upn, arpcMethod, arc, propAuthData ); evt.addMessage(new SimpleMsg("result", "Generated ARPC", result)); return result; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public byte[] verifyARQCGenerateARPC(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac ,String accoutNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn ,byte[] transData, ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "mkd method", mkdm), new SimpleMsg("parameter", "skd method", skdm), new SimpleMsg("parameter", "imk-ac", imkac), new SimpleMsg("parameter", "account number", accoutNo), new SimpleMsg("parameter", "accnt seq no", acctSeqNo), new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)), new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)), new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)), new SimpleMsg("parameter", "trans. data", transData == null ? "" : ISOUtil.hexString(transData)), new SimpleMsg("parameter", "arpc gen. method", arpcMethod), new SimpleMsg("parameter", "auth. rc", arc == null ? "" : ISOUtil.hexString(arc)), new SimpleMsg("parameter", "prop auth. data", propAuthData == null ? "" : ISOUtil.hexString(propAuthData)) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Genarate ARPC", cmdParameters)); try { byte[] result = verifyARQCGenerateARPCImpl( mkdm, skdm, imkac, accoutNo, acctSeqNo, arqc, atc, upn, transData, arpcMethod, arc, propAuthData ); evt.addMessage(new SimpleMsg("result", "ARPC", result == null ? "" : ISOUtil.hexString(result))); return result; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public byte[] generateSM_MAC(MKDMethod mkdm, SKDMethod skdm ,SecureDESKey imksmi, String accountNo, String acctSeqNo ,byte[] atc, byte[] arqc, byte[] data) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "mkd method", mkdm), new SimpleMsg("parameter", "skd method", skdm), new SimpleMsg("parameter", "imk-smi", imksmi), new SimpleMsg("parameter", "account number", accountNo), new SimpleMsg("parameter", "accnt seq no", acctSeqNo), new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)), new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)), new SimpleMsg("parameter", "data", data == null ? "" : ISOUtil.hexString(data)) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Generate Secure Messaging MAC", cmdParameters)); try { byte[] mac = generateSM_MACImpl( mkdm, skdm, imksmi, accountNo, acctSeqNo, atc, arqc, data); evt.addMessage(new SimpleMsg("result", "Generated MAC", mac!=null ? ISOUtil.hexString(mac) : "")); return mac; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public Pair<EncryptedPIN,byte[]> translatePINGenerateSM_MAC(MKDMethod mkdm ,SKDMethod skdm, PaddingMethod padm, SecureDESKey imksmi ,String accountNo, String acctSeqNo, byte[] atc, byte[] arqc ,byte[] data, EncryptedPIN currentPIN, EncryptedPIN newPIN ,SecureDESKey kd1, SecureDESKey imksmc, SecureDESKey imkac ,byte destinationPINBlockFormat) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "mkd method", mkdm), new SimpleMsg("parameter", "skd method", skdm), new SimpleMsg("parameter", "padding method", padm), new SimpleMsg("parameter", "imk-smi", imksmi), new SimpleMsg("parameter", "account number", accountNo), new SimpleMsg("parameter", "accnt seq no", acctSeqNo), new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)), new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)), new SimpleMsg("parameter", "data", data == null ? "" : ISOUtil.hexString(data)), new SimpleMsg("parameter", "Current Encrypted PIN", currentPIN), new SimpleMsg("parameter", "New Encrypted PIN", newPIN), new SimpleMsg("parameter", "Source PIN Encryption Key", kd1), new SimpleMsg("parameter", "imk-smc", imksmc), new SimpleMsg("parameter", "imk-ac", imkac), new SimpleMsg("parameter", "Destination PIN Block Format", destinationPINBlockFormat) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Translate PIN block format and Generate Secure Messaging MAC", cmdParameters)); try { Pair<EncryptedPIN,byte[]> r = translatePINGenerateSM_MACImpl( mkdm, skdm ,padm, imksmi, accountNo, acctSeqNo, atc, arqc, data, currentPIN ,newPIN, kd1, imksmc, imkac, destinationPINBlockFormat); SimpleMsg[] cmdResults = { new SimpleMsg("result", "Translated PIN block", r.getValue0()), new SimpleMsg("result", "Generated MAC", r.getValue1() == null ? "" : ISOUtil.hexString(r.getValue1())) }; evt.addMessage(new SimpleMsg("results", "Complex results", cmdResults)); return r; } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } public byte[] generateCBC_MAC (byte[] data, SecureDESKey kd) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "data", data), new SimpleMsg("parameter", "data key", kd), }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Generate CBC-MAC", cmdParameters)); byte[] result = null; try { result = generateCBC_MACImpl(data, kd); evt.addMessage(new SimpleMsg("result", "CBC-MAC", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public byte[] generateEDE_MAC (byte[] data, SecureDESKey kd) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "data", data), new SimpleMsg("parameter", "data key", kd), }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Generate EDE-MAC", cmdParameters)); byte[] result = null; try { result = generateEDE_MACImpl(data, kd); evt.addMessage(new SimpleMsg("result", "EDE-MAC", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public SecureDESKey translateKeyFromOldLMK (SecureDESKey kd) throws SMException { SimpleMsg[] cmdParameters = { new SimpleMsg("parameter", "Key under old LMK", kd) }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Translate Key from old to new LMK", cmdParameters)); SecureDESKey result = null; try { result = translateKeyFromOldLMKImpl(kd); evt.addMessage(new SimpleMsg("result", "Translated Key under new LMK", result)); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } return result; } public void eraseOldLMK () throws SMException { SimpleMsg[] cmdParameters = { }; LogEvent evt = new LogEvent(this, "s-m-operation"); evt.addMessage(new SimpleMsg("command", "Erase the key change storage", cmdParameters)); try { eraseOldLMKImpl(); } catch (Exception e) { evt.addMessage(e); throw e instanceof SMException ? (SMException) e : new SMException(e); } finally { Logger.log(evt); } } /** * Your SMAdapter should override this method if it has this functionality * @param keyLength * @param keyType * @return generated key * @throws SMException */ protected SecureDESKey generateKeyImpl (short keyLength, String keyType) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param kd * @return generated Key Check Value * @throws SMException */ protected byte[] generateKeyCheckValueImpl (SecureDESKey kd) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param keyLength * @param keyType * @param encryptedKey * @param kek * @return imported key * @throws SMException */ protected SecureDESKey importKeyImpl (short keyLength, String keyType, byte[] encryptedKey, SecureDESKey kek, boolean checkParity) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param key * @param kek * @return exported key * @throws SMException */ protected byte[] exportKeyImpl (SecureDESKey key, SecureDESKey kek) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pin * @param accountNumber * @return encrypted PIN under LMK * @throws SMException */ protected EncryptedPIN encryptPINImpl (String pin, String accountNumber) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderLmk * @return clear pin as entered by card holder * @throws SMException */ protected String decryptPINImpl (EncryptedPIN pinUnderLmk) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderKd1 * @param kd1 * @return imported pin * @throws SMException */ protected EncryptedPIN importPINImpl (EncryptedPIN pinUnderKd1, SecureDESKey kd1) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderKd1 * @param kd1 * @param kd2 * @param destinationPINBlockFormat * @return translated pin * @throws SMException */ protected EncryptedPIN translatePINImpl (EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderDuk * @param ksn * @param bdk * @return imported pin * @throws SMException */ protected EncryptedPIN importPINImpl (EncryptedPIN pinUnderDuk, KeySerialNumber ksn, SecureDESKey bdk) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderDuk * @param ksn * @param bdk * @param kd2 * @param destinationPINBlockFormat * @return translated pin * @throws SMException */ protected EncryptedPIN translatePINImpl (EncryptedPIN pinUnderDuk, KeySerialNumber ksn, SecureDESKey bdk, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderLmk * @param kd2 * @param destinationPINBlockFormat * @return exported pin * @throws SMException */ protected EncryptedPIN exportPINImpl (EncryptedPIN pinUnderLmk, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param accountNumber * @param pinLen * @param excludes * @return generated PIN under LMK * @throws SMException */ protected EncryptedPIN generatePINImpl(String accountNumber, int pinLen, List<String> excludes) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderLMK * @param pvkA * @param pvkB * @param pvkIdx * @return PVV (VISA PIN Verification Value) * @throws SMException */ protected String calculatePVVImpl(EncryptedPIN pinUnderLMK, SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx, List<String> excludes) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderKd1 * @param kd1 * @param pvkA * @param pvkB * @param pvkIdx * @return PVV (VISA PIN Verification Value) * @throws SMException */ protected String calculatePVVImpl(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx, List<String> excludes) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderKd * @param kd * @param pvkA * @param pvkB * @param pvki * @param pvv * @return * @throws SMException */ protected boolean verifyPVVImpl(EncryptedPIN pinUnderKd, SecureDESKey kd, SecureDESKey pvkA, SecureDESKey pvkB, int pvki, String pvv) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderLmk * @param pvk * @param decTab * @param pinValData * @param minPinLen * @param excludes * @return IBM PIN Offset * @throws SMException */ protected String calculateIBMPINOffsetImpl(EncryptedPIN pinUnderLmk, SecureDESKey pvk, String decTab, String pinValData, int minPinLen, List<String> excludes) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderKd1 * @param kd1 * @param pvk * @param decTab * @param pinValData * @param minPinLen * @param excludes * @return IBM PIN Offset * @throws SMException */ protected String calculateIBMPINOffsetImpl(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvk, String decTab, String pinValData, int minPinLen, List<String> excludes) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param pinUnderKd * @param kd * @param pvk * @param offset * @param decTab * @param pinValData * @param minPinLen * @return * @throws SMException */ protected boolean verifyIBMPINOffsetImpl(EncryptedPIN pinUnderKd, SecureDESKey kd ,SecureDESKey pvk, String offset, String decTab ,String pinValData, int minPinLen) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param accountNo * @param pvk * @param decTab * @param pinValData * @param minPinLen * @param offset * @return derived PIN under LMK * @throws SMException */ protected EncryptedPIN deriveIBMPINImpl(String accountNo, SecureDESKey pvk ,String decTab, String pinValData, int minPinLen ,String offset) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param accountNo * @param cvkA * @param cvkB * @param expDate * @param serviceCode * @return Card Verification Code/Value * @throws SMException */ protected String calculateCVVImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB, Date expDate, String serviceCode) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param accountNo * @param cvkA * @param cvkB * @param cvv * @param expDate * @param serviceCode * @return true if CVV/CVC is falid or false if not * @throws SMException */ protected boolean verifyCVVImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB, String cvv, Date expDate, String serviceCode) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param accountNo * @param imkac * @param dcvv * @param expDate * @param serviceCode * @param atc * @param mkdm * @return * @throws SMException */ protected boolean verifydCVVImpl(String accountNo, SecureDESKey imkac, String dcvv, Date expDate, String serviceCode, byte[] atc, MKDMethod mkdm) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param imkcvc3 * @param accountNo * @param acctSeqNo * @param atc * @param upn * @param data * @param mkdm * @param cvc3 * @return * @throws SMException */ protected boolean verifyCVC3Impl(SecureDESKey imkcvc3, String accountNo, String acctSeqNo, byte[] atc, byte[] upn, byte[] data, MKDMethod mkdm, String cvc3) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param mkdm * @param skdm * @param imkac * @param accountNo * @param acctSeqNo * @param arqc * @param atc * @param upn * @param transData * @return true if ARQC/TC/AAC is falid or false if not * @throws SMException */ protected boolean verifyARQCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac ,String accountNo, String acctSeqNo, byte[] arqc, byte[] atc ,byte[] upn, byte[] transData) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param mkdm * @param skdm * @param imkac * @param accountNo * @param acctSeqNo * @param arqc * @param atc * @param upn * @param arpcMethod * @param arc * @param propAuthData * @return calculated ARPC * @throws SMException */ protected byte[] generateARPCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac ,String accountNo, String acctSeqNo, byte[] arqc, byte[] atc ,byte[] upn, ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param mkdm * @param skdm * @param imkac * @param accountNo * @param acctSeqNo * @param arqc * @param atc * @param upn * @param arpcMethod * @param arc * @param propAuthData * @return calculated ARPC * @throws SMException */ protected byte[] verifyARQCGenerateARPCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac ,String accountNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn ,byte[] transData, ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param mkdm * @param skdm * @param imksmi * @param accountNo * @param acctSeqNo * @param atc * @param arqc * @param data * @return generated 8 bytes MAC * @throws SMException */ protected byte[] generateSM_MACImpl(MKDMethod mkdm, SKDMethod skdm ,SecureDESKey imksmi, String accountNo, String acctSeqNo ,byte[] atc, byte[] arqc, byte[] data) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param mkdm * @param skdm * @param padm * @param imksmi * @param accountNo * @param acctSeqNo * @param atc * @param arqc * @param data * @param currentPIN * @param newPIN * @param kd1 * @param imksmc * @param imkac * @param destinationPINBlockFormat * @return Pair of values, encrypted PIN and 8 bytes MAC * @throws SMException */ protected Pair<EncryptedPIN,byte[]> translatePINGenerateSM_MACImpl(MKDMethod mkdm ,SKDMethod skdm, PaddingMethod padm, SecureDESKey imksmi ,String accountNo, String acctSeqNo, byte[] atc, byte[] arqc ,byte[] data, EncryptedPIN currentPIN, EncryptedPIN newPIN ,SecureDESKey kd1, SecureDESKey imksmc, SecureDESKey imkac ,byte destinationPINBlockFormat) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param data * @param kd * @return generated CBC-MAC * @throws SMException */ protected byte[] generateCBC_MACImpl (byte[] data, SecureDESKey kd) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Your SMAdapter should override this method if it has this functionality * @param data * @param kd * @return generated EDE-MAC * @throws SMException */ protected byte[] generateEDE_MACImpl (byte[] data, SecureDESKey kd) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Translate key from encryption under the LMK held in key change storage * to encryption under a new LMK. * * @param kd the key encrypted under old LMK * @return key encrypted under the new LMK * @throws SMException if the parity of the imported key is not adjusted AND checkParity = true */ protected SecureDESKey translateKeyFromOldLMKImpl (SecureDESKey kd) throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } /** * Erase the key change storage area of memory * * It is recommended that this command is used after keys stored * by the Host have been translated from old to new LMKs. * * @throws SMException */ protected void eraseOldLMKImpl () throws SMException { throw new SMException("Operation not supported in: " + this.getClass().getName()); } }
package org.postgresql.test.jdbc4; import org.postgresql.geometric.PGbox; import org.postgresql.test.TestUtil; import org.postgresql.test.jdbc2.BaseTest4; import org.postgresql.util.PGobject; import org.postgresql.util.PGtokenizer; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; @RunWith(Parameterized.class) public class ArrayTest extends BaseTest4 { private Connection _conn; public ArrayTest(BinaryMode binaryMode) { setBinaryMode(binaryMode); } @Parameterized.Parameters(name = "binary = {0}") public static Iterable<Object[]> data() { Collection<Object[]> ids = new ArrayList<Object[]>(); for (BinaryMode binaryMode : BinaryMode.values()) { ids.add(new Object[]{binaryMode}); } return ids; } public void setUp() throws Exception { super.setUp(); _conn = con; TestUtil.createTable(_conn, "arrtest", "intarr int[], decarr decimal(2,1)[], strarr text[], uuidarr uuid[], floatarr float8[]"); TestUtil.createTable(_conn, "arrcompprnttest", "id serial, name character(10)"); TestUtil.createTable(_conn, "arrcompchldttest", "id serial, name character(10), description character varying, parent integer"); TestUtil.createTable(_conn, "\"CorrectCasing\"", "id serial"); TestUtil.createTable(_conn, "\"Evil.Table\"", "id serial"); } public void tearDown() throws SQLException { TestUtil.dropTable(_conn, "arrtest"); TestUtil.dropTable(_conn, "arrcompprnttest"); TestUtil.dropTable(_conn, "arrcompchldttest"); TestUtil.dropTable(_conn, "\"CorrectCasing\""); super.tearDown(); } @Test public void testCreateArrayOfInt() throws SQLException { PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::int[]"); Integer in[] = new Integer[3]; in[0] = 0; in[1] = -1; in[2] = 2; pstmt.setArray(1, _conn.createArrayOf("int4", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Integer out[] = (Integer[]) arr.getArray(); Assert.assertEquals(3, out.length); Assert.assertEquals(0, out[0].intValue()); Assert.assertEquals(-1, out[1].intValue()); Assert.assertEquals(2, out[2].intValue()); } @Test public void testCreateArrayOfMultiString() throws SQLException { PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::text[]"); String in[][] = new String[2][2]; in[0][0] = "a"; in[0][1] = ""; in[1][0] = "\\"; in[1][1] = "\"\\'z"; pstmt.setArray(1, _conn.createArrayOf("text", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); String out[][] = (String[][]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertEquals(2, out[0].length); Assert.assertEquals("a", out[0][0]); Assert.assertEquals("", out[0][1]); Assert.assertEquals("\\", out[1][0]); Assert.assertEquals("\"\\'z", out[1][1]); } @Test public void testCreateArrayWithNonStandardDelimiter() throws SQLException { PGbox in[] = new PGbox[2]; in[0] = new PGbox(1, 2, 3, 4); in[1] = new PGbox(5, 6, 7, 8); PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::box[]"); pstmt.setArray(1, _conn.createArrayOf("box", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); ResultSet arrRs = arr.getResultSet(); Assert.assertTrue(arrRs.next()); Assert.assertEquals(in[0], arrRs.getObject(2)); Assert.assertTrue(arrRs.next()); Assert.assertEquals(in[1], arrRs.getObject(2)); Assert.assertFalse(arrRs.next()); } @Test public void testCreateArrayOfNull() throws SQLException { if (!TestUtil.haveMinimumServerVersion(_conn, "8.2")) { return; } String sql = "SELECT ?"; // We must provide the type information for V2 protocol if (TestUtil.isProtocolVersion(_conn, 2)) { sql = "SELECT ?::int8[]"; } PreparedStatement pstmt = _conn.prepareStatement(sql); String in[] = new String[2]; in[0] = null; in[1] = null; pstmt.setArray(1, _conn.createArrayOf("int8", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Long out[] = (Long[]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertNull(out[0]); Assert.assertNull(out[1]); } @Test public void testCreateEmptyArrayOfIntViaAlias() throws SQLException { PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::int[]"); Integer in[] = new Integer[0]; pstmt.setArray(1, _conn.createArrayOf("integer", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Integer out[] = (Integer[]) arr.getArray(); Assert.assertEquals(0, out.length); ResultSet arrRs = arr.getResultSet(); Assert.assertFalse(arrRs.next()); } @Test public void testCreateArrayWithoutServer() throws SQLException { String in[][] = new String[2][2]; in[0][0] = "a"; in[0][1] = ""; in[1][0] = "\\"; in[1][1] = "\"\\'z"; Array arr = _conn.createArrayOf("varchar", in); String out[][] = (String[][]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertEquals(2, out[0].length); Assert.assertEquals("a", out[0][0]); Assert.assertEquals("", out[0][1]); Assert.assertEquals("\\", out[1][0]); Assert.assertEquals("\"\\'z", out[1][1]); } @Test public void testCreatePrimitiveArray() throws SQLException { double in[][] = new double[2][2]; in[0][0] = 3.5; in[0][1] = -4.5; in[1][0] = 10.0 / 3; in[1][1] = 77; Array arr = _conn.createArrayOf("float8", in); Double out[][] = (Double[][]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertEquals(2, out[0].length); Assert.assertEquals(3.5, out[0][0], 0.00001); Assert.assertEquals(-4.5, out[0][1], 0.00001); Assert.assertEquals(10.0 / 3, out[1][0], 0.00001); Assert.assertEquals(77, out[1][1], 0.00001); } @Test public void testUUIDArray() throws SQLException { UUID uuid1 = UUID.randomUUID(); UUID uuid2 = UUID.randomUUID(); UUID uuid3 = UUID.randomUUID(); // insert a uuid array, and check PreparedStatement pstmt1 = _conn.prepareStatement("INSERT INTO arrtest(uuidarr) VALUES (?)"); pstmt1.setArray(1, _conn.createArrayOf("uuid", new UUID[]{uuid1, uuid2, uuid3})); pstmt1.executeUpdate(); PreparedStatement pstmt2 = _conn.prepareStatement("SELECT uuidarr FROM arrtest WHERE uuidarr @> ?"); pstmt2.setObject(1, _conn.createArrayOf("uuid", new UUID[]{uuid1}), Types.OTHER); ResultSet rs = pstmt2.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); UUID out[] = (UUID[]) arr.getArray(); Assert.assertEquals(3, out.length); Assert.assertEquals(uuid1, out[0]); Assert.assertEquals(uuid2, out[1]); Assert.assertEquals(uuid3, out[2]); // concatenate a uuid, and check UUID uuid4 = UUID.randomUUID(); PreparedStatement pstmt3 = _conn.prepareStatement("UPDATE arrtest SET uuidarr = uuidarr || ? WHERE uuidarr @> ?"); pstmt3.setObject(1, uuid4, Types.OTHER); pstmt3.setArray(2, _conn.createArrayOf("uuid", new UUID[]{uuid1})); pstmt3.executeUpdate(); pstmt2.setObject(1, _conn.createArrayOf("uuid", new UUID[]{uuid4}), Types.OTHER); rs = pstmt2.executeQuery(); Assert.assertTrue(rs.next()); arr = rs.getArray(1); out = (UUID[]) arr.getArray(); Assert.assertEquals(4, out.length); Assert.assertEquals(uuid1, out[0]); Assert.assertEquals(uuid2, out[1]); Assert.assertEquals(uuid3, out[2]); Assert.assertEquals(uuid4, out[3]); } @Test public void testSetObjectFromJavaArray() throws SQLException { String[] strArray = new String[]{"a", "b", "c"}; PreparedStatement pstmt = _conn.prepareStatement("INSERT INTO arrtest(strarr) VALUES (?)"); // Incorrect, but commonly attempted by many ORMs: try { pstmt.setObject(1, strArray, Types.ARRAY); pstmt.executeUpdate(); Assert.fail("setObject() with a Java array parameter and Types.ARRAY shouldn't succeed"); } catch (org.postgresql.util.PSQLException ex) { // Expected failure. } // Also incorrect, but commonly attempted by many ORMs: try { pstmt.setObject(1, strArray); pstmt.executeUpdate(); Assert.fail("setObject() with a Java array parameter and no Types argument shouldn't succeed"); } catch (org.postgresql.util.PSQLException ex) { // Expected failure. } // Correct way, though the use of "text" as a type is non-portable. // Only supported for JDK 1.6 and JDBC4 Array sqlArray = _conn.createArrayOf("text", strArray); pstmt.setArray(1, sqlArray); pstmt.executeUpdate(); pstmt.close(); } @Test public void testGetArrayOfComposites() throws SQLException { PreparedStatement insert_parent_pstmt = _conn.prepareStatement("INSERT INTO arrcompprnttest (name) " + "VALUES ('aParent');"); insert_parent_pstmt.execute(); String[] children = { "November 5, 2013", "\"A Book Title\"", "4\" by 6\"", "5\",3\""}; PreparedStatement insert_children_pstmt = _conn.prepareStatement("INSERT INTO arrcompchldttest (name,description,parent) " + "VALUES ('child1',?,1)," + "('child2',?,1)," + "('child3',?,1)," + "('child4',?,1);"); insert_children_pstmt.setString(1, children[0]); insert_children_pstmt.setString(2, children[1]); insert_children_pstmt.setString(3, children[2]); insert_children_pstmt.setString(4, children[3]); insert_children_pstmt.execute(); PreparedStatement pstmt = _conn.prepareStatement( "SELECT arrcompprnttest.name, " + "array_agg(" + "DISTINCT(arrcompchldttest.id, " + "arrcompchldttest.name, " + "arrcompchldttest.description)) " + "AS children " + "FROM arrcompprnttest " + "LEFT JOIN arrcompchldttest " + "ON (arrcompchldttest.parent = arrcompprnttest.id) " + "WHERE arrcompprnttest.id=? " + "GROUP BY arrcompprnttest.name;"); pstmt.setInt(1, 1); ResultSet rs = pstmt.executeQuery(); Assert.assertNotNull(rs); Assert.assertTrue(rs.next()); Array childrenArray = rs.getArray("children"); Assert.assertNotNull(childrenArray); ResultSet rsChildren = childrenArray.getResultSet(); Assert.assertNotNull(rsChildren); while (rsChildren.next()) { String comp = rsChildren.getString(2); PGtokenizer token = new PGtokenizer(PGtokenizer.removePara(comp), ','); token.remove("\"", "\""); // remove surrounding double quotes if (2 < token.getSize()) { int childID = Integer.parseInt(token.getToken(0)); // remove double quotes escaping with double quotes String value = token.getToken(2).replace("\"\"", "\""); Assert.assertEquals(children[childID - 1], value); } else { Assert.fail("Needs to have 3 tokens"); } } } @Test public void testCasingComposite() throws SQLException { PGobject cc = new PGobject(); cc.setType("\"CorrectCasing\""); cc.setValue("(1)"); Object[] in = new Object[1]; in[0] = cc; Array arr = _conn.createArrayOf("\"CorrectCasing\"", in); PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::\"CorrectCasing\"[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Object[] resArr = (Object[]) rs.getArray(1).getArray(); Assert.assertTrue(resArr[0] instanceof PGobject); PGobject resObj = (PGobject) resArr[0]; Assert.assertEquals("(1)", resObj.getValue()); } @Test public void testCasingBuiltinAlias() throws SQLException { Array arr = _conn.createArrayOf("INT", new Integer[]{1, 2, 3}); PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::INT[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Integer[] resArr = (Integer[]) rs.getArray(1).getArray(); Assert.assertArrayEquals(new Integer[]{1, 2, 3}, resArr); } @Test public void testCasingBuiltinNonAlias() throws SQLException { Array arr = _conn.createArrayOf("INT4", new Integer[]{1, 2, 3}); PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::INT4[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Integer[] resArr = (Integer[]) rs.getArray(1).getArray(); Assert.assertArrayEquals(new Integer[]{1, 2, 3}, resArr); } @Test public void testEvilCasing() throws SQLException { PGobject cc = new PGobject(); cc.setType("\"Evil.Table\""); cc.setValue("(1)"); Object[] in = new Object[1]; in[0] = cc; Array arr = _conn.createArrayOf("\"Evil.Table\"", in); PreparedStatement pstmt = _conn.prepareStatement("SELECT ?::\"Evil.Table\"[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Object[] resArr = (Object[]) rs.getArray(1).getArray(); Assert.assertTrue(resArr[0] instanceof PGobject); PGobject resObj = (PGobject) resArr[0]; Assert.assertEquals("(1)", resObj.getValue()); } @Test public void testToString() throws SQLException { Double[] d = new Double[4]; d[0] = 3.5; d[1] = -4.5; d[2] = null; d[3] = 77.0; Array arr = con.createArrayOf("float8", d); PreparedStatement pstmt = con.prepareStatement("INSERT INTO arrtest(floatarr) VALUES (?)"); ResultSet rs = null; try { pstmt.setArray(1, arr); pstmt.execute(); } finally { TestUtil.closeQuietly(pstmt); } Statement stmt = null; try { stmt = con.createStatement(); rs = stmt.executeQuery("select floatarr from arrtest"); while (rs.next()) { Array doubles = rs.getArray(1); String actual = doubles.toString(); if (actual != null) { // Remove all double quotes. They do not make a difference here. actual = actual.replaceAll("\"", ""); // Replace X.0 with just X actual = actual.replaceAll("\\.0+([^0-9])", "$1"); } Assert.assertEquals("Array.toString should use square braces", "{3.5,-4.5,NULL,77}", actual); } } finally { TestUtil.closeQuietly(rs); TestUtil.closeQuietly(stmt); } } @Test public void nullArray() throws SQLException { Array arr = con.createArrayOf("float8", null); PreparedStatement ps = con.prepareStatement("INSERT INTO arrtest(floatarr) VALUES (?)"); ps.setNull(1, Types.ARRAY, "float8"); ps.execute(); ps.close(); ps = con.prepareStatement("select floatarr from arrtest"); ResultSet rs = ps.executeQuery(); Assert.assertTrue("arrtest should contain a row", rs.next()); Array getArray = rs.getArray(1); Assert.assertNull("null array should return null value on getArray", getArray); Object getObject = rs.getObject(1); Assert.assertNull("null array should return null on getObject", getObject); } }
package gov.nih.nci.eagle.util; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.IntegerValueEnum; public class IntegerEnumResolver { public static <T> T resolveEnum(Class<T> enumType, String val) { T[] enumConstants = enumType.getEnumConstants(); for(int i = 0; i < enumConstants.length; i++) { if(enumConstants[i] instanceof IntegerValueEnum) { int value = Integer.parseInt(val); if(((IntegerValueEnum)enumConstants[i]).getValue() == value) return enumConstants[i]; } else { throw new RuntimeException("Enum must implement IntegerValueEnum interface to use this utility"); } } return null; } }
package ibis.ipl.impl.registry.central.client; import ibis.ipl.IbisCapabilities; import ibis.ipl.IbisConfigurationException; import ibis.ipl.IbisProperties; import ibis.ipl.impl.IbisIdentifier; import ibis.ipl.impl.registry.central.Election; import ibis.ipl.impl.registry.central.ElectionSet; import ibis.ipl.impl.registry.central.Event; import ibis.ipl.impl.registry.central.EventList; import ibis.ipl.impl.registry.central.ListMemberSet; import ibis.ipl.impl.registry.central.Member; import ibis.ipl.impl.registry.central.MemberSet; import ibis.ipl.impl.registry.central.RegistryProperties; import ibis.ipl.impl.registry.central.TreeMemberSet; import ibis.ipl.impl.registry.statistics.Statistics; import ibis.util.TypedProperties; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; final class Pool { private static final Logger logger = Logger.getLogger(Pool.class); private final String poolName; private final boolean closedWorld; private final int size; private final MemberSet members; private final ElectionSet elections; private final EventList eventList; private final Registry registry; private final Statistics statistics; private boolean initialized; private boolean closed; private boolean stopped; private int time; Pool(IbisCapabilities capabilities, TypedProperties properties, Registry registry, Statistics statistics) { this.registry = registry; this.statistics = statistics; if (statistics != null) { statistics.newPoolSize(0); } if (properties.getBooleanProperty(RegistryProperties.TREE)) { members = new TreeMemberSet(); } else { members = new ListMemberSet(); } elections = new ElectionSet(); eventList = new EventList(); time = -1; initialized = false; closed = false; stopped = false; // get the pool .... poolName = properties.getProperty(IbisProperties.POOL_NAME); if (poolName == null) { throw new IbisConfigurationException( "cannot initialize registry, property " + IbisProperties.POOL_NAME + " is not specified"); } closedWorld = capabilities.hasCapability(IbisCapabilities.CLOSED_WORLD); if (closedWorld) { try { size = properties.getIntProperty(IbisProperties.POOL_SIZE); } catch (final NumberFormatException e) { throw new IbisConfigurationException( "could not start registry for a closed world ibis, " + "required property: " + IbisProperties.POOL_SIZE + " undefined", e); } } else { size = -1; } } synchronized Event[] getEventsFrom(int start) { return eventList.getList(start); } String getName() { return poolName; } boolean isClosedWorld() { return closedWorld; } int getSize() { return size; } synchronized Member getRandomMember() { return members.getRandom(); } synchronized int getNextRequiredEvent() { return eventList.getNextRequiredEvent(); } synchronized int getTime() { return time; } synchronized boolean isInitialized() { return initialized; } synchronized boolean isStopped() { return stopped; } synchronized boolean isMember(IbisIdentifier ibis) { return members.contains(ibis); } // new incoming events void newEventsReceived(Event[] events) { synchronized (this) { eventList.add(events); } handleEvents(); } synchronized void purgeHistoryUpto(int time) { if (this.time != -1 && this.time < time) { logger.error("EEP! we are asked to purge the history of events we still need. Our time = " + this.time + " purge time = " + time); return; } eventList.setMinimum(time); } void init(DataInputStream stream) throws IOException { long start = System.currentTimeMillis(); // copy over data first so we are not blocked while reading data byte[] bytes = new byte[stream.readInt()]; stream.readFully(bytes); DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); long read = System.currentTimeMillis(); // we have all the data in the array now, read from that... synchronized (this) { long locked = System.currentTimeMillis(); if (initialized) { //already initialized, ignore return; } logger.debug("reading bootstrap state"); time = in.readInt(); members.init(in); long membersDone = System.currentTimeMillis(); elections.init(in); int nrOfSignals = in.readInt(); if (nrOfSignals < 0) { throw new IOException("negative number of signals"); } ArrayList<Event> signals = new ArrayList<Event>(); for (int i = 0; i < nrOfSignals; i++) { signals.add(new Event(in)); } closed = in.readBoolean(); // Create list of "old" events SortedSet<Event> events = new TreeSet<Event>(); events.addAll(members.getJoinEvents()); events.addAll(elections.getEvents()); events.addAll(signals); long used = System.currentTimeMillis(); // pass old events to the registry // CALLS REGISTRY WHILE POOL IS LOCKED! for (Event event : events) { registry.handleEvent(event); } long handled = System.currentTimeMillis(); initialized = true; notifyAll(); if (statistics != null) { statistics.newPoolSize(members.size()); } long statted = System.currentTimeMillis(); logger.info("pool init, read = " + (read - start) + ", locked = " + (locked - read) + ", membersDone = " + (membersDone - locked) + ", used = " + (used - membersDone) + ", handled = " + (handled - used) + ", statted = " + (statted - handled)); } handleEvents(); logger.debug("bootstrap complete"); } void writeState(DataOutputStream out, int joinTime) throws IOException { ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(arrayOut); synchronized (this) { if (!initialized) { throw new IOException("state not initialized yet"); } dataOut.writeInt(time); members.writeTo(dataOut); elections.writeTo(dataOut); Event[] signals = eventList.getSignalEvents(joinTime, time); dataOut.writeInt(signals.length); for (Event event : signals) { event.writeTo(dataOut); } dataOut.writeBoolean(closed); } dataOut.flush(); dataOut.close(); byte[] bytes = arrayOut.toByteArray(); out.writeInt(bytes.length); out.write(bytes); logger.debug("pool state size = " + bytes.length); } synchronized IbisIdentifier getElectionResult(String election, long timeout) throws IOException { long deadline = System.currentTimeMillis() + timeout; if (timeout == 0) { deadline = Long.MAX_VALUE; } Election result = elections.get(election); while (result == null) { long timeRemaining = deadline - System.currentTimeMillis(); if (timeRemaining <= 0) { logger.debug("getElectionResullt deadline expired"); return null; } try { if (timeRemaining > 1000) { timeRemaining = 1000; } logger.debug("waiting " + timeRemaining + " for election"); wait(timeRemaining); logger.debug("DONE waiting " + timeRemaining + " for election"); } catch (final InterruptedException e) { // IGNORE } result = elections.get(election); } logger.debug("getElection result = " + result); return result.getWinner(); } private synchronized void handleEvent(Event event) { logger.debug("handling event: " + event); switch (event.getType()) { case Event.JOIN: members.add(new Member(event.getFirstIbis(), event)); if (statistics != null) { statistics.newPoolSize(members.size()); } break; case Event.LEAVE: members.remove(event.getFirstIbis()); if (statistics != null) { statistics.newPoolSize(members.size()); } break; case Event.DIED: IbisIdentifier died = event.getFirstIbis(); members.remove(died); if (statistics != null) { statistics.newPoolSize(members.size()); } if (died.equals(registry.getIbisIdentifier())) { logger.debug("we were declared dead"); stop(); } break; case Event.SIGNAL: // Not handled here break; case Event.ELECT: elections.put(new Election(event)); if (statistics != null) { statistics.electionEvent(); } break; case Event.UN_ELECT: elections.remove(event.getDescription()); if (statistics != null) { statistics.electionEvent(); } break; case Event.POOL_CLOSED: closed = true; break; default: logger.error("unknown event type: " + event.getType()); } // wake up threads waiting for events notifyAll(); if (logger.isDebugEnabled()) { logger.debug("member list now: " + members); } } synchronized void waitUntilPoolClosed() { if (!closedWorld) { throw new IbisConfigurationException("waitForAll() called but not " + "closed world"); } while (!(closed || stopped)) { try { wait(); } catch (final InterruptedException e) { // IGNORE } } } synchronized void waitForEventTime(int time, long timeout) { long deadline = System.currentTimeMillis() + timeout; if (timeout == 0) { deadline = Long.MAX_VALUE; } while (getTime() < time) { if (stopped) { return; } long currentTime = System.currentTimeMillis(); if (currentTime >= deadline) { return; } try { wait(deadline - currentTime); } catch (InterruptedException e) { // IGNORE } } } synchronized void stop() { stopped = true; notifyAll(); if (statistics != null) { statistics.newPoolSize(0); statistics.write(); } } private synchronized Event getEvent() { return eventList.get(time); } /** * Handles incoming events, passes events to the registry */ private void handleEvents() { logger.info("handling events"); if (!isInitialized()) { logger.info("handle events: not initialized yet"); return; } while (true) { // Modified the code below to do getEvent and time++ within // one synchronized block, otherwise race condition. Event event; synchronized (this) { event = getEvent(); if (event == null) { logger.info("done handling events, event time now: " + time); return; } handleEvent(event); time++; notifyAll(); // Niels: does having this outside the synchronized block not // allow for a change in the order in which the user sees the // events? (Ceriel) // TODO: check this!!! registry.handleEvent(event); } } } public synchronized Member[] getChildren() { return members.getChildren(registry.getIbisIdentifier()); } }
package fr.jayasoft.ivy.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import fr.jayasoft.ivy.Artifact; import fr.jayasoft.ivy.ModuleRevisionId; /** * @author x.hanin * @author Maarten Coene (for the optional part management) */ public class IvyPatternHelper { public static final String CONF_KEY = "conf"; public static final String TYPE_KEY = "type"; public static final String EXT_KEY = "ext"; public static final String ARTIFACT_KEY = "artifact"; public static final String REVISION_KEY = "revision"; public static final String MODULE_KEY = "module"; public static final String ORGANISATION_KEY = "organisation"; public static final String ORGANISATION_KEY2 = "organization"; private static final Pattern PARAM_PATTERN = Pattern.compile("\\@\\{(.*?)\\}"); private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{(.*?)\\}"); private static final Pattern TOKEN_PATTERN = Pattern.compile("\\[(.*?)\\]"); public static String substitute(String pattern, ModuleRevisionId moduleRevision) { return substitute(pattern, moduleRevision.getOrganisation(), moduleRevision.getName(), moduleRevision.getRevision(), "ivy", "ivy", "xml", null); } public static String substitute(String pattern, ModuleRevisionId moduleRevision, String artifact, String type, String ext) { return substitute(pattern, moduleRevision.getOrganisation(), moduleRevision.getName(), moduleRevision.getRevision(), artifact, type, ext, null); } public static String substitute(String pattern, Artifact artifact) { return substitute(pattern, artifact.getModuleRevisionId().getOrganisation(), artifact.getModuleRevisionId().getName(), artifact.getModuleRevisionId().getRevision(), artifact.getName(), artifact.getType(), artifact.getExt(), null); } public static String substitute(String pattern, String org, String module, String revision, String artifact, String type, String ext) { return substitute(pattern, org, module, revision, artifact, type, ext, null); } public static String substitute(String pattern, String org, String module, String revision, String artifact, String type, String ext, String conf) { Map tokens = new HashMap(); tokens.put(ORGANISATION_KEY, org==null?"":org); tokens.put(ORGANISATION_KEY2, org==null?"":org); tokens.put(MODULE_KEY, module==null?"":module); tokens.put(REVISION_KEY, revision==null?"":revision); tokens.put(ARTIFACT_KEY, artifact==null?module:artifact); tokens.put(TYPE_KEY, type==null?"jar":type); tokens.put(EXT_KEY, ext==null?"jar":ext); tokens.put(CONF_KEY, conf==null?"default":conf); return substituteTokens(pattern, tokens); } public static String substitute(String pattern, Map variables, Map tokens) { return substituteTokens(substituteVariables(pattern, variables), tokens); } public static String substituteVariables(String pattern, Map variables) { return substituteVariables(pattern, variables, new Stack()); } private static String substituteVariables(String pattern, Map variables, Stack substituting) { // if you supply null, null is what you get if (pattern == null) { return null; } Matcher m = VAR_PATTERN.matcher(pattern); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String val = (String)variables.get(var); if (val != null) { int index; if ((index = substituting.indexOf(var)) != -1) { List cycle = new ArrayList(substituting.subList(index, substituting.size())); cycle.add(var); throw new IllegalArgumentException("cyclic variable definition: cycle = "+cycle); } substituting.push(var); val = substituteVariables(val, variables, substituting); substituting.pop(); } else { val = m.group(); } m.appendReplacement(sb, val.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\$", "\\\\\\$")); } m.appendTail(sb); return sb.toString(); } public static String substituteTokens(String pattern, Map tokens) { StringBuffer buffer = new StringBuffer(); char[] chars = pattern.toCharArray(); StringBuffer optionalPart = null; StringBuffer tokenBuffer = null; boolean insideOptionalPart = false; boolean insideToken = false; boolean tokenHadValue = false; for (int i = 0; i < chars.length; i++) { switch (chars[i]) { case '(': if (insideOptionalPart) { throw new IllegalArgumentException("invalid start of optional part at position " + i + " in pattern " + pattern); } optionalPart = new StringBuffer(); insideOptionalPart = true; tokenHadValue = false; break; case ')': if (!insideOptionalPart || insideToken) { throw new IllegalArgumentException("invalid end of optional part at position " + i + " in pattern " + pattern); } if (tokenHadValue) { buffer.append(optionalPart.toString()); } insideOptionalPart = false; break; case '[': if (insideToken) { throw new IllegalArgumentException("invalid start of token at position " + i + " in pattern " + pattern); } tokenBuffer = new StringBuffer(); insideToken = true; break; case ']': if (!insideToken) { throw new IllegalArgumentException("invalid end of token at position " + i + " in pattern " + pattern); } String token = tokenBuffer.toString(); String value = (String) tokens.get(token); if (insideOptionalPart) { tokenHadValue = (value != null) && (value.length() > 0); optionalPart.append(value); } else { if (value == null) { // the token wasn't set, it's kept as is value = "["+token+"]"; } buffer.append(value); } insideToken = false; break; default: if (insideToken) { tokenBuffer.append(chars[i]); } else if (insideOptionalPart) { optionalPart.append(chars[i]); } else { buffer.append(chars[i]); } break; } } if (insideToken) { throw new IllegalArgumentException("last token hasn't been closed in pattern " + pattern); } if (insideOptionalPart) { throw new IllegalArgumentException("optional part hasn't been closed in pattern " + pattern); } return buffer.toString(); } public static String substituteVariable(String pattern, String variable, String value) { StringBuffer buf = new StringBuffer(pattern); substituteVariable(buf, variable, value); return buf.toString(); } public static void substituteVariable(StringBuffer buf, String variable, String value) { String from = "${"+variable+"}"; int fromLength = from.length(); for (int index = buf.indexOf(from); index != -1; index = buf.indexOf(from, index)) { buf.replace(index, index + fromLength, value); } } public static String substituteToken(String pattern, String token, String value) { StringBuffer buf = new StringBuffer(pattern); substituteToken(buf, token, value); return buf.toString(); } public static void substituteToken(StringBuffer buf, String token, String value) { String from = getTokenString(token); int fromLength = from.length(); for (int index = buf.indexOf(from); index != -1; index = buf.indexOf(from, index)) { buf.replace(index, index + fromLength, value); } } public static String getTokenString(String token) { return "["+token+"]"; } public static String substituteParams(String pattern, Map params) { return substituteParams(pattern, params, new Stack()); } private static String substituteParams(String pattern, Map params, Stack substituting) { //TODO : refactor this with substituteVariables // if you supply null, null is what you get if (pattern == null) { return null; } Matcher m = PARAM_PATTERN.matcher(pattern); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String val = (String)params.get(var); if (val != null) { int index; if ((index = substituting.indexOf(var)) != -1) { List cycle = new ArrayList(substituting.subList(index, substituting.size())); cycle.add(var); throw new IllegalArgumentException("cyclic param definition: cycle = "+cycle); } substituting.push(var); val = substituteVariables(val, params, substituting); substituting.pop(); } else { val = m.group(); } m.appendReplacement(sb, val.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\@", "\\\\\\@")); } m.appendTail(sb); return sb.toString(); } public static void main(String[] args) { String pattern = "[organisation]/[module]/build/archives/[type]s/[artifact]-[revision].[ext]"; System.out.println("pattern= "+pattern); System.out.println("resolved= "+substitute(pattern, "jayasoft", "Test", "1.0", "test", "jar", "jar")); Map variables = new HashMap(); variables.put("test", "mytest"); variables.put("test2", "${test}2"); pattern = "${test} ${test2} ${nothing}"; System.out.println("pattern= "+pattern); System.out.println("resolved= "+substituteVariables(pattern, variables)); } }
package com.lasarobotics.library.util; /** * 3D Vector : Immutable */ public class Vector3<T> { public final T x; public final T y; public final T z; public static class Builder<T> { private final T x, y, z; public Builder<T> x(T n) { this.x = n; return this; } public Builder<T> y(T n) { this.y = n; return this; } public Builder<T> z(T n) { this.z = n; return this; } public Vector3<T> build() { return new Vector3<T>(x, y, z); } } public Vector3(T x, T y, T z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return "(" + x + ", " + y + ", " + z + ")"; } }
package com.example.gsyvideoplayer; import android.content.res.Configuration; import android.os.Bundle; import android.os.Environment; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import com.example.gsyvideoplayer.video.LandLayoutVideo; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack; import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener; import com.shuyu.gsyvideoplayer.model.VideoOptionModel; import com.shuyu.gsyvideoplayer.utils.FileUtils; import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer; import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder; import com.shuyu.gsyvideoplayer.listener.LockClickListener; import com.shuyu.gsyvideoplayer.utils.Debuger; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; public class DetailPlayer extends AppCompatActivity { @BindView(R.id.post_detail_nested_scroll) NestedScrollView postDetailNestedScroll; //StandardGSYVideoPlayer //CustomGSYVideoPlayer @BindView(R.id.detail_player) LandLayoutVideo detailPlayer; @BindView(R.id.activity_detail_player) RelativeLayout activityDetailPlayer; private boolean isPlay; private boolean isPause; private OrientationUtils orientationUtils; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_player); ButterKnife.bind(this); String url = getUrl(); //detailPlayer.setUp(url, false, null, ""); //detailPlayer.setLooping(true); //detailPlayer.setShowPauseCover(false); //VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 30); //seek //VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1); //list<VideoOptionModel> list = new ArrayList<>(); //list.add(videoOptionModel); //GSYVideoManager.instance().setOptionModelList(list); //GSYVideoManager.instance().setTimeOut(4000, true); ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); //detailPlayer.setThumbImageView(imageView); resolveNormalVideoUI(); orientationUtils = new OrientationUtils(this, detailPlayer); orientationUtils.setEnable(false); Map<String, String> header = new HashMap<>(); header.put("ee", "33"); GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder(); gsyVideoOption.setThumbImageView(imageView) .setIsTouchWiget(true) .setRotateViewAuto(false) .setLockLand(false) .setAutoFullWithSize(true) .setShowFullAnimation(false) .setNeedLockFull(true) .setUrl(url) .setMapHeadData(header) .setCacheWithPlay(false) .setVideoTitle("") .setVideoAllCallBack(new GSYSampleCallBack() { @Override public void onPrepared(String url, Object... objects) { Debuger.printfError("***** onPrepared **** " + objects[0]); Debuger.printfError("***** onPrepared **** " + objects[1]); super.onPrepared(url, objects); orientationUtils.setEnable(true); isPlay = true; } @Override public void onEnterFullscreen(String url, Object... objects) { super.onEnterFullscreen(url, objects); Debuger.printfError("***** onEnterFullscreen **** " + objects[0]);//title Debuger.printfError("***** onEnterFullscreen **** " + objects[1]);//player } @Override public void onAutoComplete(String url, Object... objects) { super.onAutoComplete(url, objects); } @Override public void onClickStartError(String url, Object... objects) { super.onClickStartError(url, objects); } @Override public void onQuitFullscreen(String url, Object... objects) { super.onQuitFullscreen(url, objects); Debuger.printfError("***** onQuitFullscreen **** " + objects[0]);//title Debuger.printfError("***** onQuitFullscreen **** " + objects[1]);//player if (orientationUtils != null) { orientationUtils.backToProtVideo(); } } }) .setLockClickListener(new LockClickListener() { @Override public void onClick(View view, boolean lock) { if (orientationUtils != null) { //onConfigurationChanged orientationUtils.setEnable(!lock); } } }) .setGSYVideoProgressListener(new GSYVideoProgressListener() { @Override public void onProgress(int progress, int secProgress, int currentPosition, int duration) { Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration); } }) .build(detailPlayer); detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { orientationUtils.resolveByClick(); //trueactionbartruestatusbar detailPlayer.startWindowFullscreen(DetailPlayer.this, true, true); } }); } @Override public void onBackPressed() { if (orientationUtils != null) { orientationUtils.backToProtVideo(); } if (GSYVideoManager.backFromWindowFull(this)) { return; } super.onBackPressed(); } @Override protected void onPause() { getCurPlay().onVideoPause(); super.onPause(); isPause = true; } @Override protected void onResume() { getCurPlay().onVideoResume(false); super.onResume(); isPause = false; } @Override protected void onDestroy() { super.onDestroy(); if (isPlay) { getCurPlay().release(); } //GSYPreViewManager.instance().releaseMediaPlayer(); if (orientationUtils != null) orientationUtils.releaseListener(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (isPlay && !isPause) { detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true); } } private void resolveNormalVideoUI() { //title detailPlayer.getTitleTextView().setVisibility(View.GONE); detailPlayer.getBackButton().setVisibility(View.GONE); } private GSYVideoPlayer getCurPlay() { if (detailPlayer.getFullWindowPlayer() != null) { return detailPlayer.getFullWindowPlayer(); } return detailPlayer; } private String getUrl() { //String url = "android.resource://" + getPackageName() + "/" + R.raw.test; //ijkraw //GSYVideoManager.instance().enableRawPlay(getApplicationContext()); //urlijkhttphook: String url = "http://hjq-1257036536.cos.ap-shanghai.myqcloud.com/m3u8/m1/video.m3u8"; //String url = "file://"+ Environment.getExternalStorageDirectory().getPath() + "Download/132451525666042.mp4"; //String url = "rtsp://ajj:12345678@218.21.217.122:65523/h264/ch40/sub/av_stream"; //String url = "rtsp://ajj:ajj12345678@218.21.217.122:65522/h264/ch15/sub/av_stream";//String url = "rtsp://cloud.easydarwin.org:554/stream0.sdp"; return url; } }
package net.somethingdreadful.MAL; import net.somethingdreadful.MAL.record.AnimeRecord; import net.somethingdreadful.MAL.record.GenericMALRecord; import net.somethingdreadful.MAL.record.MangaRecord; import org.apache.commons.lang3.text.WordUtils; import android.content.Context; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.Html; import android.text.Spanned; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockDialogFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class DetailView extends SherlockFragmentActivity implements DetailsBasicFragment.IDetailsBasicAnimeFragment, EpisodesPickerDialogFragment.DialogDismissedListener, MangaProgressDialogFragment.MangaDialogDismissedListener, StatusPickerDialogFragment.StatusDialogDismissedListener, RatingPickerDialogFragment.RatingDialogDismissedListener, RemoveConfirmationDialogFragment.RemoveConfirmationDialogListener { MALManager mManager; PrefManager pManager; Context context; int recordID; ActionBar actionBar; AnimeRecord animeRecord; MangaRecord mangaRecord; String recordType; boolean isAdded = true; DetailsBasicFragment bfrag; GenericCardFragment SynopsisFragment; GenericCardFragment ProgressFragment; GenericCardFragment StatusFragment; GenericCardFragment ScoreFragment; GenericCardFragment WatchStatusFragment; FragmentManager fm; EpisodesPickerDialogFragment epd; MangaProgressDialogFragment mpdf; StatusPickerDialogFragment spdf; RatingPickerDialogFragment rpdf; RemoveConfirmationDialogFragment rcdf; TextView SynopsisView; TextView RecordTypeView; TextView RecordStatusView; TextView MyStatusView; TextView ProgressCurrentVolumeView; TextView ProgressTotalVolumeView; TextView ProgressCurrentView; TextView ProgressTotalView; ImageView CoverImageView; RatingBar MALScoreBar; RatingBar MyScoreBar; Spanned SynopsisText; String VolumeProgressText; String VolumeTotalText; String ProgressText; String TotalProgressText; String RecordStatusText; String RecordTypeText; String MyStatusText; int MyScore; float MemberScore; boolean useSecondaryAmounts; boolean networkAvailable = true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_view); //Get the recordID, passed in from the calling activity recordID = getIntent().getIntExtra("net.somethingdreadful.MAL.recordID", 1); //Get the recordType, also passed from calling activity //Record type will determine how the detail view lays out itself recordType = getIntent().getStringExtra("net.somethingdreadful.MAL.recordType"); context = getApplicationContext(); mManager = new MALManager(context); pManager = new PrefManager(context); networkAvailable = isNetworkAvailable(); fm = getSupportFragmentManager(); bfrag = (DetailsBasicFragment) fm.findFragmentById(R.id.DetailsFragment); SynopsisFragment = (GenericCardFragment) fm.findFragmentById(R.id.SynopsisFragment); SynopsisFragment.setArgsSensibly("SYNOPSIS", R.layout.card_layout_content_synopsis, GenericCardFragment.CONTENT_TYPE_SYNOPSIS, false); SynopsisFragment.inflateContentStub(); ProgressFragment = (GenericCardFragment) fm.findFragmentById(R.id.ProgressFragment); int card_layout_progress = R.layout.card_layout_progress; if ("manga".equals(recordType)) { card_layout_progress = R.layout.card_layout_progress_manga; } ProgressFragment.setArgsSensibly("PROGRESS", card_layout_progress, GenericCardFragment.CONTENT_TYPE_PROGRESS, true); ProgressFragment.inflateContentStub(); ProgressFragment.getView().setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //TODO: Added some kind of clicking feedback, like highlight it or something showProgressDialog(); } }); StatusFragment = (GenericCardFragment) fm.findFragmentById(R.id.StatusFragment); StatusFragment.setArgsSensibly("MAL STATS", R.layout.card_layout_status, GenericCardFragment.CONTENT_TYPE_INFO, false); StatusFragment.inflateContentStub(); ScoreFragment = (GenericCardFragment) fm.findFragmentById(R.id.ScoreFragment); ScoreFragment.setArgsSensibly("RATING", R.layout.card_layout_score, GenericCardFragment.CONTENT_TYPE_SCORE, true); ScoreFragment.inflateContentStub(); ScoreFragment.getView().setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showRatingDialog(); } }); WatchStatusFragment = (GenericCardFragment) fm.findFragmentById(R.id.WatchStatusFragment); WatchStatusFragment.setArgsSensibly("STATUS", R.layout.card_layout_watchstatus, GenericCardFragment.CONTENT_TYPE_WATCHSTATUS, true); WatchStatusFragment.inflateContentStub(); WatchStatusFragment.getView().setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //TODO: Added some kind of clicking feedback, like highlight it or something showStatusDialog(); } }); useSecondaryAmounts = pManager.getUseSecondaryAmountsEnabled(); // Set up the action bar. actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (isAdded) { getSupportMenuInflater().inflate(R.menu.activity_detail_view, menu); } else { getSupportMenuInflater().inflate(R.menu.activity_detail_view_unrecorded, menu); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (networkAvailable) { menu.findItem(R.id.action_Remove).setVisible(true); } else { menu.findItem(R.id.action_Remove).setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.action_Share: Share(); break; case R.id.action_Remove: showRemoveDialog(); break; case R.id.action_addToList: addToList(); break; } return true; } public void showRemoveDialog() { rcdf = new RemoveConfirmationDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { rcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { rcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } rcdf.show(fm, "fragment_RemoveConfirmationDialog"); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); try { if ("anime".equals(recordType)) { if (animeRecord.getDirty() == 1) { writeDetails(animeRecord); } } else { if (mangaRecord.getDirty() == 1) { writeDetails(mangaRecord); } } } catch (NullPointerException ignored) { } } //Called after the basic fragment is finished it's setup, populate data into it @Override public void basicFragmentReady() { CoverImageView = (ImageView) bfrag.getView().findViewById(R.id.detailCoverImage); getDetails(); } public void getDetails() { new getDetailsTask().execute(); } public void showProgressDialog() // Just a function to keep logic out of the switch statement { if ("anime".equals(recordType)) { showEpisodesWatchedDialog(); } else { showMangaProgressDialog(); } } public void showStatusDialog() { spdf = new StatusPickerDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { spdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { spdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } spdf.show(fm, "fragment_EditStatusDialog"); } public void showRatingDialog() { rpdf = new RatingPickerDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { rpdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { rpdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } rpdf.show(fm, "fragment_EditRatingDialog"); } public void showEpisodesWatchedDialog() { //Standard code for setting up a dialog fragment //Note we use setStyle to change the theme, the default light styled dialog didn't look good so we use the dark dialog epd = new EpisodesPickerDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { epd.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { epd.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } epd.show(fm, "fragment_EditEpisodesWatchedDialog"); } public void showMangaProgressDialog() { //Standard code for setting up a dialog fragment // Toast.makeText(context, "TODO: Make a MangaProgressFragment", Toast.LENGTH_SHORT).show(); mpdf = new MangaProgressDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { mpdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { mpdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } mpdf.show(fm, "fragment_EditMangaProgressDialog"); } public class getDetailsTask extends AsyncTask<Void, Boolean, GenericMALRecord> { int mRecordID; MALManager mMalManager; ImageDownloader imageDownloader = new ImageDownloader(context); String internalType; @Override protected void onPreExecute() { mRecordID = recordID; mMalManager = mManager; internalType = recordType; } @Override protected GenericMALRecord doInBackground(Void... arg0) { if ("anime".equals(internalType)) { animeRecord = mMalManager.getAnimeRecord(mRecordID); //Basically I just use publishProgress as an easy way to display info we already have loaded sooner //This way, I can let the database work happen on the background thread and then immediately display it while //the synopsis loads if it hasn't previously been downloaded. publishProgress(true); if(networkAvailable) { if ((animeRecord.getSynopsis() == null) || (animeRecord.getMemberScore() <= 0)) { animeRecord = mMalManager.updateWithDetails(mRecordID, animeRecord); } } else { } return animeRecord; } else { mangaRecord = mMalManager.getMangaRecord(mRecordID); //Basically I just use publishProgress as an easy way to display info we already have loaded sooner //This way, I can let the database work happen on the background thread and then immediately display it while //the synopsis loads if it hasn't previously been downloaded. publishProgress(true); if(networkAvailable) { if ((mangaRecord.getSynopsis() == null) || (mangaRecord.getMemberScore() <= 0)) { mangaRecord = mMalManager.updateWithDetails(mRecordID, mangaRecord); } } return mangaRecord; } } @Override protected void onProgressUpdate(Boolean... progress) { if ("anime".equals(internalType)) { actionBar.setTitle(animeRecord.getName()); CoverImageView.setImageDrawable(new BitmapDrawable(imageDownloader.returnDrawable(context, animeRecord.getImageUrl()))); ProgressText = Integer.toString(animeRecord.getPersonalProgress(false)); TotalProgressText = animeRecord.getTotal(false); MyStatusText = WordUtils.capitalize(animeRecord.getMyStatus()); ProgressCurrentView = (TextView) ProgressFragment.getView().findViewById(R.id.progressCountCurrent); ProgressTotalView = (TextView) ProgressFragment.getView().findViewById(R.id.progressCountTotal); if (ProgressTotalView != null) { ProgressCurrentView.setText(ProgressText); ProgressTotalView.setText("/" + TotalProgressText); } RecordStatusText = WordUtils.capitalize(animeRecord.getRecordStatus()); RecordTypeText = WordUtils.capitalize(animeRecord.getRecordType()); MemberScore = animeRecord.getMemberScore(); MyScore = animeRecord.getMyScore(); RecordTypeView = (TextView) StatusFragment.getView().findViewById(R.id.mediaType); RecordStatusView = (TextView) StatusFragment.getView().findViewById(R.id.mediaStatus); if (RecordStatusView != null) { RecordTypeView.setText(RecordTypeText); RecordStatusView.setText(RecordStatusText); } if ("".equals(animeRecord.getMyStatus())) { Log.v("MALX", "No status found; Record must have been searched for, therefore not added to list"); setAddToListUI(true); } } else { actionBar.setTitle(mangaRecord.getName()); CoverImageView.setImageDrawable(new BitmapDrawable(imageDownloader.returnDrawable(context, mangaRecord.getImageUrl()))); VolumeProgressText = Integer.toString(mangaRecord.getVolumeProgress()); VolumeTotalText = Integer.toString(mangaRecord.getVolumesTotal()); ProgressText = Integer.toString(mangaRecord.getPersonalProgress(false)); TotalProgressText = mangaRecord.getTotal(false); MyStatusText = WordUtils.capitalize(mangaRecord.getMyStatus()); ProgressCurrentVolumeView = (TextView) ProgressFragment.getView().findViewById(R.id.progressVolumesCountCurrent); ProgressTotalVolumeView = (TextView) ProgressFragment.getView().findViewById(R.id.progressVolumesCountTotal); ProgressCurrentView = (TextView) ProgressFragment.getView().findViewById(R.id.progressCountCurrent); ProgressTotalView = (TextView) ProgressFragment.getView().findViewById(R.id.progressCountTotal); MyStatusView = (TextView) WatchStatusFragment.getView().findViewById(R.id.cardStatusLabel); if (ProgressTotalVolumeView != null) { ProgressCurrentVolumeView.setText(VolumeProgressText); ProgressTotalVolumeView.setText("/" + VolumeTotalText); } if (ProgressTotalView != null) { ProgressCurrentView.setText(ProgressText); ProgressTotalView.setText("/" + TotalProgressText); } if (MyStatusView != null) { MyStatusView.setText(MyStatusText); } RecordStatusText = WordUtils.capitalize(mangaRecord.getRecordStatus()); RecordTypeText = WordUtils.capitalize(mangaRecord.getRecordType()); RecordTypeView = (TextView) StatusFragment.getView().findViewById(R.id.mediaType); RecordStatusView = (TextView) StatusFragment.getView().findViewById(R.id.mediaStatus); if (RecordStatusView != null) { RecordTypeView.setText(RecordTypeText); RecordStatusView.setText(RecordStatusText); } if ("".equals(mangaRecord.getMyStatus())) { Log.v("MALX", "No status found; Record must have been searched for, therefore not added to list"); setAddToListUI(true); } } } @Override protected void onPostExecute(GenericMALRecord gr) { if (ProgressFragment.getView() == null) { // Parent activity is destroy, skipping return; } if ("anime".equals(internalType)) { MALScoreBar = (RatingBar) ScoreFragment.getView().findViewById(R.id.MALScoreBar); MyScoreBar = (RatingBar) ScoreFragment.getView().findViewById(R.id.MyScoreBar); if (MALScoreBar != null) { MALScoreBar.setRating(MemberScore / 2); MyScoreBar.setRating(MyScore / 2); } MyStatusView = (TextView) WatchStatusFragment.getView().findViewById(R.id.cardStatusLabel); if (MyStatusView != null) { MyStatusView.setText(MyStatusText); } } else { MemberScore = mangaRecord.getMemberScore(); MyScore = mangaRecord.getMyScore(); MALScoreBar = (RatingBar) ScoreFragment.getView().findViewById(R.id.MALScoreBar); MyScoreBar = (RatingBar) ScoreFragment.getView().findViewById(R.id.MyScoreBar); if (MALScoreBar != null) { MALScoreBar.setRating(MemberScore / 2); MyScoreBar.setRating(MyScore / 2); } } if (gr.getSpannedSynopsis() != null) { SynopsisText = gr.getSpannedSynopsis(); MemberScore = gr.getMemberScore(); } else { SynopsisText = Html.fromHtml("<em>No data loaded.</em>"); MemberScore = 0.0f; } if (SynopsisFragment.getView() != null) { SynopsisView = (TextView) SynopsisFragment.getView().findViewById(R.id.SynopsisContent); if (SynopsisView != null) { SynopsisView.setText(SynopsisText, TextView.BufferType.SPANNABLE); } } if (MALScoreBar != null) { MALScoreBar.setRating(MemberScore / 2); MyScoreBar.setRating(MyScore / 2); } } } public class writeDetailsTask extends AsyncTask<GenericMALRecord, Void, Boolean> { MALManager internalManager; String internalType; boolean internalNetworkAvailable; @Override protected void onPreExecute() { internalManager = mManager; internalType = recordType; internalNetworkAvailable = networkAvailable; } @Override protected Boolean doInBackground(GenericMALRecord... gr) { boolean result; if ("anime".equals(internalType)) { internalManager.saveItem((AnimeRecord) gr[0], false); } else { internalManager.saveItem((MangaRecord) gr[0], false); } if (gr[0].hasDelete()) { internalManager.deleteItemFromDatabase(internalType, gr[0].getID()); result = internalManager.writeDetailsToMAL(gr[0], internalType); } else { if (internalNetworkAvailable){ if ("anime".equals(internalType)) { if (gr[0].hasCreate()) { result = internalManager.addItemToMAL(gr[0], internalType); } else { result = internalManager.writeDetailsToMAL(gr[0], MALManager.TYPE_ANIME); } } else { if (gr[0].hasCreate()) { result = internalManager.addItemToMAL(gr[0], internalType); } else { result = internalManager.writeDetailsToMAL(gr[0], MALManager.TYPE_MANGA); } } } else { result = false; } if (result) { gr[0].setDirty(GenericMALRecord.CLEAN); if ("anime".equals(internalType)) { internalManager.saveItem((AnimeRecord) gr[0], false); } else { internalManager.saveItem((MangaRecord) gr[0], false); } } } return result; } } //Dialog returns new value, do something with it @Override public void onDialogDismissed(int newValue) { if ("anime".equals(recordType)) { if (newValue == animeRecord.getPersonalProgress(false)) { } else { if (Integer.parseInt(animeRecord.getTotal(false)) != 0) { if (newValue == Integer.parseInt(animeRecord.getTotal(false))) { animeRecord.setMyStatus(GenericMALRecord.STATUS_COMPLETED); MyStatusView.setText(WordUtils.capitalize(GenericMALRecord.STATUS_COMPLETED)); } if (newValue == 0) { animeRecord.setMyStatus(AnimeRecord.STATUS_PLANTOWATCH); MyStatusView.setText(WordUtils.capitalize(AnimeRecord.STATUS_PLANTOWATCH)); } } animeRecord.setEpisodesWatched(newValue); animeRecord.setDirty(GenericMALRecord.DIRTY); ProgressCurrentView.setText(Integer.toString(newValue)); } } } public void setAddToListUI(boolean enabled) { if (enabled) { //Configure DetailView to show the add to list UI, hide extraneous elements isAdded = false; supportInvalidateOptionsMenu(); FragmentTransaction ft = fm.beginTransaction(); ft.hide(ScoreFragment); ft.hide(ProgressFragment); ft.hide(WatchStatusFragment); ft.commit(); } else { //Record was added, revert UI changes. isAdded = true; supportInvalidateOptionsMenu(); FragmentTransaction ft = fm.beginTransaction(); ft.show(ScoreFragment); ft.show(ProgressFragment); ft.show(WatchStatusFragment); ft.commit(); } } //Create new write task and run it public void writeDetails(GenericMALRecord gr) { new writeDetailsTask().execute(gr); } public void setStatus(String currentStatus) { String prevStatus; if ("anime".equals(recordType)) { prevStatus = animeRecord.getMyStatus(); if (AnimeRecord.STATUS_WATCHING.equals(currentStatus)) { animeRecord.setMyStatus(AnimeRecord.STATUS_WATCHING); } if (GenericMALRecord.STATUS_COMPLETED.equals(currentStatus)) { animeRecord.setMyStatus(AnimeRecord.STATUS_COMPLETED); } if (GenericMALRecord.STATUS_ONHOLD.equals(currentStatus)) { animeRecord.setMyStatus(AnimeRecord.STATUS_ONHOLD); } if (GenericMALRecord.STATUS_DROPPED.equals(currentStatus)) { animeRecord.setMyStatus(AnimeRecord.STATUS_DROPPED); } if ((AnimeRecord.STATUS_PLANTOWATCH.equals(currentStatus))) { animeRecord.setMyStatus(AnimeRecord.STATUS_PLANTOWATCH); } if (!prevStatus.equals(currentStatus)) { animeRecord.setDirty(GenericMALRecord.DIRTY); MyStatusView.setText(WordUtils.capitalize(currentStatus)); } } else { prevStatus = mangaRecord.getMyStatus(); if (MangaRecord.STATUS_WATCHING.equals(currentStatus)) { mangaRecord.setMyStatus(MangaRecord.STATUS_WATCHING); } if (GenericMALRecord.STATUS_COMPLETED.equals(currentStatus)) { mangaRecord.setMyStatus(MangaRecord.STATUS_COMPLETED); } if (GenericMALRecord.STATUS_ONHOLD.equals(currentStatus)) { mangaRecord.setMyStatus(MangaRecord.STATUS_ONHOLD); } if (GenericMALRecord.STATUS_DROPPED.equals(currentStatus)) { mangaRecord.setMyStatus(MangaRecord.STATUS_DROPPED); } if (MangaRecord.STATUS_PLANTOWATCH.equals(currentStatus)) { mangaRecord.setMyStatus(MangaRecord.STATUS_PLANTOWATCH); } if (!prevStatus.equals(currentStatus)) { mangaRecord.setDirty(GenericMALRecord.DIRTY); MyStatusView.setText(WordUtils.capitalize(currentStatus)); } } } public void setRating(int rating) { Log.v("MALX", "setRating received rating: " + rating); if ("anime".equals(recordType)) { MyScoreBar.setRating((float) rating / 2); animeRecord.setMyScore(rating); animeRecord.setDirty(GenericMALRecord.DIRTY); } else { MyScoreBar.setRating((float) rating / 2); mangaRecord.setMyScore(rating); mangaRecord.setDirty(GenericMALRecord.DIRTY); } } @Override public void onMangaDialogDismissed(int newChapterValue, int newVolumeValue) { if ("manga".equals(recordType)) { if (newChapterValue == mangaRecord.getPersonalProgress(false)) { } else { if (Integer.parseInt(mangaRecord.getTotal(false)) != 0) { if (newChapterValue == Integer.parseInt(mangaRecord.getTotal(false))) { mangaRecord.setMyStatus(GenericMALRecord.STATUS_COMPLETED); } if (newChapterValue == 0) { mangaRecord.setMyStatus(MangaRecord.STATUS_PLANTOWATCH); } } mangaRecord.setPersonalProgress(false, newChapterValue); mangaRecord.setDirty(GenericMALRecord.DIRTY); ProgressCurrentView.setText(Integer.toString(newChapterValue)); } if (newVolumeValue == mangaRecord.getVolumeProgress()) { } else { mangaRecord.setVolumesRead(newVolumeValue); mangaRecord.setDirty(GenericMALRecord.DIRTY); ProgressCurrentVolumeView.setText(Integer.toString(newVolumeValue)); } if (newChapterValue == 9001 || newVolumeValue == 9001) { Crouton.makeText(this, "It's over 9000!!", Style.INFO).show(); } } } public void contentInflated(int contentType) { switch (contentType) { case GenericCardFragment.CONTENT_TYPE_SYNOPSIS: SynopsisView = (TextView) SynopsisFragment.getView().findViewById(R.id.SynopsisContent); if (SynopsisText != null) { SynopsisView.setText(SynopsisText, TextView.BufferType.SPANNABLE); } break; case GenericCardFragment.CONTENT_TYPE_PROGRESS: ProgressCurrentView = (TextView) ProgressFragment.getView().findViewById(R.id.progressCountCurrent); ProgressTotalView = (TextView) ProgressFragment.getView().findViewById(R.id.progressCountTotal); if (ProgressText != null) { ProgressCurrentView.setText(ProgressText); ProgressTotalView.setText("/" + TotalProgressText); } break; case GenericCardFragment.CONTENT_TYPE_INFO: RecordTypeView = (TextView) StatusFragment.getView().findViewById(R.id.mediaType); RecordStatusView = (TextView) StatusFragment.getView().findViewById(R.id.mediaStatus); if (RecordStatusText != null) { RecordTypeView.setText(RecordTypeText); RecordStatusView.setText(RecordStatusText); } break; case GenericCardFragment.CONTENT_TYPE_SCORE: MALScoreBar = (RatingBar) ScoreFragment.getView().findViewById(R.id.MALScoreBar); MyScoreBar = (RatingBar) ScoreFragment.getView().findViewById(R.id.MyScoreBar); if (MemberScore > 0) { MALScoreBar.setRating(MemberScore / 2); MyScoreBar.setRating(MyScore / 2); } break; case GenericCardFragment.CONTENT_TYPE_WATCHSTATUS: MyStatusView = (TextView) WatchStatusFragment.getView().findViewById(R.id.cardStatusLabel); if (MyStatusText != null) { Log.v("MALX", "MyStatusText not null, setting"); MyStatusView.setText(MyStatusText); } break; } } public void Share() { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); sharingIntent.putExtra(Intent.EXTRA_TEXT, makeShareText()); startActivity(Intent.createChooser(sharingIntent, "Share via")); } public String makeShareText() { String shareText = pManager.getCustomShareText(); shareText = shareText.replace("$title;", actionBar.getTitle()); shareText = shareText.replace("$link;", "http://myanimelist.net/" + recordType + "/" + Integer.toString(recordID)); shareText = shareText + getResources().getString(R.string.customShareText_fromAtarashii); return shareText; } @Override public void onStatusDialogDismissed(String currentStatus) { setStatus(currentStatus); } @Override public void onRatingDialogDismissed(int rating) { setRating(rating); Log.v("MALX", "Listener recieved rating: " + rating); } @Override public void onRemoveConfirmed() { Log.v("MALX", "Item flagged for being removing."); if ("anime".equals(recordType)) { animeRecord.markForDeletion(true); animeRecord.setDirty(GenericMALRecord.DIRTY); } else { mangaRecord.markForDeletion(true); mangaRecord.setDirty(GenericMALRecord.DIRTY); } finish(); } public void addToList() { if (recordType.equals("anime")) { animeRecord.markForCreate(true); animeRecord.setMyStatus(AnimeRecord.STATUS_WATCHING); MyStatusView.setText(WordUtils.capitalize(AnimeRecord.STATUS_WATCHING)); animeRecord.setDirty(1); } else { mangaRecord.markForCreate(true); mangaRecord.setMyStatus(MangaRecord.STATUS_WATCHING); MyStatusView.setText(WordUtils.capitalize(MangaRecord.STATUS_WATCHING)); mangaRecord.setDirty(1); } setAddToListUI(false); } public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { return true; } else { return false; } } }
package com.iuridiniz.checkmyecg; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.view.WindowManager; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.interpolation.SplineInterpolator; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.CameraBridgeViewBase; import org.opencv.android.OpenCVLoader; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfInt; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; interface Filter { public Mat apply(Mat src); }; class GradeFilter implements Filter { private Mat mGray, mMaskRed1, mMaskRed2; /* CV_8UC1 */ private Mat mRgb, mHsv; /* CV_8UC3 */ private Mat mRgba; /* CV_8UC4 */ private Scalar mLowerRed1, mUpperRed1; private Scalar mLowerRed2, mUpperRed2; public GradeFilter(int rows, int cols) { mGray = new Mat(rows, cols, CvType.CV_8UC1); mMaskRed1 = new Mat(rows, cols, CvType.CV_8UC1); mMaskRed2 = new Mat(rows, cols, CvType.CV_8UC1); mHsv = new Mat(rows, cols, CvType.CV_8UC3); mRgb = new Mat(rows, cols, CvType.CV_8UC3); mRgba = new Mat(rows, cols, CvType.CV_8UC4); mLowerRed1 = new Scalar(0, 100, 100); mUpperRed1 = new Scalar(15, 255, 255); mLowerRed2 = new Scalar(230, 100, 100); mUpperRed2 = new Scalar(255, 255, 255); } @Override public Mat apply(Mat rgba) { /* HSV first */ Imgproc.cvtColor(rgba, mRgb, Imgproc.COLOR_RGBA2RGB); Imgproc.cvtColor(mRgb, mHsv, Imgproc.COLOR_RGB2HSV); /* get first red range */ Core.inRange(mHsv, mLowerRed1, mUpperRed1, mMaskRed1); /* get second red range */ Core.inRange(mHsv, mLowerRed1, mUpperRed1, mMaskRed1); Core.inRange(mHsv, mLowerRed2, mUpperRed2, mMaskRed2); /* merge it */ Core.bitwise_or(mMaskRed1, mMaskRed2, mMaskRed1); /* invert it */ Core.bitwise_not(mMaskRed1, mMaskRed1); /* convert back to colorspace expected */ Imgproc.cvtColor(mMaskRed1, mRgba, Imgproc.COLOR_GRAY2RGBA); return mRgba; } } class GraphFilter implements Filter { protected Mat mGray; protected Mat mMatMaskBlack; protected Mat mMatMaskBlackInv; /* CV_8UC1 */ protected Mat mRgb, mHsv; /* CV_8UC3 */ protected Mat mRgbaDst; /* CV_8UC4 */ protected Scalar mLowerBlack, mUpperBlack; public GraphFilter(int rows, int cols) { mGray = new Mat(rows, cols, CvType.CV_8UC1); mMatMaskBlack = new Mat(rows, cols, CvType.CV_8UC1); mMatMaskBlackInv = new Mat(rows, cols, CvType.CV_8UC1); mHsv = new Mat(rows, cols, CvType.CV_8UC3); mRgb = new Mat(rows, cols, CvType.CV_8UC3); //mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4, new Scalar(255)); mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4); mLowerBlack = new Scalar(0, 0, 0); mUpperBlack = new Scalar(255, 255, 100); } @Override public Mat apply(Mat rgba) { /* HSV first */ Imgproc.cvtColor(rgba, mRgb, Imgproc.COLOR_RGBA2RGB); Imgproc.cvtColor(mRgb, mHsv, Imgproc.COLOR_RGB2HSV); /* get only black */ Core.inRange(mHsv, mLowerBlack, mUpperBlack, mMatMaskBlack); /* invert it */ Core.bitwise_not(mMatMaskBlack, mMatMaskBlackInv); /* convert back to colorspace expected */ Imgproc.cvtColor(mMatMaskBlackInv, mRgbaDst, Imgproc.COLOR_GRAY2RGBA); return mRgbaDst; } } class NormalizerFilter implements Filter { private Mat mRgbaDst; /* CV_8UC4 */ private double mAlpha, mBeta; private int mNormType; NormalizerFilter(int cols, int rows, double mAlpha, double mBeta, int mNormType) { mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4); setAlpha(mAlpha); setBeta(mBeta); setNormType(mNormType); } NormalizerFilter(int cols, int rows, double mAlpha, double mBeta) { this(cols, rows, mAlpha, mBeta, Core.NORM_MINMAX); } NormalizerFilter(int cols, int rows) { this(cols, rows, 0.0, 255.0); } @Override public Mat apply(Mat src) { Core.normalize(src, mRgbaDst, mAlpha, mBeta, mNormType); return mRgbaDst; } public double getAlpha() { return mAlpha; } public void setAlpha(double mAlpha) { this.mAlpha = mAlpha; } public double getBeta() { return mBeta; } public void setBeta(double mBeta) { this.mBeta = mBeta; } public int getNormType() { return mNormType; } public void setNormType(int mNormType) { this.mNormType = mNormType; } } class ContrastFilter implements Filter { private final Mat mRgbaDst; private final Mat mLut; public ContrastFilter(int rows, int cols, int mMin, int mMax) { mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4); mLut = new MatOfInt(); SplineInterpolator si = new SplineInterpolator(); UnivariateFunction f = si.interpolate(new double[]{0, mMin, mMax, 255}, new double[]{0, 0, 255, 255}); /* create my mLut */ mLut.create(256, 1, CvType.CV_8UC4); for (int i = 0; i < 256; i++) { final double v = f.value(i); /* r, g, b */ mLut.put(i, 0, v, v, v, i); /* alpha not touched */ } } @Override public Mat apply(Mat src) { Core.LUT(src, mLut, mRgbaDst); return mRgbaDst; } } public class CameraActivity extends Activity implements CameraBridgeViewBase.CvCameraViewListener2 { private static final String TAG = "ActivityCamera"; private boolean mOpenCvLoaded = false; private CameraBridgeViewBase mPreview; private Filter mGradeFilter; private Filter mGraphFilter; private Filter mNormalizeFilter; private Filter mContrastFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); /* Keep the screen on */ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); /* start openCV */ /* try static initialization */ if (OpenCVLoader.initDebug()) { Log.i(TAG, "OpenCV loaded successfully (static initialization)"); mOpenCvLoaded = true; return; } /* binaries not included, use OpenCV manager */ Log.i(TAG, "OpenCV libs not included on APK, trying async initialization"); OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_10, this, new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case BaseLoaderCallback.SUCCESS: Log.i(TAG, "OpenCV loaded successfully (async initialization)"); runOnUiThread(new Runnable() { @Override public void run() { mOpenCvLoaded = true; createCameraPreview(); } }); break; default: super.onManagerConnected(status); break; } } }); } private void createCameraPreview() { /* Create our Preview */ if (mPreview == null) { mPreview = (CameraBridgeViewBase) findViewById(R.id.camera_view); mPreview.setVisibility(SurfaceView.VISIBLE); mPreview.setCvCameraViewListener(this); } if (mOpenCvLoaded) { mPreview.enableView(); } } @Override public void onResume() { super.onResume(); createCameraPreview(); } @Override protected void onDestroy() { super.onDestroy(); if (mPreview != null) { mPreview.disableView(); } } @Override protected void onStop() { super.onStop(); if (mPreview != null) { mPreview.disableView(); } } @Override public void onCameraViewStarted(int width, int height) { mGradeFilter = new GradeFilter(height, width); mGraphFilter = new GraphFilter(height, width); mNormalizeFilter = new NormalizerFilter(height, width, 100, 200); mContrastFilter = new ContrastFilter(height, width, 100, 140); } @Override public void onCameraViewStopped() { } @Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { /* show previews */ Mat src = null, bottomLeft = null, topLeft = null, topRight = null, bottomRight = null; src = inputFrame.rgba(); Mat grade = mGradeFilter.apply(src); Mat graph = mGraphFilter.apply(src); Mat srcNormalized = mContrastFilter.apply(src); Mat gradeNormalized = mGradeFilter.apply(srcNormalized); Mat graphNormalized = mGraphFilter.apply(srcNormalized); topLeft = grade; bottomLeft = gradeNormalized; topRight = graph; bottomRight = graphNormalized; drawMini(src, topLeft, bottomLeft, topRight, bottomRight); return src; } private void drawMini(Mat dst, Mat topLeft, Mat bottomLeft, Mat topRight, Mat bottomRight) { int dstHeight = dst.rows(); int dstWidth = dst.cols(); int dstRoiHeight = dstHeight / 3; int dstRoiWidth = dstWidth / 3; Mat dstRoi; if (topLeft != null) { /* draw topLeft into top left corner */ dstRoi = dst.submat(0, dstRoiHeight, 0, dstRoiWidth); Imgproc.resize(topLeft, dstRoi, dstRoi.size()); } if (bottomLeft != null) { /* draw bottomLeft into bottom left corner */ dstRoi = dst.submat(dstHeight - dstRoiHeight, dstHeight, 0, dstRoiWidth); Imgproc.resize(bottomLeft, dstRoi, dstRoi.size()); } if (topRight != null) { /* draw topRight into top right corner */ dstRoi = dst.submat(0, dstRoiHeight, dstWidth - dstRoiWidth, dstWidth); Imgproc.resize(topRight, dstRoi, dstRoi.size()); } if (bottomRight != null) { /* draw bottomRight into bottom right corner */ dstRoi = dst.submat(dstHeight - dstRoiHeight, dstHeight, dstWidth - dstRoiWidth, dstWidth); Imgproc.resize(bottomRight, dstRoi, dstRoi.size()); } } }
package com.parrot.arsdk.arsal; import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import android.annotation.TargetApi; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothGattDescriptor; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.bluetooth.BluetoothAdapter; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Looper; import com.parrot.arsdk.arsal.ARSALPrint; @TargetApi(18) public class ARSALBLEManager { private static String TAG = "ARSALBLEManager"; private static final UUID ARSALBLEMANAGER_CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); private static final int ARSALBLEMANAGER_CONNECTION_TIMEOUT_SEC = 30; private static final int GATT_INTERNAL_ERROR = 133; private static final int GATT_INTERRUPT_ERROR = 8; private static final int GATT_CONN_FAIL_ESTABLISH = 62; private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics; private Context context; private BluetoothManager bluetoothManager; private BluetoothAdapter bluetoothAdapter; private BluetoothDevice deviceBLEService; private BluetoothGatt activeGatt; private ARSALBLEManagerListener listener; private HashMap<String, ARSALManagerNotification> registeredNotificationCharacteristics = new HashMap<String, ARSALManagerNotification>(); private Semaphore connectionSem; private Semaphore disconnectionSem; private Semaphore discoverServicesSem; private Semaphore discoverCharacteristicsSem; private Semaphore configurationSem; private ARSAL_ERROR_ENUM connectionError; private ARSAL_ERROR_ENUM discoverServicesError; private ARSAL_ERROR_ENUM discoverCharacteristicsError; private ARSAL_ERROR_ENUM configurationCharacteristicError; private ARSAL_ERROR_ENUM writeCharacteristicError; private boolean askDisconnection; private boolean isDiscoveringServices; private boolean isDiscoveringCharacteristics; private boolean isConfiguringCharacteristics; private boolean isDeviceConnected = false; public class ARSALManagerNotificationData { public BluetoothGattCharacteristic characteristic = null; public byte[] value = null; public ARSALManagerNotificationData(BluetoothGattCharacteristic _characteristic, byte[] _value) { this.characteristic = _characteristic; this.value = _value; } } public class ARSALManagerNotification { private Semaphore readCharacteristicSem = new Semaphore(0); private Lock readCharacteristicMutex = new ReentrantLock(); List<BluetoothGattCharacteristic> characteristics = null; ArrayList<ARSALManagerNotificationData> notificationsArray = new ArrayList<ARSALManagerNotificationData>(); public ARSALManagerNotification(List<BluetoothGattCharacteristic> characteristicsArray) { this.characteristics = characteristicsArray; } void addNotification(ARSALManagerNotificationData notificationData) { readCharacteristicMutex.lock(); notificationsArray.add(notificationData); readCharacteristicMutex.unlock(); synchronized (readCharacteristicSem) { readCharacteristicSem.notify(); } } int getAllNotification(List<ARSALManagerNotificationData> getNoticationsArray, int maxCount) { ArrayList<ARSALManagerNotificationData> removeNotifications = new ArrayList<ARSALManagerNotificationData>(); readCharacteristicMutex.lock(); for (int i = 0; (i < maxCount) && (i < notificationsArray.size()); i++) { ARSALManagerNotificationData notificationData = notificationsArray.get(i); getNoticationsArray.add(notificationData); removeNotifications.add(notificationData); } for (int i = 0; (i < removeNotifications.size()); i++) { notificationsArray.remove(removeNotifications.get(i)); } readCharacteristicMutex.unlock(); return getNoticationsArray.size(); } /** * Waits for a notification to occur, unless timeout expires first. * * @param timeout timeout value in milliseconds. 0 means no timeout. */ boolean waitNotification(long timeout) { boolean ret = true; try { if (timeout == 0) { readCharacteristicSem.acquire(); } else { readCharacteristicSem.tryAcquire(timeout, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { ret = false; } return ret; } boolean waitNotification() { return waitNotification(0); } void signalNotification() { readCharacteristicSem.release(); } } private static class ARSALBLEManagerHolder { private final static ARSALBLEManager instance = new ARSALBLEManager(); } public static ARSALBLEManager getInstance(Context context) { ARSALBLEManager manager = ARSALBLEManagerHolder.instance; manager.setContext(context); return manager; } private synchronized void setContext(Context context) { if (this.context == null) { if (context == null) { throw new IllegalArgumentException("Context must not be null"); } this.context = context; } initialize(); } public boolean initialize() { boolean result = true; if (bluetoothManager == null) { bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null) { ARSALPrint.e(TAG, "Unable to initialize BluetoothManager."); ARSALPrint.e(TAG, "initialize: Unable to initialize BluetoothManager."); result = false; } } bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) { ARSALPrint.e(TAG, "Unable to obtain a BluetoothAdapter."); ARSALPrint.e(TAG, "initialize: Unable to obtain a BluetoothAdapter."); result = false; } return result; } private Handler mUIHandler; /** * Constructor */ private ARSALBLEManager() { this.context = null; this.deviceBLEService = null; this.activeGatt = null; mUIHandler = new Handler(Looper.getMainLooper()); listener = null; connectionSem = new Semaphore(0); disconnectionSem = new Semaphore(0); discoverServicesSem = new Semaphore(0); discoverCharacteristicsSem = new Semaphore(0); configurationSem = new Semaphore(0); askDisconnection = false; isDiscoveringServices = false; isDiscoveringCharacteristics = false; isConfiguringCharacteristics = false; connectionError = ARSAL_ERROR_ENUM.ARSAL_OK; discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_OK; discoverCharacteristicsError = ARSAL_ERROR_ENUM.ARSAL_OK; configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_OK; } /** * Destructor */ public void finalize() throws Throwable { try { disconnect(); } finally { super.finalize(); } } public boolean isDeviceConnected() { boolean ret = false; synchronized (this) { if (activeGatt != null && isDeviceConnected) { ret = true; } } return ret; } private BluetoothGatt connectionGatt; @TargetApi(18) public ARSAL_ERROR_ENUM connect(BluetoothDevice deviceBLEService) { ARSALPrint.e(TAG, "connecting to " + deviceBLEService); ARSAL_ERROR_ENUM result = ARSAL_ERROR_ENUM.ARSAL_OK; synchronized (this) { /* if there is an active activeGatt, disconnecting it */ if (activeGatt != null) { disconnect(); } /* reset */ ARSALPrint.d(TAG, "resetting connection objects"); reset(); connectionError = ARSAL_ERROR_ENUM.ARSAL_OK; /* connection to the new activeGatt */ ARSALPrint.e(TAG, "connection to the new activeGatt"); ARSALBLEManager.this.deviceBLEService = bluetoothAdapter.getRemoteDevice(deviceBLEService.getAddress()); mUIHandler.post(new Runnable() { @Override public void run() { connectionGatt = ARSALBLEManager.this.deviceBLEService.connectGatt(context, false, gattCallback); if (connectionGatt == null) { ARSALPrint.e(TAG, "connect (connectionGatt == null)"); connectionError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; } } }); /* wait the connect semaphore*/ try { ARSALPrint.d(TAG, "try acquiring connection semaphore "); boolean aquired = connectionSem.tryAcquire(ARSALBLEMANAGER_CONNECTION_TIMEOUT_SEC, TimeUnit.SECONDS); if (aquired) { // Sleep for 100 ms to get a stabilized state for connectionError // In fact, it is possible in some cases for connectionError to be modified several // times in a very short time by the BLE onConnectionStateChange callback // In these cases, we can retrieve an old value for connectionError, so we wait // and pray for having the good value when we wake up try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } result = connectionError; ARSALPrint.d(TAG, "aquired: " + result); } else { ARSALPrint.w(TAG, "failed acquiring connection semaphore"); /* Connection failed */ result = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; } ARSALPrint.d(TAG, "result : " + result); } catch (InterruptedException e) { e.printStackTrace(); } ARSALPrint.d(TAG, "activeGatt : " + activeGatt + ", result: " + result); mUIHandler.post(new Runnable() { @Override public void run() { if (activeGatt != null) { // TODO see connectionGatt = null; } else { /* Connection failed */ if (connectionGatt != null) { disconnectGatt(); connectionGatt.close(); connectionGatt = null; } } } }); } ARSALPrint.d(TAG, "connect ends with result: " + result); return result; } private void disconnectGatt() { mUIHandler.post(new Runnable() { @Override public void run() { boolean manualDisconnectGatt = true; if (bluetoothManager != null) { BluetoothGatt gatt = activeGatt; if (gatt != null && bluetoothManager.getConnectionState(gatt.getDevice(), BluetoothProfile.GATT) == BluetoothProfile.STATE_CONNECTED) { manualDisconnectGatt = false; gatt.disconnect(); } } if (manualDisconnectGatt) { ARSALPrint.d(TAG, "disconnect gatt manually " + bluetoothManager + " " + activeGatt); disconnectionSem.release(); } } }); } public void disconnect() { //synchronized (this) if (activeGatt != null) { askDisconnection = true; disconnectGatt(); ARSALPrint.d(TAG, "wait the disconnect semaphore"); /* wait the disconnect Semaphore*/ try { boolean acquire = disconnectionSem.tryAcquire(ARSALBLEMANAGER_CONNECTION_TIMEOUT_SEC, TimeUnit.SECONDS); if (!acquire) { ARSALPrint.d(TAG, "disconnect semaphore not acquired. Manually disconnect Gatt"); onDisconectGatt(); } } catch (InterruptedException e) { e.printStackTrace(); } askDisconnection = false; } } public ARSAL_ERROR_ENUM discoverBLENetworkServices() { ARSAL_ERROR_ENUM result = ARSAL_ERROR_ENUM.ARSAL_OK; synchronized (this) { /* If there is an active Gatt, disconnect it */ if (activeGatt != null && isDeviceConnected) { isDiscoveringServices = true; discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_OK; mUIHandler.post(new Runnable() { @Override public void run() { /* run the discovery of the activeGatt services */ boolean discoveryRes = activeGatt.discoverServices(); if (!discoveryRes) { discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_ERROR; discoverServicesSem.release(); } } }); /* wait the discoverServices semaphore*/ try { discoverServicesSem.acquire(); result = discoverServicesError; } catch (InterruptedException e) { e.printStackTrace(); result = ARSAL_ERROR_ENUM.ARSAL_ERROR; } isDiscoveringServices = false; } else { result = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; } } return result; } public BluetoothGatt getGatt() { return activeGatt; } public void setListener(ARSALBLEManagerListener listener) { this.listener = listener; } private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) { ARSALPrint.w(TAG, "onConnectionStateChange : status = " + status + " newState = " + newState); if (newState == BluetoothProfile.STATE_DISCONNECTED) { if ((activeGatt != null) && (gatt == activeGatt)) { isDeviceConnected = false; onDisconectGatt(); } else { ARSALPrint.w(TAG, "Disconnection of another gatt"); gatt.close(); } } switch (status) { case BluetoothGatt.GATT_SUCCESS: if (newState == BluetoothProfile.STATE_CONNECTED) { mUIHandler.post(new Runnable() { @Override public void run() { activeGatt = gatt; isDeviceConnected = true; connectionError = ARSAL_ERROR_ENUM.ARSAL_OK; /* post a connect Semaphore */ connectionSem.release(); } }); } break; case GATT_INTERNAL_ERROR: ARSALPrint.e(TAG, "On connection state change: GATT_INTERNAL_ERROR (133 status) newState:" + newState); connectionError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_CONNECTION; /* post a connect Semaphore */ connectionSem.release(); break; /* triggered when pull out the battery of delos ( special for Android 5.0+ ) */ case GATT_INTERRUPT_ERROR: ARSALPrint.e(TAG, "On connection state change: GATT_INTERRUPT_ERROR (8 status) newState:" + newState); connectionError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_CONNECTION; connectionSem.release(); break; case BluetoothGatt.GATT_FAILURE: ARSALPrint.w(TAG, "On connection state change: GATT_FAILURE newState:" + newState); /* post a connect Semaphore */ connectionSem.release(); break; case GATT_CONN_FAIL_ESTABLISH: ARSALPrint.e(TAG, "On connection state change: GATT_CONN_FAIL_ESTABLISH (62 status) newState:" + newState); connectionError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_CONNECTION; /* post a connect Semaphore */ connectionSem.release(); break; default: ARSALPrint.e(TAG, "unknown status : " + status); break; } } @Override // New services discovered public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { ARSALPrint.w(TAG, "On services discovered state:" + status); /* the discovery is not successes */ discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_SERVICES_DISCOVERING; } discoverServicesSem.release(); } @Override /* Result of a characteristic read operation */ public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //Do Nothing } @Override public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { //Do Nothing } @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { /* check the status */ if (status != BluetoothGatt.GATT_SUCCESS) { configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_CHARACTERISTIC_CONFIGURING; } /* post a configuration Semaphore */ configurationSem.release(); } @Override /* Characteristic notification */ /*public void onCharacteristicChanged (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { readCharacteristicMutex.lock(); characteristicNotifications.add(characteristic); readCharacteristicMutex.unlock(); // post a readCharacteristic Semaphore readCharacteristicSem.release(); }*/ public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { ARSALManagerNotification foundNotification = null; Set<String> keys = registeredNotificationCharacteristics.keySet(); for (String key : keys) { ARSALManagerNotification notification = registeredNotificationCharacteristics.get(key); for (BluetoothGattCharacteristic characteristicItem : notification.characteristics) { if (characteristicItem.getUuid().toString().contentEquals(characteristic.getUuid().toString())) { foundNotification = notification; break; } } if (foundNotification != null) { break; } } if (foundNotification != null) { byte[] value = characteristic.getValue(); byte[] newValue = null; if (value != null) { newValue = new byte[value.length]; System.arraycopy(value, 0, newValue, 0, value.length); } else { newValue = new byte[0]; } ARSALManagerNotificationData notificationData = new ARSALManagerNotificationData(characteristic, newValue); foundNotification.addNotification(notificationData); foundNotification.signalNotification(); } } //Characteristic.WRITE_TYPE_NO_RESPONSE dosen't have reply /*@Override public void onCharacteristicWrite (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //ARSALPrint.d(TAG, "onCharacteristicWrite " + status); }*/ }; public ARSAL_ERROR_ENUM setCharacteristicNotification(BluetoothGattService service, BluetoothGattCharacteristic characteristic) { ARSAL_ERROR_ENUM result = ARSAL_ERROR_ENUM.ARSAL_OK; synchronized (this) { BluetoothGatt localActiveGatt = activeGatt; /* If there is an active Gatt, disconnect it */ if (localActiveGatt != null) { isConfiguringCharacteristics = true; configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_OK; boolean notifSet = localActiveGatt.setCharacteristicNotification(characteristic, true); BluetoothGattDescriptor descriptor = characteristic.getDescriptor(ARSALBLEMANAGER_CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID); if (descriptor != null) { boolean valueSet = descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); boolean descriptorWriten = localActiveGatt.writeDescriptor(descriptor); /* wait the configuration semaphore*/ try { configurationSem.acquire(); result = configurationCharacteristicError; } catch (InterruptedException e) { e.printStackTrace(); result = ARSAL_ERROR_ENUM.ARSAL_ERROR; } } else { ARSALPrint.w(TAG, "setCharacteristicNotification " + characteristic.getUuid() + " - BluetoothGattDescriptor " + ARSALBLEMANAGER_CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID + " is null."); result = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_CHARACTERISTIC_CONFIGURING; } isConfiguringCharacteristics = false; } else { result = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; } } return result; } public boolean writeData(byte data[], BluetoothGattCharacteristic characteristic) { boolean result = false; BluetoothGatt localActiveGatt = activeGatt; if ((localActiveGatt != null) && (characteristic != null) && (data != null)) { characteristic.setValue(data); characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); result = localActiveGatt.writeCharacteristic(characteristic); } return result; } //public void registerNotificationCharacteristics(ArrayList<BluetoothGattCharacteristic> characteristicsArray, String readCharacteristicKey) public void registerNotificationCharacteristics(List<BluetoothGattCharacteristic> characteristicsArray, String readCharacteristicKey) { this.registeredNotificationCharacteristics.put(readCharacteristicKey, new ARSALManagerNotification(characteristicsArray)); } public boolean unregisterNotificationCharacteristics(String readCharacteristicKey) { boolean result = false; ARSALManagerNotification notification = this.registeredNotificationCharacteristics.get(readCharacteristicKey); if (notification != null) { result = true; registeredNotificationCharacteristics.remove(notification); } return result; } public boolean cancelReadNotification(String readCharacteristicKey) { boolean result = false; ARSALManagerNotification notification = this.registeredNotificationCharacteristics.get(readCharacteristicKey); if (notification != null) { result = true; notification.signalNotification(); } return result; } public boolean readData(BluetoothGattCharacteristic characteristic) { return activeGatt.readCharacteristic(characteristic); } /** * Read notification data. Block until data is received or timeout occurs. * * @param notificationsArray a list where the received data will be put. * @param maxCount maximum number of notifications to receive. * @param readCharacteristicKey the characteristic to read notifications from. * @param timeout the maximum time in milliseconds to wait for data before failing. * 0 means infinite timeout. */ public boolean readDataNotificationData(List<ARSALManagerNotificationData> notificationsArray, int maxCount, String readCharacteristicKey, long timeout) { boolean result = false; ARSALManagerNotification notification = this.registeredNotificationCharacteristics.get(readCharacteristicKey); if (notification != null) { notification.waitNotification(timeout); if (notification.notificationsArray.size() > 0) { notification.getAllNotification(notificationsArray, maxCount); result = true; } } return result; } public boolean readDataNotificationData(List<ARSALManagerNotificationData> notificationsArray, int maxCount, String readCharacteristicKey) { return readDataNotificationData(notificationsArray, maxCount, readCharacteristicKey, 0); } /*public boolean readData (List<BluetoothGattCharacteristic> characteristicArray) { boolean result = false; // wait the readCharacteristic semaphore try { readCharacteristicSem.acquire (); if (characteristicNotifications.size() > 0) { readCharacteristicMutex.lock(); characteristicArray.addAll(characteristicNotifications); characteristicNotifications.clear(); readCharacteristicMutex.unlock(); result = true; } } catch (InterruptedException e) { e.printStackTrace(); } return result; }*/ public void unlock() { /* post all Semaphore to unlock the all the functions */ connectionSem.release(); configurationSem.release(); discoverServicesSem.release(); discoverCharacteristicsSem.release(); //readCharacteristicSem.release(); for (String key : registeredNotificationCharacteristics.keySet()) { ARSALManagerNotification notification = registeredNotificationCharacteristics.get(key); notification.signalNotification(); } /* disconnectionSem is not post because: * if the connection is fail, disconnect is not call. * if the connection is successful, the BLE callback is always called. * the disconnect function is called after the join of the network threads. */ } public void reset() { synchronized (this) { /* reset all Semaphores */ while (connectionSem.tryAcquire() == true) { /* Do nothing*/ } while (disconnectionSem.tryAcquire() == true) { /* Do nothing*/ } while (discoverServicesSem.tryAcquire() == true) { /* Do nothing*/ } while (discoverCharacteristicsSem.tryAcquire() == true) { /* Do nothing*/ } /*while (readCharacteristicSem.tryAcquire() == true) {*/ /* Do nothing*/ while (configurationSem.tryAcquire() == true) { /* Do nothing*/ } for (String key : registeredNotificationCharacteristics.keySet()) { ARSALManagerNotification notification = registeredNotificationCharacteristics.get(key); notification.signalNotification(); } registeredNotificationCharacteristics.clear(); //TODO closeGatt(); } } private void onDisconectGatt() { ARSALPrint.d(TAG, "activeGatt disconnected"); /* Post disconnectionSem only if the disconnect is asked */ if (askDisconnection) { disconnectionSem.release(); } /* if activePeripheral is discovering services */ if (isDiscoveringServices) { discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; discoverServicesSem.release(); } /* if activePeripheral is discovering Characteristics */ if (isDiscoveringCharacteristics) { discoverCharacteristicsError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; discoverCharacteristicsSem.release(); } /* if activePeripheral is configuring Characteristics */ if (isConfiguringCharacteristics) { configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; configurationSem.release(); } /* Notify listener */ if (!askDisconnection) { if (listener != null) { listener.onBLEDisconnect(); } } } private void closeGatt() { mUIHandler.post(new Runnable() { @Override public void run() { if (activeGatt != null) { activeGatt.close(); activeGatt = null; } } }); } }
package com.sun.star.comp.connections; import com.sun.star.comp.loader.FactoryHelper; import com.sun.star.connection.XConnection; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.registry.XRegistryKey; public class PipedConnection implements XConnection { /** * When set to true, enables various debugging output. */ public static final boolean DEBUG = false; /** * The name of the service, the <code>JavaLoader</code> acceses this through reflection. */ static private final String __serviceName = "com.sun.star.connection.PipedConnection"; /** * Gives a factory for creating the service. * This method is called by the <code>JavaLoader</code> * <p> * @return returns a <code>XSingleServiceFactory</code> for creating the component * @param implName the name of the implementation for which a service is desired * @param multiFactory the service manager to be uses if needed * @param regKey the registryKey * @see com.sun.star.comp.loader.JavaLoader */ public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; if (implName.equals(PipedConnection.class.getName()) ) xSingleServiceFactory = FactoryHelper.getServiceFactory(PipedConnection.class, __serviceName, multiFactory, regKey); return xSingleServiceFactory; } /** * Writes the service information into the given registry key. * This method is called by the <code>JavaLoader</code> * <p> * @return returns true if the operation succeeded * @param regKey the registryKey * @see com.sun.star.comp.loader.JavaLoader */ public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { return FactoryHelper.writeRegistryServiceInfo(PipedConnection.class.getName(), __serviceName, regKey); } /** * The amount of time in milliseconds, to wait to * see check the buffers. */ protected static final int __waitTime = 10000; protected byte _buffer[] = new byte[4096]; protected int _in, _out; protected boolean _closed; protected PipedConnection _otherSide; /** * Constructs a new <code>PipedConnection</code>, sees if there * is an other side, which it should be connected to. * <p> * @param args Another side could be in index 0. */ public PipedConnection(Object args[]) throws com.sun.star.uno.RuntimeException { if (DEBUG) System.err.println(" _otherSide = (args.length == 1) ? (PipedConnection)args[0] : null; if(_otherSide != null) { if(_otherSide == this) throw new RuntimeException("can not connect to myself"); _otherSide._otherSide = this; } } /** * This is a private method, used to cummunicate * internal in the pipe. */ private synchronized void receive(byte aData[]) throws com.sun.star.io.IOException { int bytesWritten = 0; if(DEBUG) System.err.println(" while(bytesWritten < aData.length) { // wait until it is not full anymore while(_out == (_in - 1) || (_in == 0 && _out == _buffer.length - 1)) { try { notify(); // the buffer is full, signal it wait(__waitTime); } catch(InterruptedException interruptedException) { throw new com.sun.star.io.IOException(interruptedException.toString()); } } if(_closed) throw new com.sun.star.io.IOException("connection has been closed"); int bytes = 0; if(_out < _in) { bytes = Math.min(aData.length - bytesWritten, _in - _out - 1); System.arraycopy(aData, bytesWritten, _buffer, _out, bytes); } else { if(_in > 0){ bytes = Math.min(aData.length - bytesWritten, _buffer.length - _out); } else { bytes = Math.min(aData.length - bytesWritten, _buffer.length - _out - 1); } System.arraycopy(aData, bytesWritten, _buffer, _out, bytes); } bytesWritten += bytes; _out += bytes; if(_out >= _buffer.length) _out = 0; } } /** * Read the required number of bytes. * <p> * @return the number of bytes read * @param aReadBytes the outparameter, where the bytes have to be placed * @param nBytesToRead the number of bytes to read * @see com.sun.star.connections.XConnection#read */ public synchronized int read(/*OUT*/byte[][] aReadBytes, int nBytesToRead) throws com.sun.star.io.IOException, com.sun.star.uno.RuntimeException { aReadBytes[0] = new byte[nBytesToRead]; if(DEBUG) System.err.println(" // loop while not all bytes read or when closed but there is still data while(nBytesToRead > 0 && (_in != _out || !_closed)) { while(_in == _out && !_closed) { try { notify(); // the buffer is empty, signal it wait(__waitTime); // we wait for data or for the pipe to be closed } catch(InterruptedException interruptedException) { throw new com.sun.star.io.IOException(interruptedException.toString()); } } if(_in < _out) { int bytes = Math.min(nBytesToRead, _out - _in); System.arraycopy(_buffer, _in, aReadBytes[0], aReadBytes[0].length - nBytesToRead, bytes); nBytesToRead -= bytes; _in += bytes; } else if(_in > _out) { int bytes = Math.min(nBytesToRead, _buffer.length - _in); System.arraycopy(_buffer, _in, aReadBytes[0], aReadBytes[0].length - nBytesToRead, bytes); nBytesToRead -= bytes; _in += bytes; if(_in >= _buffer.length) _in = 0; } } if(nBytesToRead > 0) { // not all bytes read byte tmp[] = new byte[aReadBytes[0].length - nBytesToRead]; System.arraycopy(aReadBytes[0], 0, tmp, 0, tmp.length); aReadBytes[0] = tmp; } return aReadBytes[0].length; } /** * Write bytes. * <p> * @param aData the bytes to write * @see com.sun.star.connections.XConnection#write */ public void write(byte aData[]) throws com.sun.star.io.IOException, com.sun.star.uno.RuntimeException { _otherSide.receive(aData); } /** * Flushes the buffer, notifies if necessary the other side that new data has arrived. * <p> * @see com.sun.star.connections.XConnection#flush */ public void flush() throws com.sun.star.io.IOException, com.sun.star.uno.RuntimeException { synchronized(_otherSide) { _otherSide.notify(); } } /** * Closes the pipe. * <p> * @see com.sun.star.connections.XConnection#closed */ public synchronized void close() throws com.sun.star.io.IOException, com.sun.star.uno.RuntimeException { if(!_closed) { _closed = true; _otherSide.close(); notify(); } } /** * Gives a description of this pipe. * <p> * @return the description * @see com.sun.star.connections.XConnection#getDescription */ public String getDescription() throws com.sun.star.uno.RuntimeException { return getClass().getName(); } }
package com.james.status.services; import android.annotation.TargetApi; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.support.v4.app.NotificationCompat; import com.james.status.data.NotificationData; import com.james.status.data.PreferenceData; import com.james.status.utils.StaticUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @TargetApi(18) public class StatusService extends NotificationListenerService { private PackageManager packageManager; private StatusServiceImpl impl; @Override public void onCreate() { super.onCreate(); if (impl == null) impl = new StatusServiceImpl(this); impl.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); if (intent == null) return START_STICKY; String action = intent.getAction(); if (action == null) return START_STICKY; return impl.onStartCommand(intent, flags, startId); } @Override public void onTaskRemoved(Intent rootIntent) { if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) impl.onTaskRemoved(rootIntent); else super.onTaskRemoved(rootIntent); } @Override public void onDestroy() { impl.onDestroy(); super.onDestroy(); } @Override public void onListenerConnected() { super.onListenerConnected(); packageManager = getPackageManager(); sendNotifications(); } @Override public void onNotificationPosted(StatusBarNotification sbn) { if ((boolean) PreferenceData.STATUS_ENABLED.getValue(this) && (boolean) PreferenceData.APP_NOTIFICATIONS.getSpecificValue(this, sbn.getPackageName()) && !StaticUtils.shouldUseCompatNotifications(this) && !sbn.getPackageName().matches("com.james.status")) impl.onNotificationAdded(getKey(sbn), new NotificationData(sbn, getKey(sbn))); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { if ((boolean) PreferenceData.STATUS_ENABLED.getValue(this) && !StaticUtils.shouldUseCompatNotifications(this)) impl.onNotificationRemoved(getKey(sbn)); } private ArrayList<StatusBarNotification> getNotifications() { ArrayList<StatusBarNotification> activeNotifications = new ArrayList<>(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { try { activeNotifications.addAll(Arrays.asList(getActiveNotifications())); } catch (NullPointerException ignored) { } } return activeNotifications; } public void sendNotifications() { if (packageManager == null) packageManager = getPackageManager(); if (packageManager == null) return; if ((boolean) PreferenceData.STATUS_ENABLED.getValue(this) && !StaticUtils.shouldUseCompatNotifications(this)) { List<StatusBarNotification> notifications = getNotifications(); Collections.reverse(notifications); for (StatusBarNotification sbn : notifications) { if (sbn == null || sbn.getPackageName().matches("com.james.status")) continue; if (!((boolean) PreferenceData.APP_NOTIFICATIONS.getSpecificValue(this, sbn.getPackageName()))) continue; NotificationData notification = new NotificationData(sbn, getKey(sbn)); notification.priority = NotificationCompat.PRIORITY_DEFAULT; impl.onNotificationAdded(getKey(sbn), notification); } } } private String getKey(StatusBarNotification statusBarNotification) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) return statusBarNotification.getKey(); else return statusBarNotification.getPackageName() + "/" + String.valueOf(statusBarNotification.getId()); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * * @author Hyun Choi, Ted Pyne, Patrick Forelli */ public class CheckersGUI extends javax.swing.JFrame { //keeps track of a Board, a 2d array of JLabels to represent each tile, and JPanel to store the tiles public Board board; private JLabel[][] GUIboard; //JPanel entireGUI for the enclosure of both the board and the text private JPanel entireGUI; //outer JPanel panel for the outer board panel, boardGUI for the inner board panel private JPanel panel; private JPanel boardGUI; //JPanel for textual info; JLabels/JButton for information and toggling private JPanel text; private JLabel victoryStatus; private JLabel turnStatus; private JButton aiToggle; //AI implementation private AI ai; private boolean aiActive; private boolean selected = false; //if a piece is selected or not private int[][] currentSelected; //coordinates of the selected piece and the target area private final int MULTIPLIER = 62; //width of one tile /** * Creates new form CheckersGUI */ public CheckersGUI() { board = new Board(); GUIboard = new JLabel[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { //if(board.getPiece(i,j) != null) GUIboard[i][j] = new JLabel(); } } entireGUI = new JPanel(); //outer JPanel to store the boardGUI and the textual information entireGUI.setLayout(new BoxLayout(entireGUI, BoxLayout.X_AXIS)); aiActive = false; //by default, AI is inactive text = new JPanel(); //inner JPanel to hold text text.setLayout(new GridLayout (3,2)); initializeText(); currentSelected = new int[2][2]; boardGUI = new JPanel(); boardGUI.setLayout(new GridLayout(8,8)); //tiles in a GridLayout of 8x8 boardGUI.addMouseListener(new MouseAdapter() { //essence of the GUI's click detection int selected =0; public void mouseClicked(MouseEvent e) { if (selected==0) //if nothing is selected { currentSelected[0]=arrayCoord(pressed(e)); //store coordinates of the press in array selected++; System.out.println("FIRST SELECTION"); //if invalid selection, revert if(!board.isValidSelection(currentSelected[0][1], currentSelected[0][0])){ currentSelected = new int[2][2]; selected=0; System.out.println("INVALID FIRST SELECTION"); } } else if (selected ==1) //target tile { //using the coordinates, make a move and render the board on the GUI System.out.println(currentSelected[0][1] + " " + currentSelected[0][0] + " " + currentSelected[1][1] + " " + currentSelected[1][0]); currentSelected[1]=arrayCoord(pressed(e)); TurnProcessor turnProc = new TurnProcessor(currentSelected[0][1], currentSelected[0][0], currentSelected[1][1], currentSelected[1][0], board); if(currentSelected[1][1]==currentSelected[0][1] && currentSelected[0][0] == currentSelected[1][0]){ currentSelected = new int[2][2]; selected=0; System.out.println("DESELECTING"); } else if(!turnProc.isValidTurn()){ selected = 1; System.out.println("INVALID SELECTION"); } else{ move(currentSelected); renderBoard(); //revert to original state currentSelected = new int[2][2]; selected=0; System.out.println("MAKE VALID MOVE"); } } if (ai!=null) //make AI move if AI is active { ai.makeMove(); renderBoard(); } } }); panel = new JPanel(); //enclose GridLayout within JPanel on the JFrame panel.add(boardGUI); renderBoard(); //render board on the GUI } public void renderBoard() //method to arrange images to form the board { boolean previousColorIsWhite = false; //for arrangement for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board.getPiece(i,j) != null) { if (board.getPiece(i,j).getIsWhite())//if the piece is white { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhiteking.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhite.png"))); } else //so that means it's a red { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithredking.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithred.png"))); } previousColorIsWhite=true; } else //if no piece, then blank tile (white or green) { if (previousColorIsWhite) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/greentile.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitetile.png"))); previousColorIsWhite = !previousColorIsWhite; } boardGUI.add(GUIboard[i][j]); } previousColorIsWhite=!previousColorIsWhite; } refreshText(); //update the text fields //combine the two components of the GUI entireGUI.add(panel); entireGUI.add(text); setResizable(false); //window cannot be resized //make it visible pack(); this.setContentPane(entireGUI); setVisible(true); } private void initializeText() { final JLabel VICTORY = new JLabel ("VICTORY"); victoryStatus = new JLabel(); final JLabel TURN = new JLabel ("TURN"); turnStatus = new JLabel(); final JLabel AI = new JLabel ("AI STATUS"); aiToggle = new JButton("AI INACTIVE"); aiToggle.addActionListener(new ActionListener() { //button for toggling AI activation status public void actionPerformed(ActionEvent e) { aiActive = !aiActive; if (aiActive) { ai = new AI(board); aiToggle.setText("AI ACTIVE"); } else { aiToggle.setText("AI INACTIVE"); ai = null; } } }); text.add(VICTORY); text.add(victoryStatus); text.add(TURN); text.add(turnStatus); text.add(AI); text.add(aiToggle); } public void refreshText() { if (board.gameIsWon()!=null) //set victor if there is one { if (board.gameIsWon().getIsWhite()) { victoryStatus.setText("WHITE"); } else { victoryStatus.setText("BLACK"); } } else { victoryStatus.setText("???"); } if (board.isWhiteTurn()) //display turn turnStatus.setText("WHITE"); else turnStatus.setText("RED"); } private int[] pressed(MouseEvent e) //returns pixel coordinates where clicked { Component c = boardGUI.findComponentAt(e.getX(), e.getY()); int[] coordinates = new int[2]; coordinates[0] = e.getX(); coordinates[1] = e.getY(); return coordinates; } private int[] arrayCoord(int[] pixelCoord) //returns coordinates within the checkerboard, limited to [0,0] to [7,7] { for (int i=0; i<2; i++) pixelCoord[i] /= MULTIPLIER; return pixelCoord; } private void move(int[][] currentSelected) //moves the pieces in the Board variable { board.makeMove(currentSelected[0][1],currentSelected[0][0],currentSelected[1][1],currentSelected[1][0]); } public static void run () //runs the game with debugging console { CheckersGUI gui = new CheckersGUI(); gui.renderBoard(); } }
package com.parrot.arsdk.arutils; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.util.Log; import android.content.Context; import com.parrot.arsdk.arsal.ARSALBLEManager; import com.parrot.arsdk.arsal.ARSALBLEManager.ARSALManagerNotificationData; import com.parrot.arsdk.arsal.ARSALPrint; import com.parrot.arsdk.arsal.ARSAL_ERROR_ENUM; import com.parrot.arsdk.arsal.ARUUID; public class ARUtilsBLEFtp { private static final String APP_TAG = "BLEFtp "; public final static String BLE_GETTING_KEY = "kARUTILS_BLEFtp_Getting"; public final static String BLE_PACKET_WRITTEN = "FILE WRITTEN"; public final static String BLE_PACKET_NOT_WRITTEN = "FILE NOT WRITTEN"; public final static String BLE_PACKET_EOF = "End of Transfer"; public final static String BLE_PACKET_RENAME_SUCCESS = "Rename successful"; public final static String BLE_PACKET_RENAME_FROM_SUCCESS = "Rename successful"; public final static String BLE_PACKET_DELETE_SUCCESS = "Delete successful"; public final static int BLE_PACKET_MAX_SIZE = 132; public final static int BLE_PACKET_BLOCK_PUTTING_COUNT = 500; public final static int BLE_PACKET_BLOCK_GETTING_COUNT = 100; public final static long BLE_PACKET_WRITE_SLEEP = 35; /* 20ms or 30ms*/ public final static int BLE_MTU_SIZE = 20; public final static byte BLE_BLOCK_HEADER_START = 0x02; //Paquet de Start : ID = 10 (en binaire) + data public final static byte BLE_BLOCK_HEADER_CONTINUE = 0x00; //Paquet de "data" : ID = 00 + data public final static byte BLE_BLOCK_HEADER_STOP = 0x01; //Paquet de Stop : ID = 01 + data public final static byte BLE_BLOCK_HEADER_SINGLE = 0x03; //Paquet unique : ID = 11 + data private ARSALBLEManager bleManager = null; private BluetoothGatt gattDevice = null; private int port; private int connectionCount = 0; private Lock connectionLock = new ReentrantLock(); private BluetoothGattCharacteristic transferring = null; private BluetoothGattCharacteristic getting = null; private BluetoothGattCharacteristic handling = null; private ArrayList<BluetoothGattCharacteristic> arrayGetting = null; private native void nativeProgressCallback(long nativeCallbackObject, float percent); private native static void nativeJNIInit(); static { nativeJNIInit(); } private ARUtilsBLEFtp() { } private static class ARUtilsBLEFtpHolder { private final static ARUtilsBLEFtp instance = new ARUtilsBLEFtp(); } public static ARUtilsBLEFtp getInstance(Context context) { ARUtilsBLEFtp instance = ARUtilsBLEFtpHolder.instance; if (context == null) { throw new IllegalArgumentException("Context must not be null"); } instance.setBLEManager(context); return instance; } private synchronized void setBLEManager(Context context) { if (this.bleManager == null) { if (context == null) { throw new IllegalArgumentException("Context must not be null"); } this.bleManager = ARSALBLEManager.getInstance(context); } } public boolean registerDevice(BluetoothGatt gattDevice, int port) { boolean ret = true; if (connectionCount == 0) { this.gattDevice = gattDevice; this.port = port; connectionCount++; ret = registerCharacteristics(); } else if ((this.gattDevice == gattDevice) && (this.port == port)) { connectionCount++; } else { ARSALPrint.e("DBG", APP_TAG + "Bad parameters"); ret = false; } return ret; } public boolean unregisterDevice() { boolean ret = true; if (connectionCount > 0) { if (connectionCount == 1) { this.gattDevice = null; this.port = 0; this.transferring = null; this.getting = null; this.handling = null; unregisterCharacteristics(); } connectionCount } else { ARSALPrint.e("DBG", APP_TAG + "Bad parameters"); ret = false; } return ret; } public boolean registerCharacteristics() { List<BluetoothGattService> services = gattDevice.getServices(); ARSAL_ERROR_ENUM error = ARSAL_ERROR_ENUM.ARSAL_OK; boolean ret = true; ARSALPrint.d("DBG", APP_TAG + "registerCharacteristics"); Iterator<BluetoothGattService> servicesIterator = services.iterator(); while (servicesIterator.hasNext()) { BluetoothGattService service = servicesIterator.next(); String serviceUuid = ARUUID.getShortUuid(service.getUuid()); String name = ARUUID.getShortUuid(service.getUuid()); ARSALPrint.d("DBG", APP_TAG + "service " + name); if (serviceUuid.startsWith(String.format("fd%02d", this.port))) { List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); Iterator<BluetoothGattCharacteristic> characteristicsIterator = characteristics.iterator(); while (characteristicsIterator.hasNext()) { BluetoothGattCharacteristic characteristic = characteristicsIterator.next(); String characteristicUuid = ARUUID.getShortUuid(characteristic.getUuid()); ARSALPrint.d("DBG", APP_TAG + "characteristic " + characteristicUuid); if (characteristicUuid.startsWith(String.format("fd%02d", this.port + 1))) { this.transferring = characteristic; } else if (characteristicUuid.startsWith(String.format("fd%02d", this.port + 2))) { this.arrayGetting = new ArrayList<BluetoothGattCharacteristic>(); this.arrayGetting.add(characteristic); this.getting = characteristic; ARSALPrint.d("DBG", APP_TAG + "set " + error.toString()); } else if (characteristicUuid.startsWith(String.format("fd%02d", this.port + 3))) { this.handling = characteristic; } } } } if ((transferring != null) && (getting != null) && (handling != null)) { /*error = bleManager.setCharacteristicNotification(gettingService, this.getting); if (error != ARSAL_ERROR_ENUM.ARSAL_OK) { ARSALPrint.e("DBG", APP_TAG + "set " + error.toString()); ret = false; }*/ if (ret == true) { bleManager.registerNotificationCharacteristics(this.arrayGetting, BLE_GETTING_KEY); } } return ret; } public boolean unregisterCharacteristics() { boolean ret = true; ARSALPrint.d("DBG", APP_TAG + "unregisterCharacteristics"); ret = bleManager.unregisterNotificationCharacteristics(BLE_GETTING_KEY); return ret; } /* Do nothing*/ /* Check that the buffer is large enough to hold the current * data block. If it isn't, enlarge it by one allocation unit. */ if ((bufferIndex + blockLen) > buffer.length) { int minSize = bufferIndex + blockLen; int newSize = buffer.length + BLE_PACKET_MAX_SIZE; /* Just in the (unlikely) event when block would be larger * than BLE_PACKET_MAX_SIZE. */ if (newSize < minSize) { newSize = minSize; } ARSALPrint.d("DBG", APP_TAG + "buffer alloc size " + buffer.length + " -> " + newSize); byte[] oldBuffer = buffer; buffer = new byte[newSize]; System.arraycopy(oldBuffer, 0, buffer, 0, oldBuffer.length); } /* Copy the current block to the packet buffer. */ System.arraycopy(block, blockIndex, buffer, bufferIndex, blockLen); bufferIndex += blockLen; blockCount++; ARSALPrint.d("DBG", APP_TAG + "block " + blockCount +", "+ blockLen +", "+ bufferIndex); } } else { //ret = false; ARSALPrint.d("DBG", APP_TAG + "Empty block "); } receivedNotifications.remove(notificationData); } } while ((ret == true) && (end == false)); if (bufferIndex > 0) { /* Allocate a buffer just the right size copy the read packet to it. */ byte[] finalBuffer = new byte[bufferIndex]; System.arraycopy(buffer, 0, finalBuffer, 0, bufferIndex); if ((notificationArray != null) && (notificationArray.length > 0)) { notificationArray[0] = finalBuffer; } else { ret = false; } } return ret; } private boolean sendPutData(int fileSize, FileInputStream src, int resumeIndex, boolean resume, boolean abort, long nativeCallbackObject, Semaphore cancelSem) { BufferedInputStream in = new BufferedInputStream(src); byte[] buffer = new byte [BLE_PACKET_MAX_SIZE]; boolean ret = true; int packetLen = 0; int packetCount = 0; int totalPacket = 0; int totalSize = 0; boolean endFile = false; ARUtilsMD5 md5 = new ARUtilsMD5(); ARUtilsMD5 md5End = new ARUtilsMD5(); String[] md5Msg = new String[1]; md5Msg[0] = ""; String md5Txt = null; byte[] send = null; float percent = 0.f; float lastPercent = 0.f; try { if (abort == true) { endFile = true; resumeIndex = 0; resume = false; } do { if (abort == false) { packetLen = in.read(buffer, 0, BLE_PACKET_MAX_SIZE); } if (packetLen > 0) { packetCount++; totalPacket++; totalSize += packetLen; md5End.update(buffer, 0, packetLen); if ((resume == false) || ((resume == true) && (totalPacket > resumeIndex))) { md5.update(buffer, 0, packetLen); send = buffer; if (packetLen != BLE_PACKET_MAX_SIZE) { send = new byte[packetLen]; System.arraycopy(buffer, 0, send, 0, packetLen); } ret = sendBufferBlocks(send, transferring); ARSALPrint.d("DBG", APP_TAG + "packet " + packetCount + ", " + packetLen); } else { ARSALPrint.d("DBG", APP_TAG + "resume " + packetCount); } if (nativeCallbackObject != 0) { percent = ((float)totalSize / (float)fileSize) * 100.f; if ((resume == true) && (totalPacket < resumeIndex)) { if ((percent - lastPercent) > 1.f) { lastPercent = percent; nativeProgressCallback(nativeCallbackObject, percent); } } else { nativeProgressCallback(nativeCallbackObject, percent); } } if (isConnectionCanceled(cancelSem)) { ARSALPrint.e("DBG", APP_TAG + "Canceled received"); send = new byte[0]; boolean err = false; err = sendResponse(send, transferring); err = readPutMd5(md5Msg); ret = false; } } else { if (packetLen == -1) { endFile = true; } } if ((ret == true) && ((packetCount >= BLE_PACKET_BLOCK_PUTTING_COUNT) || ((endFile == true) && (packetCount > 0)))) { packetCount = 0; if ((resume == false) || ((resume == true) && (totalPacket > resumeIndex))) { md5Txt = md5.digest(); md5.initialize(); ARSALPrint.d("DBG", APP_TAG + "sending md5 " + md5Txt); md5Txt = "MD5" + md5Txt; send = md5Txt.getBytes("UTF8"); ret = sendBufferBlocks(send, transferring); if (ret == true) { ret = readPudDataWritten(); } } } } while ((ret == true) && (endFile == false)); if ((ret == true) && (endFile == true)) { send = new byte[0]; ret = sendResponse(send, transferring); if (ret == true) { ret = readPutMd5(md5Msg); } if (ret == true) { md5Txt = md5End.digest(); ARSALPrint.d("DBG", APP_TAG + "md5 end" + md5Txt); if (md5Msg[0].compareTo(md5Txt) != 0) { ARSALPrint.e("DBG", APP_TAG + "md5 end Failed"); ret = false; } else { ARSALPrint.d("DBG", APP_TAG + "md5 end ok"); } } } } catch (IOException e) { ARSALPrint.e("DBG", APP_TAG + e.toString()); ret = false; } return ret; } /*private boolean readPutResumeIndex(int[] resumeIndex) { ArrayList<ARSALManagerNotificationData> receivedNotifications = new ArrayList<ARSALManagerNotificationData>(); boolean ret = true; bleManager.readData(getting); ret = bleManager.readDataNotificationData(receivedNotifications, 1, BLE_GETTING_KEY); if (ret = true) { if (receivedNotifications.size() > 0) { ARSALManagerNotificationData notificationData = receivedNotifications.get(0); byte[] packet = notificationData.value; int packetLen = notificationData.value.length; if (packetLen == 3) { int size = (0xff & packet[0]) | (0xff00 & (packet[1] << 8)) | (0xff0000 & (packet[2] << 16)); resumeIndex[0] = size; ARSALPrint.d("DBG", APP_TAG + "resume index " + size); } else { ARSALPrint.e("DBG", APP_TAG + "eee"); ret = false; } } else { ret = false; } } return ret; }*/ private boolean readPutResumeIndex(String remoteFile, int[] resumeIndex, int[]totalSize) { double[] fileSize = new double[1]; fileSize[0] = 0.f; boolean ret = true; resumeIndex[0] = 0; ret = sizeFile(remoteFile, fileSize); if (ret == true) { resumeIndex[0] = (int)fileSize[0] / BLE_PACKET_MAX_SIZE; totalSize[0] = (int)fileSize[0]; } return ret; } private boolean readGetData(int fileSize, FileOutputStream dst, byte[][] data, long nativeCallbackObject, Semaphore cancelSem) { byte[][] notificationArray = new byte[1][]; boolean ret = true; int packetCount = 0; int totalSize = 0; int totalPacket = 0; boolean endFile = false; boolean endMD5 = false; String md5Msg = null; String md5Txt = null; ARUtilsMD5 md5 = new ARUtilsMD5(); ARUtilsMD5 md5End = new ARUtilsMD5(); while ((ret == true) && (endMD5 == false)) { boolean blockMD5 = false; md5.initialize(); do { ret = readBufferBlocks(notificationArray); if (ret == false) { ret = bleManager.isDeviceConnected(); } else { //for (int i=0; (i < receivedNotifications.size()) && (ret == true) && (blockMD5 == false) && (endMD5 == false); i++) if ((ret == true) && (notificationArray[0] != null) && (blockMD5 == false) && (endMD5 == false)) { int packetLen = notificationArray[0].length; byte[] packet = notificationArray[0]; packetCount++; totalPacket++; ARSALPrint.d("DBG", APP_TAG + "== packet " + packetLen +", "+ packetCount + ", " + totalPacket + ", " + totalSize); //String s = new String(packet); //ARSALPrint.d("DBG", APP_TAG + "packet " + s); if (packetLen > 0) { if (endFile == true) { endMD5 = true; if (packetLen == (ARUtilsMD5.MD5_LENGTH * 2)) { md5Msg = new String(packet, 0, packetLen); ARSALPrint.d("DBG", APP_TAG + "md5 end received " + md5Msg); } else { ret = false; ARSALPrint.d("DBG", APP_TAG + "md5 end failed size " + packetLen); } } else if (compareToString(packet, packetLen, BLE_PACKET_EOF)) { endFile = true; if (packetLen == (BLE_PACKET_EOF.length() + 1)) { ARSALPrint.d("DBG", APP_TAG + "End of file received "); } else { ARSALPrint.d("DBG", APP_TAG + "End of file failed size " + packetLen); ret = false; } } else if (compareToString(packet, packetLen, "MD5")) { if (packetCount > (BLE_PACKET_BLOCK_GETTING_COUNT + 1)) { ARSALPrint.d("DBG", APP_TAG + "md5 failed packet count " + packetCount); } if (packetLen == ((ARUtilsMD5.MD5_LENGTH * 2) + 3)) { blockMD5 = true; md5Msg = new String(packet, 3, packetLen - 3); ARSALPrint.d("DBG", APP_TAG + "md5 received " + md5Msg); } else { ret = false; ARSALPrint.d("DBG", APP_TAG + "md5 failed size " + packetLen); } } else { totalSize += packetLen; md5.update(packet, 0, packetLen); md5End.update(packet, 0, packetLen); if (dst != null) { try { dst.write(packet, 0, packetLen); } catch (IOException e) { ARSALPrint.e("DBG", APP_TAG + "failed writting file " + e.toString()); ret = false; } } else { byte[] newData = new byte[totalSize]; if (data[0] != null) { System.arraycopy(data[0], 0, newData, 0, totalSize - packetLen); } System.arraycopy(packet, 0, newData, totalSize - packetLen, packetLen); data[0] = newData; } if (nativeCallbackObject != 0) { nativeProgressCallback(nativeCallbackObject, ((float)totalSize / (float)fileSize) * 100.f); } } } else { //empty packet authorized } } } //receivedNotifications.clear(); notificationArray[0] = null; } while ((ret == true) && (blockMD5 == false) && (endMD5 == false)); if ((ret == true) && (blockMD5 == true)) { blockMD5 = false; packetCount = 0; md5Txt = md5.digest(); if (md5Msg.contentEquals(md5Txt) == false) { ARSALPrint.d("DBG", APP_TAG + "md5 block failed"); //TOFIX some 1st md5 packet failed !!!! //ret = false; } else { ARSALPrint.d("DBG", APP_TAG + "md5 block ok"); } //firmware 1.0.45 protocol dosen't implement cancel today at the and of 100 packets download if (isConnectionCanceled(cancelSem)) { ARSALPrint.e("DBG", APP_TAG + "Canceled received"); ret = false; } if (ret == false) { ret = sendResponse("CANCEL", getting); } else { ret = sendResponse("MD5 OK", getting); } } } if (endMD5 == true) { md5Txt = md5End.digest(); ARSALPrint.d("DBG", APP_TAG + "md5 end computed " + md5Txt); if (md5Msg.contentEquals(md5Txt) == false) { ARSALPrint.d("DBG", APP_TAG + "md5 end Failed"); ret = false; } else { ARSALPrint.d("DBG", APP_TAG + "md5 end OK"); } } else { ret = false; } if (isConnectionCanceled(cancelSem)) { ARSALPrint.e("DBG", APP_TAG + "Canceled received"); ret = false; } return ret; } private boolean readPudDataWritten() { byte[][] notificationArray = new byte[1][]; boolean ret = false; ret = readBufferBlocks(notificationArray); if (ret = true) { if (notificationArray[0] != null) { int packetLen = notificationArray[0].length; byte[] packet = notificationArray[0]; if (packetLen > 0) { //String packetTxt = new String(packet, 0, packetLen, "UTF8"); if (compareToString(packet, packetLen, BLE_PACKET_WRITTEN)) { ARSALPrint.d("DBG", APP_TAG + "Written OK"); ret = true; } else if (compareToString(packet, packetLen, BLE_PACKET_NOT_WRITTEN)) { ARSALPrint.e("DBG", APP_TAG + "NOT Written"); ret = false; } else { ARSALPrint.e("DBG", APP_TAG + "UNKNOWN Written"); ret = false; } } } else { ARSALPrint.e("DBG", APP_TAG + "UNKNOWN Written"); ret = false; } } return ret; } private boolean readPutMd5(String[] md5Txt) { byte[][] notificationArray = new byte[1][]; boolean ret = false; md5Txt[0] = ""; try { ret = readBufferBlocks(notificationArray); if (ret == true) { if (notificationArray[0] != null) { int packetLen = notificationArray[0].length; byte[] packet = notificationArray[0]; if (packetLen > 0) { if (packetLen == 32) { String packetTxt = new String(packet, 0, packetLen, "UTF8"); md5Txt[0] = packetTxt; ARSALPrint.d("DBG", APP_TAG + "md5 end received " + md5Txt[0]); } else { ARSALPrint.e("DBG", APP_TAG + "md5 size failed"); ret = false; } } else { ARSALPrint.e("DBG", APP_TAG + "md5 end failed"); ret = false; } } else { ARSALPrint.e("DBG", APP_TAG + "md5 end size failed"); ret = false; } } } catch (UnsupportedEncodingException e) { ARSALPrint.e("DBG", APP_TAG + e.toString()); ret = false; } return ret; } private boolean readRenameData() { byte[][] notificationArray = new byte[1][]; boolean ret = false; ret = readBufferBlocks(notificationArray); if (ret == true) { if (notificationArray[0] != null) { int packetLen = notificationArray[0].length; byte[] packet = notificationArray[0]; if (packetLen > 0) { //String packetString = new String(packet); if (compareToString(packet, packetLen, BLE_PACKET_RENAME_SUCCESS)) { ARSALPrint.d("DBG", APP_TAG + "Rename Success"); ret = true; } else { ARSALPrint.e("DBG", APP_TAG + "Rename Failed"); ret = false; } } else { ARSALPrint.e("DBG", APP_TAG + "Rename Failed"); ret = false; } } else { ARSALPrint.e("DBG", APP_TAG + "Rename Failed"); ret = false; } } return ret; } private boolean readDeleteData() { byte[][] notificationArray = new byte[1][]; boolean ret = false; ret = readBufferBlocks(notificationArray); if (ret == true) { if (notificationArray[0] != null) { int packetLen = notificationArray[0].length; byte[] packet = notificationArray[0]; if (packetLen > 0) { //String packetString = new String(packet); if (compareToString(packet, packetLen, BLE_PACKET_DELETE_SUCCESS)) { ARSALPrint.d("DBG", APP_TAG + "Delete Success"); ret = true; } else { ARSALPrint.e("DBG", APP_TAG + "Delete Failed"); ret = false; } } else { ARSALPrint.e("DBG", APP_TAG + "Delete Failed"); ret = false; } } else { ARSALPrint.e("DBG", APP_TAG + "Delete Failed"); ret = false; } } return ret; } public static String getListNextItem(String list, String[] nextItem, String prefix, boolean isDirectory, int[] indexItem, int[] itemLen) { String lineData = null; String item = null; String line = null; int fileIdx = 0; int endLine = 0; int ptr; if ((list != null) && (nextItem != null)) { if (nextItem[0] == null) { nextItem[0] = list; if (indexItem != null) { indexItem[0] = 0; } } else { if (indexItem != null) { indexItem[0] += itemLen[0]; } } ptr = 0; while ((item == null) && (ptr != -1)) { line = nextItem[0]; endLine = line.length(); ptr = line.indexOf('\n'); if (ptr == -1) { ptr = line.indexOf('\r'); } if (ptr != -1) { endLine = ptr; if (line.charAt(endLine - 1) == '\r') { endLine } ptr++; nextItem[0] = line.substring(ptr); fileIdx = 0; if (line.charAt(0) == ((isDirectory == true) ? 'd' : '-')) { int varSpace = 0; while (((ptr = line.indexOf('\u0020', fileIdx)) != -1) && (ptr < endLine) && (varSpace < 8)) { if (line.charAt(ptr + 1) != '\u0020') { varSpace++; } fileIdx = ++ptr; } if ((prefix != null) && (prefix.length() != 0)) { if (line.indexOf(prefix, fileIdx) != -1) { fileIdx = -1; } } if (fileIdx != -1) { int len = endLine - fileIdx; lineData = line.substring(fileIdx, fileIdx + len); item = lineData; } } } } if (itemLen != null) { itemLen[0] = endLine; //ARSALPrint.d("DBG", APP_TAG + "LINE " + list.substring(indexItem[0], indexItem[0] + itemLen[0])); } } return item; } //-rw-r--r-- 1 root root 1210512 Jan 1 02:46 ckcm.bin public static String getListItemSize(String list, int lineIndex, int lineSize, double[] size) { int fileIdx; int sizeIdx; int endLine; int ptr; String item = null; int varSpace = 0; if ((list != null) && (size != null)) { size[0] = 0.f; endLine = lineIndex + lineSize; sizeIdx = -1; fileIdx = lineIndex; while ((ptr = list.indexOf('\u0020', fileIdx)) != -1 && (ptr < endLine) && (varSpace < 3)) { if ((list.charAt(ptr - 1) == '\u0020') && (list.charAt(ptr + 1) != '\u0020')) { varSpace++; if ((list.charAt(0) == '-')) { if ((varSpace == 3) && (sizeIdx == -1)) { sizeIdx = ptr + 1; String subLine = list.substring(sizeIdx); Scanner scanner = new Scanner(subLine); try { size[0] = scanner.nextDouble(); } catch (InputMismatchException e) { size[0] = 0.f; } catch (IllegalStateException e) { size[0] = 0.f; } catch (NoSuchElementException e) { size[0] = 0.f; } scanner.close(); item = subLine; } } } fileIdx = ++ptr; } } return item; } private boolean compareToString(byte[] buffer, int len, String str) { boolean ret = false; byte[] strBytes = null; try { strBytes = str.getBytes("UTF8"); if (len >= strBytes.length) { ret = true; for (int i=0; i<strBytes.length; i++) { if (buffer[i] != strBytes[i]) { ret = false; break; } } } else { ret = false; } } catch (UnsupportedEncodingException e) { ARSALPrint.e("DBG", APP_TAG + e.toString()); ret = false; } return ret; } private String normalizePathName(String name) { String newName = name; if (name.charAt(0) != '/') { newName = "/" + name; } return newName; } }
package com.fsck.k9.helper; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Locale; import android.util.Log; import com.fsck.k9.K9; import org.apache.commons.io.IOUtils; public class FileHelper { /** * Regular expression that represents characters we won't allow in file names. * * <p> * Allowed are: * <ul> * <li>word characters (letters, digits, and underscores): {@code \w}</li> * <li>spaces: {@code " "}</li> * <li>special characters: {@code !}, {@code #}, {@code $}, {@code %}, {@code &}, {@code '}, * {@code (}, {@code )}, {@code -}, {@code @}, {@code ^}, {@code `}, <code>&#123;</code>, * <code>&#125;</code>, {@code ~}, {@code .}, {@code ,}</li> * </ul></p> * * @see #sanitizeFilename(String) */ private static final String INVALID_CHARACTERS = "[^\\w ! /** * Invalid characters in a file name are replaced by this character. * * @see #sanitizeFilename(String) */ private static final String REPLACEMENT_CHARACTER = "_"; /** * Creates a unique file in the given directory by appending a hyphen * and a number to the given filename. */ public static File createUniqueFile(File directory, String filename) { File file = new File(directory, filename); if (!file.exists()) { return file; } // Get the extension of the file, if any. int index = filename.lastIndexOf('.'); String name; String extension; if (index != -1) { name = filename.substring(0, index); extension = filename.substring(index); } else { name = filename; extension = ""; } for (int i = 2; i < Integer.MAX_VALUE; i++) { file = new File(directory, String.format(Locale.US, "%s-%d%s", name, i, extension)); if (!file.exists()) { return file; } } return null; } public static void touchFile(final File parentDir, final String name) { final File file = new File(parentDir, name); try { if (!file.exists()) { if (!file.createNewFile()) { Log.d(K9.LOG_TAG, "Unable to create file: " + file.getAbsolutePath()); } } else { if (!file.setLastModified(System.currentTimeMillis())) { Log.d(K9.LOG_TAG, "Unable to change last modification date: " + file.getAbsolutePath()); } } } catch (Exception e) { Log.d(K9.LOG_TAG, "Unable to touch file: " + file.getAbsolutePath(), e); } } private static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); try { byte[] buffer = new byte[1024]; int count; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } public static void renameOrMoveByCopying(File from, File to) throws IOException { deleteFileIfExists(to); boolean renameFailed = !from.renameTo(to); if (renameFailed) { copyFile(from, to); boolean deleteFromFailed = !from.delete(); if (deleteFromFailed) { Log.e(K9.LOG_TAG, "Unable to delete source file after copying to destination!"); } } } private static void deleteFileIfExists(File to) throws IOException { boolean fileDoesNotExist = !to.exists(); if (fileDoesNotExist) { return; } boolean deleteOk = to.delete(); if (deleteOk) { return; } throw new IOException("Unable to delete file: " + to.getAbsolutePath()); } public static boolean move(final File from, final File to) { if (to.exists()) { if (!to.delete()) { Log.d(K9.LOG_TAG, "Unable to delete file: " + to.getAbsolutePath()); } } if (!to.getParentFile().mkdirs()) { Log.d(K9.LOG_TAG, "Unable to make directories: " + to.getParentFile().getAbsolutePath()); } try { copyFile(from, to); boolean deleteFromFailed = !from.delete(); if (deleteFromFailed) { Log.e(K9.LOG_TAG, "Unable to delete source file after copying to destination!"); } return true; } catch (Exception e) { Log.w(K9.LOG_TAG, "cannot move " + from.getAbsolutePath() + " to " + to.getAbsolutePath(), e); return false; } } public static void moveRecursive(final File fromDir, final File toDir) { if (!fromDir.exists()) { return; } if (!fromDir.isDirectory()) { if (toDir.exists()) { if (!toDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete already existing file/directory " + toDir.getAbsolutePath()); } } if (!fromDir.renameTo(toDir)) { Log.w(K9.LOG_TAG, "cannot rename " + fromDir.getAbsolutePath() + " to " + toDir.getAbsolutePath() + " - moving instead"); move(fromDir, toDir); } return; } if (!toDir.exists() || !toDir.isDirectory()) { if (toDir.exists()) { if (!toDir.delete()) { Log.d(K9.LOG_TAG, "Unable to delete file: " + toDir.getAbsolutePath()); } } if (!toDir.mkdirs()) { Log.w(K9.LOG_TAG, "cannot create directory " + toDir.getAbsolutePath()); } } File[] files = fromDir.listFiles(); for (File file : files) { if (file.isDirectory()) { moveRecursive(file, new File(toDir, file.getName())); if (!file.delete()) { Log.d(K9.LOG_TAG, "Unable to delete file: " + toDir.getAbsolutePath()); } } else { File target = new File(toDir, file.getName()); if (!file.renameTo(target)) { Log.w(K9.LOG_TAG, "cannot rename " + file.getAbsolutePath() + " to " + target.getAbsolutePath() + " - moving instead"); move(file, target); } } } if (!fromDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete " + fromDir.getAbsolutePath()); } } /** * Replace characters we don't allow in file names with a replacement character. * * @param filename * The original file name. * * @return The sanitized file name containing only allowed characters. */ public static String sanitizeFilename(String filename) { return filename.replaceAll(INVALID_CHARACTERS, REPLACEMENT_CHARACTER); } }
package com.tlongdev.bktf.activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.tlongdev.bktf.BptfApplication; import com.tlongdev.bktf.R; import com.tlongdev.bktf.fragment.CalculatorFragment; import com.tlongdev.bktf.fragment.ConverterFragment; import com.tlongdev.bktf.fragment.FavoritesFragment; import com.tlongdev.bktf.fragment.RecentsFragment; import com.tlongdev.bktf.fragment.UnusualFragment; import com.tlongdev.bktf.fragment.UserFragment; import com.tlongdev.bktf.gcm.GcmRegisterPriceUpdatesService; import com.tlongdev.bktf.util.CircleTransform; import com.tlongdev.bktf.util.Profile; import com.tlongdev.bktf.util.Utility; import butterknife.Bind; import butterknife.ButterKnife; /** * Tha main activity if the application. Navigation drawer is used. This is where most of the * fragments are shown. */ public class MainActivity extends AppCompatActivity { /** * Log tag for logging. */ @SuppressWarnings("unused") private static final String LOG_TAG = MainActivity.class.getSimpleName(); /** * Request codes for onActivityResult */ public static final int REQUEST_SETTINGS = 100; public static final int REQUEST_NEW_ITEM = 101; /** * Remember the position of the selected item. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * The {@link Tracker} used to record screen views. */ private Tracker mTracker; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; /** * The drawer layout and the navigation drawer */ @Bind(R.id.drawer_layout) DrawerLayout mDrawerLayout; @Bind(R.id.navigation_view) NavigationView mNavigationView; /** * The index of the current fragment. */ private int mCurrentSelectedPosition = -1; /** * Variables used for managing fragments. */ private boolean userStateChanged = false; /** * Listener to be notified when the drawer opens. Mainly for fragments with toolbars so we can * exapnd the fragment's toolbar when the drawer opens. */ private OnDrawerOpenedListener drawerListener; /** * Views of the navigation header view. */ private TextView name; private TextView backpack; private ImageView avatar; private MenuItem userMenuItem; /** * Listener for the navigation drawer. */ NavigationView.OnNavigationItemSelectedListener navigationListener = new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Close the drawers and handle item clicks mDrawerLayout.closeDrawers(); switch (menuItem.getItemId()) { // TODO: 2015. 10. 25. fragment selections in the navigation view is incorrect when selecting the user fragment case R.id.nav_recents: switchFragment(0); break; case R.id.nav_unusuals: switchFragment(1); break; case R.id.nav_user: switchFragment(2); break; case R.id.nav_favorites: switchFragment(3); break; case R.id.nav_converter: switchFragment(4); break; case R.id.nav_calculator: switchFragment(5); break; case R.id.nav_settings: Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); startActivityForResult(settingsIntent, REQUEST_SETTINGS); break; case R.id.nav_steam: Uri webPage = Uri.parse("http://steamcommunity.com/groups/bptfandroid"); //Open link in the device default web browser Intent intent = new Intent(Intent.ACTION_VIEW, webPage); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } break; } return true; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); // Obtain the shared Tracker instance. BptfApplication application = (BptfApplication) getApplication(); mTracker = application.getDefaultTracker(); //Set the default values for all preferences when the app is first loaded PreferenceManager.setDefaultValues(this, R.xml.pref_general, false); //Setup the drawer mDrawerLayout.setStatusBarBackgroundColor(Utility.getColor(this, R.color.primary_dark)); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); //The navigation view mNavigationView.setNavigationItemSelectedListener(navigationListener); //User clicked on the header View navigationHeader = mNavigationView.getHeaderView(0); //Find the views of the navigation drawer header name = (TextView) navigationHeader.findViewById(R.id.user_name); backpack = (TextView) navigationHeader.findViewById(R.id.backpack_value); avatar = (ImageView) navigationHeader.findViewById(R.id.avatar); //Check if there is a fragment to be restored if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mNavigationView.getMenu().getItem(mCurrentSelectedPosition).setChecked(true); } else { mNavigationView.getMenu().getItem(0).setChecked(true); } userMenuItem = mNavigationView.getMenu().getItem(2); // Select either the default item (0) or the last selected item. switchFragment(0); } @Override protected void onResume() { mTracker.setScreenName(String.valueOf(getTitle())); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); //If needed (mostly when the steamId was changed) reload a new instance of the UserFragment if (userStateChanged) { FragmentManager fragmentManager = getSupportFragmentManager(); if (Profile.isSignedIn(this)) { fragmentManager.beginTransaction() .replace(R.id.container, new UserFragment()) .commit(); } else { mNavigationView.getMenu().getItem(0).setChecked(true); mCurrentSelectedPosition = 0; fragmentManager.beginTransaction() .replace(R.id.container, new RecentsFragment()) .commit(); } userStateChanged = false; } updateDrawer(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean autoSync = !prefs.getString(getString(R.string.pref_auto_sync), "1").equals("0"); if (prefs.getBoolean(getString(R.string.pref_registered_topic_price_updates), false) != autoSync) { Intent intent = new Intent(this, GcmRegisterPriceUpdatesService.class); intent.putExtra(GcmRegisterPriceUpdatesService.EXTRA_SUBSCRIBE, autoSync); startService(intent); } super.onResume(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //Save the current fragment to be restored. outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_SETTINGS) { //User returned from the settings activity if (resultCode == RESULT_OK) { if (mCurrentSelectedPosition == 2) { if (data != null && data.getBooleanExtra("login_changed", false)) { //User fragment needs to be reloaded if the steamId was changed userStateChanged = true; } } } return; } //super call is needed to pass the result to the fragments super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onOptionsItemSelected(MenuItem item) { //Handler the drawer toggle press return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void setSupportActionBar(Toolbar toolbar) { super.setSupportActionBar(toolbar); //Since each fragment has it's own toolbar we need to re add the drawer toggle everytime we //switch fragments restoreNavigationIcon(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } /** * Switches to another fragment. * * @param position the position of the clicked item in the navigation view */ public void switchFragment(int position) { if (mCurrentSelectedPosition == position) { return; } mCurrentSelectedPosition = position; if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mNavigationView); } //Start handling fragment transactions FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.setCustomAnimations(R.anim.simple_fade_in, R.anim.simple_fade_out); Fragment newFragment; //Initialize fragments and add them is the drawer listener switch (position) { case 0: newFragment = new RecentsFragment(); drawerListener = (RecentsFragment) newFragment; break; case 1: newFragment = new UnusualFragment(); drawerListener = (UnusualFragment) newFragment; break; case 2: newFragment = new UserFragment(); drawerListener = (UserFragment) newFragment; break; case 3: newFragment = new FavoritesFragment(); drawerListener = (FavoritesFragment) newFragment; break; case 4: newFragment = new ConverterFragment(); drawerListener = null; break; case 5: newFragment = new CalculatorFragment(); drawerListener = (CalculatorFragment) newFragment; break; default: throw new IllegalArgumentException("unknown fragment to switch to: " + position); } //Commit the transaction transaction.replace(R.id.container, newFragment); transaction.commit(); } /** * Updates the information in the navigation drawer header. */ public void updateDrawer() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (Profile.isSignedIn(this)) { //Set the name name.setText(prefs.getString(getString(R.string.pref_player_name), null)); //Set the backpack value double bpValue = Utility.getDouble(prefs, getString(R.string.pref_player_backpack_value_tf2), -1); if (bpValue >= 0) { backpack.setText(String.format("Backpack: %s", getString(R.string.currency_metal, String.valueOf(Math.round(bpValue))))); } else { backpack.setText("Private backpack"); } //Download the avatar (if needed) and set it if (prefs.contains(getString(R.string.pref_new_avatar)) && Utility.isNetworkAvailable(this)) { Glide.with(this) .load(PreferenceManager.getDefaultSharedPreferences(this). getString(getString(R.string.pref_player_avatar_url), "")) .diskCacheStrategy(DiskCacheStrategy.ALL) .transform(new CircleTransform(this)) .into(avatar); } userMenuItem.setEnabled(true); } else { name.setText(null); backpack.setText(null); userMenuItem.setEnabled(false); } } /** * Restores the navigation icon of the toolbar. */ private void restoreNavigationIcon() { // set up the drawer's list view with items and click listener ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); //Notify the listeners if (drawerListener != null) { drawerListener.onDrawerOpened(); } } }; // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } /** * Interface for listening drawer open events. */ public interface OnDrawerOpenedListener { /** * Called when the navigation drawer is opened. */ void onDrawerOpened(); } }
package de.stefanhoth.android.got2048.logic; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.deploygate.sdk.DeployGate; import de.stefanhoth.android.got2048.logic.model.Cell; import de.stefanhoth.android.got2048.logic.model.Grid; import de.stefanhoth.android.got2048.logic.model.MOVE_DIRECTION; import de.stefanhoth.android.got2048.logic.model.MovementChanges; public class MCP { private static final String TAG = MCP.class.getName(); protected static final int DEFAULT_START_FIELDS = 2; protected static final int DEFAULT_START_VALUE = 2; protected static final int DEFAULT_WON_VALUE = 2048; public static final String BROADCAST_MCP = MCP.class.getPackage() + ".BROADCAST_MCP"; public static final String BROADCAST_ACTION_MOVE_START = MCP.class.getPackage() + ".action.MOVE_START"; public static final String BROADCAST_ACTION_MOVE_DONE = MCP.class.getPackage() + ".action.MOVE_DONE"; public static final String BROADCAST_ACTION_GAME_WON = MCP.class.getPackage() + ".action.GAME_WON"; public static final String BROADCAST_ACTION_GAME_OVER = MCP.class.getPackage() + ".action.GAME_OVER"; public static final String KEY_DIRECTION = MCP.class.getPackage() + ".key.DIRECTION"; public static final String KEY_MOVEMENT_CHANGES = MCP.class.getPackage() + ".key.MOVEMENTS"; private final Context mContext; private Grid playlingField; private boolean mGameStopped; private boolean mCurrentlyMoving; public MCP(Context context, int gridSize) { mContext = context; playlingField = new Grid(gridSize); mGameStopped = false; mCurrentlyMoving = false; } protected Grid getPlaylingField() { return playlingField; } public void addStartCells() { Cell cell = playlingField.getRandomCell(); playlingField.setCellValue(cell.getRow(), cell.getColumn(), DEFAULT_START_VALUE); Cell nextCell = playlingField.getRandomCell(); for (int count = playlingField.getActiveCells(); count < DEFAULT_START_FIELDS; count++) { while (cell.equals(nextCell)) { nextCell = playlingField.getRandomCell(); } playlingField.setCellValue(nextCell.getRow(), nextCell.getColumn(), DEFAULT_START_VALUE); cell = nextCell; } updateMoveDoneListeners(new MovementChanges(getPlaylingField().getGridStatus())); } public void addNewCell() { if (playlingField.getActiveCells() == (playlingField.getGridSize() * playlingField.getGridSize())) { Log.i(TAG, "addNewCell: Field is full. Can't add new cell."); return; } Cell cell; do { cell = playlingField.getRandomCell(); } while (playlingField.cellHasValue(cell.getRow(), cell.getColumn())); playlingField.setCellValue(cell.getRow(), cell.getColumn(), DEFAULT_START_VALUE); } public void move(MOVE_DIRECTION direction) { move(direction, true); } protected void move(MOVE_DIRECTION direction, boolean spawnNewCell) { if (mGameStopped) { Log.w(TAG, "move: Game is stopped. Not accepting any movement at this time."); return; } else if (mCurrentlyMoving) { Log.d(TAG, "move: Currently working on a move, not accepting further input until done"); return; } mCurrentlyMoving = true; if (playlingField.wouldMoveCells(direction)) { updateMoveStartListeners(direction); Log.v(TAG, "move: Executing move to " + direction + "."); MovementChanges changes = playlingField.moveCells(direction); if (spawnNewCell) { addNewCell(); changes.gridStatus = playlingField.getGridStatus(); } updateMoveDoneListeners(changes); } else { Log.d(TAG, "move: Move to " + direction + " wouldn't move any cells, so nothing is happening."); } if (playlingField.isGameOver()) { mGameStopped = true; updateGameOverListeners(); } else if (playlingField.isGameWon(DEFAULT_WON_VALUE)) { mGameStopped = true; updateGameWonListeners(); } mCurrentlyMoving = false; } private void updateMoveStartListeners(MOVE_DIRECTION direction) { Bundle extras = new Bundle(); extras.putSerializable(KEY_DIRECTION, direction.ordinal()); sendLocalBroadcast(BROADCAST_ACTION_MOVE_START, extras); } private void updateMoveDoneListeners(MovementChanges changes) { Bundle extras = new Bundle(); extras.putParcelable(KEY_MOVEMENT_CHANGES, changes); sendLocalBroadcast(BROADCAST_ACTION_MOVE_DONE, extras); } private void updateGameOverListeners() { sendLocalBroadcast(BROADCAST_ACTION_GAME_OVER, null); String username = DeployGate.getLoginUsername(); String message = String.format("%s just LOST a game.", (username == null) ? "UNKNOWN" : username); DeployGate.logInfo(message); } private void updateGameWonListeners() { sendLocalBroadcast(BROADCAST_ACTION_GAME_WON, null); String username = DeployGate.getLoginUsername(); String message = String.format("%s just WON a game.", (username == null) ? "UNKNOWN" : username); DeployGate.logInfo(message); } private void sendLocalBroadcast(String action, Bundle extras) { if (mContext == null) { Log.e(TAG, "sendLocalBroadcast: Context=null, can't broadcast action=" + action); return; } Intent localIntent = new Intent(BROADCAST_MCP) .setAction(action); if (extras != null && !extras.isEmpty()) { localIntent.putExtras(extras); } LocalBroadcastManager.getInstance(mContext).sendBroadcast(localIntent); } }
package org.jasig.portal; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.Element; import org.apache.xerces.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.*; import java.sql.*; import java.util.*; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.jasig.portal.utils.DTDResolver; import org.jasig.portal.services.LogService; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.jasig.portal.security.IRole; import org.jasig.portal.utils.DocumentFactory; /** * SQL implementation for the 2.x relational database model * @author George Lindholm * @version $Revision$ */ public class RDBMUserLayoutStore implements IUserLayoutStore { //This class is instantiated ONCE so NO class variables can be used to keep state between calls static int DEBUG = 0; protected RdbmServices rdbmService = null; protected static final String channelPrefix = "n"; protected static final String folderPrefix = "s"; /** * put your documentation comment here */ public void RDBMUserLayoutStore () { rdbmService = new RdbmServices(); } /** * put your documentation comment here * @param node * @param indent */ public static final void dumpDoc (Node node, String indent) { if (node == null) { return; } if (node instanceof Element) { System.err.print(indent + "element: tag=" + ((Element)node).getTagName() + " "); } else if (node instanceof Document) { System.err.print("document:"); } else { System.err.print(indent + "node:"); } System.err.println("name=" + node.getNodeName() + " value=" + node.getNodeValue()); NamedNodeMap nm = node.getAttributes(); if (nm != null) { for (int i = 0; i < nm.getLength(); i++) { System.err.println(indent + " " + nm.item(i).getNodeName() + ": '" + nm.item(i).getNodeValue() + "'"); } System.err.println(indent + " } if (node.hasChildNodes()) { dumpDoc(node.getFirstChild(), indent + " "); } dumpDoc(node.getNextSibling(), indent); } /** * put your documentation comment here * @param name * @param value * @param channel */ protected static final void addChannelHeaderAttribute (String name, int value, Element channel) { addChannelHeaderAttribute(name, value + "", channel); } /** * put your documentation comment here * @param name * @param value * @param channel */ protected static final void addChannelHeaderAttribute (String name, String value, Element channel) { channel.setAttribute(name, value); } /** * put your documentation comment here * @param name * @param value * @param channel */ protected static final void addChannelHeaderAttributeFlag (String name, String value, Element channel) { addChannelHeaderAttribute(name, (value != null && value.equals("Y") ? "true" : "false"), channel); } /** * put your documentation comment here * @param doc * @param chanId * @param idTag * @param rs * @param channel * @exception java.sql.SQLException */ protected static final void createChannelNodeHeaders (DocumentImpl doc, int chanId, String idTag, ResultSet rs, Element channel) throws java.sql.SQLException { String chanTitle = rs.getString("CHAN_TITLE"); String chanDesc = rs.getString("CHAN_DESC"); String chanClass = rs.getString("CHAN_CLASS"); int chanTypeId = rs.getInt("CHAN_TYPE_ID"); int chanPupblUsrId = rs.getInt("CHAN_PUBL_ID"); int chanApvlId = rs.getInt("CHAN_APVL_ID"); java.sql.Timestamp chanPublDt = rs.getTimestamp("CHAN_PUBL_DT"); java.sql.Timestamp chanApvlDt = rs.getTimestamp("CHAN_APVL_DT"); int chanTimeout = rs.getInt("CHAN_TIMEOUT"); String chanMinimizable = rs.getString("CHAN_MINIMIZABLE"); String chanEditable = rs.getString("CHAN_EDITABLE"); String chanHasHelp = rs.getString("CHAN_HAS_HELP"); String chanHasAbout = rs.getString("CHAN_HAS_ABOUT"); // String chanUnremovable = rs.getString("CHAN_UNREMOVABLE"); String chanDetachable = rs.getString("CHAN_DETACHABLE"); String chanName = rs.getString("CHAN_NAME"); String chanFName = rs.getString("CHAN_FNAME"); doc.putIdentifier(idTag, channel); addChannelHeaderAttribute("ID", idTag, channel); channel.setAttribute("chanID", chanId + ""); if (DEBUG > 1) { System.err.println("channel " + chanName + "@" + chanId + " has tag " + chanId); } addChannelHeaderAttribute("name", chanName, channel); addChannelHeaderAttribute("description", chanDesc, channel); addChannelHeaderAttribute("fname", chanFName, channel); addChannelHeaderAttribute("class", chanClass, channel); addChannelHeaderAttribute("typeID", chanTypeId, channel); addChannelHeaderAttribute("timeout", chanTimeout, channel); addChannelHeaderAttributeFlag("minimizable", chanMinimizable, channel); addChannelHeaderAttributeFlag("editable", chanEditable, channel); addChannelHeaderAttributeFlag("hasHelp", chanHasHelp, channel); addChannelHeaderAttributeFlag("hasAbout", chanHasAbout, channel); // addChannelHeaderAttributeFlag("unremovable", chanUnremovable, channel); addChannelHeaderAttributeFlag("detachable", chanDetachable, channel); } /** * put your documentation comment here * @param doc * @param rs * @param channel * @exception java.sql.SQLException */ protected static final void createChannelNodeParameters (DocumentImpl doc, ResultSet rs, Element channel) throws java.sql.SQLException { String chanParmNM = rs.getString("CHAN_PARM_NM"); if (rs.wasNull()) { return; } String chanParmVal = rs.getString("CHAN_PARM_VAL"); Element parameter = doc.createElement("parameter"); parameter.setAttribute("name", chanParmNM); parameter.setAttribute("value", chanParmVal); String override = rs.getString("CHAN_PARM_OVRD"); if (override != null && override.equals("Y")) { parameter.setAttribute("override", "yes"); } channel.appendChild(parameter); } /** * put your documentation comment here * @param con * @param doc * @param chanId * @param idTag * @return * @exception java.sql.SQLException */ protected Element createChannelNode (Connection con, DocumentImpl doc, int chanId, String idTag) throws java.sql.SQLException { Element channel = null; Statement stmt = con.createStatement(); try { String sQuery = "SELECT * FROM UP_CHANNEL WHERE CHAN_ID=" + chanId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::createChannelNode(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { if (!channelApproved(rs.getTimestamp("CHAN_APVL_DT"))) { /* Channel hasn't been approved yet. Replace it with the error channel and a suitable message */ /* !!!!!!! Add code here someday !!!!!!!!!!!*/ LogService.instance().log(LogService.INFO, "RDBMUserLayoutStore::createLayoutStructure(): Channel hasn't been approved for publishing yet (ignored at the moment) for channel " + chanId); // return new ErrorChannel() } channel = doc.createElement("channel"); createChannelNodeHeaders(doc, chanId, idTag, rs, channel); rs.close(); sQuery = "SELECT * FROM UP_CHAN_PARAM WHERE CHAN_ID=" + chanId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::createChannelNode(): " + sQuery); rs = stmt.executeQuery(sQuery); while (rs.next()) { createChannelNodeParameters(doc, rs, channel); } } } finally { rs.close(); } } finally { stmt.close(); } return channel; } /** * put your documentation comment here * @param node * @param tag * @return */ protected static final NamedNodeMap findSystemNamedNodeMap (Element node, String tag) { NodeList nl = node.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equals(tag)) { return nl.item(i).getAttributes(); } } return null; } /** * put your documentation comment here * @param con * @param doc * @param stmt * @param root * @param userId * @param profileId * @param layoutId * @param structId * @exception java.sql.SQLException */ protected void createLayout (Connection con, DocumentImpl doc, Statement stmt, Element root, int userId, int profileId, int layoutId, int structId) throws java.sql.SQLException { if (structId == 0) { // End of line return; } int nextStructId; int chldStructId; int chanId; Element parameter = null; Element structure; String sQuery = "SELECT * FROM UP_LAYOUT_STRUCT WHERE USER_ID=" + userId + " AND LAYOUT_ID = " + layoutId + " AND STRUCT_ID=" + structId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::createLayout(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { rs.next(); nextStructId = rs.getInt("NEXT_STRUCT_ID"); chldStructId = rs.getInt("CHLD_STRUCT_ID"); chanId = rs.getInt("CHAN_ID"); structure = createLayoutStructure(rs, chanId, userId, con, doc); } finally { rs.close(); } if (chanId != 0) { // Channel parameter = (Element)structure.getElementsByTagName("parameter").item(0); } sQuery = "SELECT * FROM UP_STRUCT_PARAM WHERE USER_ID=" + userId + " AND LAYOUT_ID = " + layoutId + " AND STRUCT_ID=" + structId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::createLayout(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { createLayoutStructureParameter(chanId, rs, structure, parameter); } } finally { rs.close(); } root.appendChild(structure); if (chanId == 0) { // Folder createLayout(con, doc, stmt, structure, userId, profileId, layoutId, chldStructId); } createLayout(con, doc, stmt, root, userId, profileId, layoutId, nextStructId); } /** * put your documentation comment here * @param chanId * @param rs * @param structure * @param parameter * @exception java.sql.SQLException */ protected static final void createLayoutStructureParameter (int chanId, ResultSet rs, Element structure, Element parameter) throws java.sql.SQLException { String paramName = rs.getString("STRUCT_PARM_NM"); if (paramName != null) { String paramValue = rs.getString("STRUCT_PARM_VAL"); if (chanId == 0) { // Folder structure.setAttribute(paramName, paramValue); } else { // Channel NodeList parameters = structure.getElementsByTagName("parameter"); for (int i = 0; i < parameters.getLength(); i++) { Element parmElement = (Element)parameters.item(i); NamedNodeMap nm = parmElement.getAttributes(); String nodeName = nm.getNamedItem("name").getNodeValue(); if (nodeName.equals(paramName)) { Node override = nm.getNamedItem("override"); if (override != null && override.getNodeValue().equals("yes")) { Node valueNode = nm.getNamedItem("value"); valueNode.setNodeValue(paramValue); } return; } } } } } /** * put your documentation comment here * @param chanId * @param userId * @param con * @return * @exception java.sql.SQLException */ protected static boolean channelApproved(java.sql.Timestamp approvedDate) { java.sql.Timestamp rightNow = new java.sql.Timestamp(System.currentTimeMillis()); return (approvedDate != null && rightNow.after(approvedDate)); } /** * put your documentation comment here * @param chanId * @param userId * @param con * @return * @exception java.sql.SQLException */ protected static boolean channelInUserRole (int chanId, int userId, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "SELECT UC.CHAN_ID FROM UP_CHANNEL UC, UP_ROLE_CHAN URC, UP_ROLE UR, UP_USER_ROLE UUR " + "WHERE UUR.USER_ID=" + userId + " AND UC.CHAN_ID=" + chanId + " AND UUR.ROLE_ID=UR.ROLE_ID AND UR.ROLE_ID=URC.ROLE_ID AND URC.CHAN_ID=UC.CHAN_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::channelInUserRole(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (!rs.next()) { return false; } } finally { rs.close(); } } finally { stmt.close(); } return true; } /** * put your documentation comment here * @param rs * @param chanId * @param userId * @param stmt * @param doc * @return * @exception java.sql.SQLException */ protected final Element createLayoutStructure (ResultSet rs, int chanId, int userId, Connection con, DocumentImpl doc) throws java.sql.SQLException { String idTag = rs.getString("STRUCT_ID"); Element returnNode=null; if (chanId != 0) { // Channel /* See if we have access to the channel */ if (!channelInUserRole(chanId, userId, con)) { /* No access to channel. Replace it with the error channel and a suitable message */ /* !!!!!!! Add code here someday !!!!!!!!!!!*/ LogService.instance().log(LogService.INFO, "RDBMUserLayoutStore::createLayoutStructure(): No role access (ignored at the moment) for channel " + chanId + " for user " + userId); // return new ErrorChannel() } returnNode = createChannelNode(con, doc, chanId, channelPrefix + idTag); } else { // Folder String name = rs.getString("NAME"); String type = rs.getString("TYPE"); returnNode = doc.createElement("folder"); doc.putIdentifier(folderPrefix + idTag, returnNode); addChannelHeaderAttribute("ID", folderPrefix + idTag, returnNode); addChannelHeaderAttribute("name", name, returnNode); addChannelHeaderAttribute("type", (type != null ? type : "regular"), returnNode); } // set common attributes if(returnNode!=null) { String hidden = rs.getString("HIDDEN"); String unremovable = rs.getString("UNREMOVABLE"); String immutable = rs.getString("IMMUTABLE"); addChannelHeaderAttribute("hidden", (hidden != null && hidden.equals("Y") ? "true" : "false"), returnNode); addChannelHeaderAttribute("immutable", (immutable != null && immutable.equals("Y") ? "true" : "false"), returnNode); addChannelHeaderAttribute("unremovable", (unremovable != null && unremovable.equals("Y") ? "true" : "false"), returnNode); } return returnNode; } /** * UserLayout * @param userId, the user ID * @param profileId, the profile ID * @return a DOM object representing the user layout * @throws Exception */ public Document getUserLayout (int userId, int profileId) throws Exception { Connection con = rdbmService.getConnection(); String str_uLayoutXML = null; try { DocumentImpl doc = new DocumentImpl(); Element root = doc.createElement("layout"); Statement stmt = con.createStatement(); try { long startTime = System.currentTimeMillis(); String subSelectString = "SELECT LAYOUT_ID FROM UP_USER_PROFILES WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + subSelectString); int layoutId; ResultSet rs = stmt.executeQuery(subSelectString); try { rs.next(); layoutId = rs.getInt("LAYOUT_ID"); } finally { rs.close(); } String sQuery = "SELECT INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID=" + userId + " AND LAYOUT_ID = " + layoutId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery); rs = stmt.executeQuery(sQuery); try { if (rs.next()) { int structId = rs.getInt("INIT_STRUCT_ID"); if (structId == 0) { // Grab the default "Guest" layout structId = 1; // Should look this up } createLayout(con, doc, stmt, root, userId, profileId, layoutId, structId); } } finally { rs.close(); } long stopTime = System.currentTimeMillis(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): Layout document for user " + userId + " took " + (stopTime - startTime) + " milliseconds to create"); doc.appendChild(root); if (DEBUG > 1) { System.err.println("--> created document"); dumpDoc(doc, ""); System.err.println("< } } finally { stmt.close(); } return doc; } finally { rdbmService.releaseConnection(con); } } /** * Save the user layout * @param userId * @param profileId * @param layoutXML * @throws Exception */ public void setUserLayout (int userId, int profileId, Document layoutXML) throws Exception { int layoutId = 0; Connection con = rdbmService.getConnection(); try { setAutoCommit(con, false); // Need an atomic update here Statement stmt = con.createStatement(); try { String query = "SELECT LAYOUT_ID FROM UP_USER_PROFILES WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + query); ResultSet rs = stmt.executeQuery(query); try { if (rs.next()) { layoutId = rs.getInt("LAYOUT_ID"); } } finally { rs.close(); } String selectString = "USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId; String sQuery = "DELETE FROM UP_STRUCT_PARAM WHERE " + selectString; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery); stmt.executeUpdate(sQuery); sQuery = "DELETE FROM UP_LAYOUT_STRUCT WHERE " + selectString; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery); stmt.executeUpdate(sQuery); if (DEBUG > 1) { System.err.println("--> saving document"); dumpDoc(layoutXML.getFirstChild().getFirstChild(), ""); System.err.println("< } saveStructure(layoutXML.getFirstChild().getFirstChild(), stmt, userId, profileId); } finally { stmt.close(); } commit(con); } catch (Exception e) { rollback(con); throw e; } finally { rdbmService.releaseConnection(con); } } protected class StructId { public int id = 1; } /** * convert true/false int Y/N for database * @param value to check * @result Y/N */ protected static final String dbBool (String value) { if (value != null && value.equals("true")) { return "Y"; } else { return "N"; } } /** * put your documentation comment here * @param node * @param stmt * @param userId * @param layoutId * @param structId * @return * @exception java.sql.SQLException */ protected int saveStructure (Node node, Statement stmt, int userId, int layoutId) throws java.sql.SQLException { if (node == null) { return 0; } else if (node.getNodeName().equals("parameter")) { return 0; } Element structure = (Element)node; int saveStructId = Integer.parseInt(structure.getAttribute("ID").substring(1)); int nextStructId = 0; int childStructId = 0; String sQuery; if (DEBUG > 0) { LogService.instance().log(LogService.DEBUG, "-->" + node.getNodeName() + "@" + saveStructId); } if (node.hasChildNodes()) { childStructId = saveStructure(node.getFirstChild(), stmt, userId, layoutId); } nextStructId = saveStructure(node.getNextSibling(), stmt, userId, layoutId); String chanId = "NULL"; String structName = "NULL"; if (node.getNodeName().equals("channel")) { chanId = node.getAttributes().getNamedItem("chanID").getNodeValue(); } else { structName = "'" + sqlEscape(structure.getAttribute("name")) + "'"; } String externalId = structure.getAttribute("external_id"); if (externalId != null && externalId.trim().length() > 0) { externalId = "'" + externalId + "'"; } else { externalId = "NULL"; } sQuery = "INSERT INTO UP_LAYOUT_STRUCT " + "(USER_ID, LAYOUT_ID, STRUCT_ID, NEXT_STRUCT_ID, CHLD_STRUCT_ID,EXTERNAL_ID,CHAN_ID,NAME,TYPE,HIDDEN,IMMUTABLE,UNREMOVABLE) VALUES (" + userId + "," + layoutId + "," + saveStructId + "," + nextStructId + "," + childStructId + "," + externalId + "," + chanId + "," + structName + ",'" + structure.getAttribute("type") + "'," + "'" + dbBool(structure.getAttribute("hidden")) + "','" + dbBool(structure.getAttribute("immutable")) + "'," + "'" + dbBool(structure.getAttribute("unremovable")) + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + sQuery); stmt.executeUpdate(sQuery); NodeList parameters = node.getChildNodes(); if (parameters != null) { for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeName().equals("parameter")) { Element parmElement = (Element)parameters.item(i); NamedNodeMap nm = parmElement.getAttributes(); String nodeName = nm.getNamedItem("name").getNodeValue(); String nodeValue = nm.getNamedItem("value").getNodeValue(); Node override = nm.getNamedItem("override"); if (DEBUG > 0) { System.err.println(nodeName + "=" + nodeValue); } if (override == null || !override.getNodeValue().equals("yes")) { if (DEBUG > 0) System.err.println("Not saving channel defined parameter value " + nodeName); } else { sQuery = "INSERT INTO UP_STRUCT_PARAM (USER_ID, LAYOUT_ID, STRUCT_ID, STRUCT_PARM_NM, STRUCT_PARM_VAL) VALUES (" + userId + "," + layoutId + "," + saveStructId + ",'" + nodeName + "','" + nodeValue + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + sQuery); stmt.executeUpdate(sQuery); } } } } return saveStructId; } /** * * UserPreferences * */ /** * * ChannelRegistry * */ public void addChannel (int id, int publisherId, String title, Document doc, String catID[]) throws SQLException { Connection con = rdbmService.getConnection(); try { addChannel(id, publisherId, title, doc, con); // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { for (int i = 0; i < catID.length; i++) { // Take out "cat" prefix if its there String categoryID = catID[i].startsWith("cat") ? catID[i].substring(3) : catID[i]; String sInsert = "INSERT INTO UP_CAT_CHAN (CHAN_ID, CAT_ID) VALUES (" + id + "," + categoryID + ")"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addChannel(): " + sInsert); stmt.executeUpdate(sInsert); } // Commit the transaction commit(con); } catch (SQLException sqle) { // Roll back the transaction rollback(con); throw sqle; } finally { if (stmt != null) stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param id * @param title * @param doc * @exception java.sql.SQLException */ public void addChannel (int id, int publisherId, String title, Document doc) throws SQLException { //System.out.println("Enterering ChannelRegistryImpl::addChannel()"); Connection con = rdbmService.getConnection(); try { addChannel(id, publisherId, title, doc, con); } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param sql * @return */ protected static final String sqlEscape (String sql) { if (sql == null) { return ""; } else { int primePos = sql.indexOf("'"); if (primePos == -1) { return sql; } else { StringBuffer sb = new StringBuffer(sql.length() + 4); int startPos = 0; do { sb.append(sql.substring(startPos, primePos + 1)); sb.append("'"); startPos = primePos + 1; primePos = sql.indexOf("'", startPos); } while (primePos != -1); sb.append(sql.substring(startPos)); return sb.toString(); } } } /** * put your documentation comment here * @param chanId * @param approverId * @exception Exception */ public void approveChannel(int chanId, int approverId, java.sql.Timestamp approveDate) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sUpdate = "UPDATE UP_CHANNEL SET CHAN_APVL_ID = " + approverId + ", CHAN_APVL_DT = " + "{ts '" + approveDate.toString() + "'}" + " WHERE CHAN_ID = " + chanId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::approveChannel(): " + sUpdate); stmt.executeUpdate(sUpdate); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param id * @param title * @param doc * @param con * @exception Exception */ protected void addChannel (int id, int publisherId, String title, Document doc, Connection con) throws SQLException { Element channel = (Element)doc.getFirstChild(); // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { java.sql.Timestamp rightNow = new java.sql.Timestamp(System.currentTimeMillis()); String sysdate = "{ts '" + rightNow.toString() + "'}"; String sqlTitle = sqlEscape(title); String sqlName = sqlEscape(channel.getAttribute("name")); String sqlFName = sqlEscape(channel.getAttribute("fname")); String sInsert = "INSERT INTO UP_CHANNEL (CHAN_ID, CHAN_TITLE, CHAN_DESC, CHAN_CLASS, CHAN_TYPE_ID, CHAN_PUBL_ID, CHAN_PUBL_DT, CHAN_TIMEOUT, " + "CHAN_MINIMIZABLE, CHAN_EDITABLE, CHAN_HAS_HELP, CHAN_HAS_ABOUT, CHAN_UNREMOVABLE, CHAN_DETACHABLE, CHAN_NAME, CHAN_FNAME) "; sInsert += "VALUES (" + id + ",'" + sqlTitle + "','" + sqlTitle + " Channel','" + channel.getAttribute("class") + "', " + channel.getAttribute("typeID") + "," + publisherId + "," + sysdate + ",'" + channel.getAttribute("timeout") + "'," + "'" + dbBool(channel.getAttribute("minimizable")) + "'" + ",'" + dbBool(channel.getAttribute("editable")) + "'" + ",'" + dbBool(channel.getAttribute("hasHelp")) + "'," + "'" + dbBool(channel.getAttribute("hasAbout")) + "'" + ",'" + dbBool(channel.getAttribute("unremovable")) + "'," + "'" + dbBool(channel.getAttribute("detachable")) + "'" + ",'" + sqlName + "','" + sqlFName + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addChannel(): " + sInsert); stmt.executeUpdate(sInsert); NodeList parameters = channel.getChildNodes(); if (parameters != null) { for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeName().equals("parameter")) { Element parmElement = (Element)parameters.item(i); NamedNodeMap nm = parmElement.getAttributes(); String paramName = null; String paramValue = null; String paramOverride = "NULL"; for (int j = 0; j < nm.getLength(); j++) { Node param = nm.item(j); String nodeName = param.getNodeName(); String nodeValue = param.getNodeValue(); if (DEBUG > 1) { System.err.println(nodeName + "=" + nodeValue); } if (nodeName.equals("name")) { paramName = nodeValue; } else if (nodeName.equals("value")) { paramValue = nodeValue; } else if (nodeName.equals("override") && nodeValue.equals("yes")) { paramOverride = "'Y'"; } } if (paramName == null && paramValue == null) { throw new RuntimeException("Invalid parameter node"); } sInsert = "INSERT INTO UP_CHAN_PARAM (CHAN_ID, CHAN_PARM_NM, CHAN_PARM_VAL, CHAN_PARM_OVRD) VALUES (" + id + ",'" + paramName + "','" + paramValue + "'," + paramOverride + ")"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addChannel(): " + sInsert); stmt.executeUpdate(sInsert); } } } // Commit the transaction commit(con); } catch (SQLException sqle) { rollback(con); throw sqle; } finally { stmt.close(); } } public Document getChannelRegistryXML () throws SQLException { Document doc = new org.apache.xerces.dom.DocumentImpl(); Element registry = doc.createElement("registry"); doc.appendChild(registry); Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID IS NULL ORDER BY CAT_TITLE"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getChannelRegistryXML(): " + query); ResultSet rs = stmt.executeQuery(query); try { while (rs.next()) { int catId = rs.getInt(1); String catTitle = rs.getString(2); String catDesc = rs.getString(3); // Top level <category> Element category = doc.createElement("category"); category.setAttribute("ID", "cat" + catId); category.setAttribute("name", catTitle); category.setAttribute("description", catDesc); ((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(category.getAttribute("ID"), category); registry.appendChild(category); // Add child categories and channels appendChildCategoriesAndChannels(category, catId); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return doc; } protected void appendChildCategoriesAndChannels (Element category, int catId) throws SQLException { Document doc = category.getOwnerDocument(); Connection con = rdbmService.getConnection(); Statement stmt = null; ResultSet rs = null; try { stmt = con.createStatement(); String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID=" + catId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::appendChildCategoriesAndChannels(): " + query); rs = stmt.executeQuery(query); while (rs.next()) { int childCatId = rs.getInt(1); String childCatTitle = rs.getString(2); String childCatDesc = rs.getString(3); // Child <category> Element childCategory = doc.createElement("category"); childCategory.setAttribute("ID", "cat" + childCatId); childCategory.setAttribute("name", childCatTitle); childCategory.setAttribute("description", childCatDesc); ((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(childCategory.getAttribute("ID"), childCategory); category.appendChild(childCategory); // Append child categories and channels recursively appendChildCategoriesAndChannels(childCategory, childCatId); } // Append children channels query = "SELECT CHAN_ID FROM UP_CAT_CHAN WHERE CAT_ID=" + catId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::appendChildCategoriesAndChannels(): " + query); rs = stmt.executeQuery(query); while (rs.next()) { int chanId = rs.getInt(1); // This createChannelNode() method is getting a null pointer exception. // If I can fix this then I can // use the next two lines and remove the appendChildChannel(category, chanId) method. // Element channel = createChannelNode (con, (org.apache.xerces.dom.DocumentImpl)doc, chanId, "chan" + chanId); // category.appendChild(channel); appendChildChannel(category, chanId); } } finally { stmt.close(); con.close(); } } protected void appendChildChannel (Node category, int chanId) throws SQLException { Document doc = category.getOwnerDocument(); Connection con = rdbmService.getConnection(); Statement stmt = null; ResultSet rs = null; Element channel = null; try { stmt = con.createStatement(); String query = "SELECT * FROM UP_CHANNEL WHERE CHAN_ID=" + chanId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::appendChildChannel(): " + query); rs = stmt.executeQuery(query); if (rs.next()) { if (!channelApproved(rs.getTimestamp("CHAN_APVL_DT"))) { /* Channel hasn't been approved yet. Replace it with the error channel and a suitable message */ /* !!!!!!! Add code here someday !!!!!!!!!!!*/ LogService.instance().log(LogService.INFO, "RDBMUserLayoutStore::createLayoutStructure(): Channel " + chanId + "hasn't been approved for publishing yet (ignored at the moment)"); // return new ErrorChannel() } channel = doc.createElement("channel"); createChannelNodeHeaders((org.apache.xerces.dom.DocumentImpl)doc, chanId, "chan" + chanId, rs, channel); rs.close(); query = "SELECT * FROM UP_CHAN_PARAM WHERE CHAN_ID=" + chanId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::createChannelNode(): " + query); rs = stmt.executeQuery(query); while (rs.next()) { createChannelNodeParameters((org.apache.xerces.dom.DocumentImpl)doc, rs, channel); } category.appendChild(channel); } } finally { rs.close(); stmt.close(); } } /** * Get channel types xml. * It will look something like this: * <p><code> * *<channelTypes> * <channelType ID="0"> * <class>org.jasig.portal.channels.CImage</class> * <name>Image</name> * <description>Simple channel to display an image with optional * caption and subcaption</description> * <cpd-uri>webpages/media/org/jasig/portal/channels/CImage/CImage.cpd</cpd-uri> * </channelType> * <channelType ID="1"> * <class>org.jasig.portal.channels.CWebProxy</class> * <name>Web Proxy</name> * <description>Incorporate a dynamic HTML or XML application</description> * <cpd-uri>webpages/media/org/jasig/portal/channels/CWebProxy/CWebProxy.cpd</cpd-uri> * </channelType> *</channelTypes> * * </code></p> * @return types, the channel types as a Document * @throws java.sql.SQLException */ public Document getChannelTypesXML () throws SQLException { Document doc = new org.apache.xerces.dom.DocumentImpl(); Element root = doc.createElement("channelTypes"); doc.appendChild(root); Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT TYPE_ID, TYPE, TYPE_NAME, TYPE_DESCR, TYPE_DEF_URI FROM UP_CHAN_TYPES"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getChannelTypesXML(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int ID = rs.getInt(1); String javaClass = rs.getString(2); String name = rs.getString(3); String descr = rs.getString(4); String cpdUri = rs.getString(5); // <channelType> Element channelType = doc.createElement("channelType"); channelType.setAttribute("ID", String.valueOf(ID)); Element elem = null; // <class> elem = doc.createElement("class"); elem.appendChild(doc.createTextNode(javaClass)); channelType.appendChild(elem); // <name> elem = doc.createElement("name"); elem.appendChild(doc.createTextNode(name)); channelType.appendChild(elem); // <description> elem = doc.createElement("description"); elem.appendChild(doc.createTextNode(descr)); channelType.appendChild(elem); // <cpd-uri> elem = doc.createElement("cpd-uri"); elem.appendChild(doc.createTextNode(cpdUri)); channelType.appendChild(elem); root.appendChild(channelType); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return doc; } /** Returns a string of XML which describes the channel categories. * @param role role of the current user */ public void getCategoryXML (Document catsDoc, Element root, String role) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT UC.CAT_ID, UC.CAT_TITLE " + "FROM UP_CATEGORY UC "; if (role != null && !role.equals("")) { sQuery += ", UP_CAT_CHAN, UCC, UP_CHANNEL UC, UP_ROLE_CHAN URC, UP_ROLE UR" + " WHERE UR.ROLE_TITLE='" + role + "' AND URC.ROLE_ID = UR.ROLE_ID AND URC.CHAN_ID = UC.CHAN_ID" + " AND UC.CHAN_ID = UCC.CHAN_ID AND UCC.CAT_ID = UC.CAT_ID"; } sQuery += " ORDER BY UC.CAT_TITLE"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getCategoryXML(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { Element cat = null; while (rs.next()) { String catnm = rs.getString(2); String id = rs.getString(1); cat = catsDoc.createElement("category"); cat.setAttribute("ID", id); cat.setAttribute("name", catnm); root.appendChild(cat); } catsDoc.appendChild(root); } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * Get the next structure Id * @parameter userId * @result next free structure ID */ public String getNextStructChannelId (int userId) throws Exception { return getNextStructId(userId, channelPrefix); } /** * put your documentation comment here * @param userId * @return * @exception Exception */ public String getNextStructFolderId (int userId) throws Exception { return getNextStructId(userId, folderPrefix); } /** * Return the Structure ID tag * @param structId * @param chanId * @return ID tag */ protected String getStructId(int structId, int chanId) { if (chanId == 0) { return folderPrefix + structId; } else { return channelPrefix + structId; } } /** * put your documentation comment here * @param userId * @param prefix * @return * @exception Exception */ protected String getNextStructId (int userId, String prefix) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { rs.next(); int currentStructId = rs.getInt(1); int nextStructId = currentStructId + 1; sQuery = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + userId + " AND NEXT_STRUCT_ID=" + currentStructId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sQuery); stmt.executeUpdate(sQuery); return prefix + nextStructId; } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * * ReferenceAuthorization * */ /** * Is a user in this role */ public boolean isUserInRole (int userId, String role) throws Exception { Connection con = rdbmService.getConnection(); try { String query = "SELECT * FROM UP_USER_ROLE UUR, UP_ROLE UR, UP_USER UU " + "WHERE UU.USER_ID=" + userId + " UUR.USER_ID=UU.USER_ID AND UUR.ROLE_ID=UR.ROLE_ID " + "AND " + "UPPER(ROLE_TITLE)=UPPER('" + role + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::isUserInRole(): " + query); Statement stmt = con.createStatement(); try { ResultSet rs = stmt.executeQuery(query); try { if (rs.next()) { return (true); } else { return (false); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @return * @exception java.sql.SQLException */ public Vector getAllRoles () throws SQLException { Vector roles = new Vector(); Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT ROLE_TITLE, ROLE_DESC FROM UP_ROLE"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getAllRolessQuery(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { IRole role = null; // Add all of the roles in the portal database to to the vector while (rs.next()) { role = new org.jasig.portal.security.provider.RoleImpl(rs.getString(1)); role.setAttribute("description", rs.getString(2)); roles.add(role); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return (roles); } /** * put your documentation comment here * @param channelID * @param roles * @return * @exception Exception */ public int setChannelRoles (int channelID, Vector roles) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); int recordsInserted = 0; Statement stmt = con.createStatement(); try { // Count the number of records inserted for (int i = 0; i < roles.size(); i++) { String sQuery = "SELECT ROLE_ID FROM UP_ROLE WHERE ROLE_TITLE = '" + roles.elementAt(i) + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setChannelRoles(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { rs.next(); int roleId = rs.getInt("ROLE_ID"); String sInsert = "INSERT INTO UP_ROLE_CHAN (CHAN_ID, ROLE_ID) VALUES (" + channelID + "," + roleId + ")"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setChannelRoles(): " + sInsert); recordsInserted += stmt.executeUpdate(sInsert); } finally { rs.close(); } } } finally { stmt.close(); } // Commit the transaction commit(con); return (recordsInserted); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { rdbmService.releaseConnection(con); } } /** * Get the roles that a channel belongs to * @param channelRoles * @param channelID * @exception Exception */ public void getChannelRoles (Vector channelRoles, int channelID) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String query = "SELECT ROLE_TITLE, CHAN_ID FROM UP_ROLE_CHAN UCR, UP_ROLE UR, UP_CHANNEL UC " + "WHERE UC.CHAN_ID=" + channelID + " AND UC.CHAN_ID=URC.CHAN_ID AND URC.ROLE_ID=UR.ROLE_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getChannelRoles(): " + query); ResultSet rs = stmt.executeQuery(query); try { while (rs.next()) { channelRoles.addElement(rs.getString("ROLE_TITLE")); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * Get the roles that a user belongs to * @param userRoles * @param userId * @exception Exception */ public void getUserRoles (Vector userRoles, int userId) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String query = "SELECT ROLE_TITLE, USER_ID FROM UP_USER_ROLE UUR, UP_ROLE UR, UP_USER UU " + "WHERE UU.USER_ID=" + userId + " AND UU.USER_ID=UUR.USER_ID AND UUR.ROLE_ID=UR.ROLE_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserRoles(): " + query); ResultSet rs = stmt.executeQuery(query); try { while (rs.next()) { userRoles.addElement(rs.getString("ROLE_TITLE")); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param roles * @exception Exception */ public void addUserRoles (int userId, Vector roles) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { int insertCount = 0; for (int i = 0; i < roles.size(); i++) { String query = "SELECT ROLE_ID, ROLE_TITLE FROM UP_ROLE WHERE ROLE_TITLE = '" + roles.elementAt(i) + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addUserRoles(): " + query); ResultSet rs = stmt.executeQuery(query); try { rs.next(); int roleId = rs.getInt("ROLE_ID"); String insert = "INSERT INTO UP_USER_ROLE (USER_ID, ROLE_ID) VALUES (" + userId + ", " + roleId + ")"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addUserRoles(): " + insert); insertCount = stmt.executeUpdate(insert); if (insertCount != 1) { LogService.instance().log(LogService.ERROR, "AuthorizationBean addUserRoles(): SQL failed -> " + insert); } } finally { rs.close(); } } // Commit the transaction commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param roles * @exception Exception */ public void removeUserRoles (int userId, Vector roles) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { int deleteCount = 0; for (int i = 0; i < roles.size(); i++) { String delete = "DELETE FROM UP_USER_ROLE WHERE USER_ID=" + userId + " AND ROLE_ID=" + roles.elementAt(i); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeUserRoles(): " + delete); deleteCount = stmt.executeUpdate(delete); if (deleteCount != 1) { LogService.instance().log(LogService.ERROR, "AuthorizationBean removeUserRoles(): SQL failed -> " + delete); } } // Commit the transaction commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * * Authorization * */ public String[] getUserAccountInformation (String username) throws Exception { String[] acct = new String[] { null, null, null, null }; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String query = "SELECT UP_USER.USER_ID, ENCRPTD_PSWD, FIRST_NAME, LAST_NAME, EMAIL FROM UP_USER, UP_PERSON_DIR WHERE UP_USER.USER_ID = UP_PERSON_DIR.USER_ID AND " + "UP_USER.USER_NAME = '" + username + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserAccountInformation(): " + query); ResultSet rset = stmt.executeQuery(query); try { if (rset.next()) { acct[0] = rset.getInt("USER_ID") + ""; acct[1] = rset.getString("ENCRPTD_PSWD"); acct[2] = rset.getString("FIRST_NAME"); acct[3] = rset.getString("LAST_NAME"); } } finally { rset.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return acct; } /** * * Example Directory Information * Normally directory information would come from a real directory server using * for example, LDAP. The reference inplementation uses the database for * directory information. */ public String[] getUserDirectoryInformation (String username) throws Exception { String[] acct = new String[] { null, null, null }; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String query = "SELECT FIRST_NAME, LAST_NAME, EMAIL FROM UP_USER, UP_PERSON_DIR " + "WHERE UP_USER.USER_ID = UP_PERSON_DIR.USER_ID AND " + "UP_USER.USER_NAME = '" + username + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserDirectoryInformation(): " + query); ResultSet rset = stmt.executeQuery(query); try { if (rset.next()) { acct[0] = rset.getString("FIRST_NAME"); acct[1] = rset.getString("LAST_NAME"); acct[2] = rset.getString("EMAIL"); } } finally { rset.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return acct; } /* DBCounter */ /* * get&increment method. */ public synchronized int getIncrementIntegerId (String tableName) throws Exception { int id; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT SEQUENCE_VALUE FROM UP_SEQUENCE WHERE SEQUENCE_NAME='" + tableName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getIncrementInteger(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { rs.next(); id = rs.getInt("SEQUENCE_VALUE") + 1; } finally { rs.close(); } String sInsert = "UPDATE UP_SEQUENCE SET SEQUENCE_VALUE=" + id + " WHERE SEQUENCE_NAME='" + tableName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getIncrementInteger(): " + sInsert); stmt.executeUpdate(sInsert); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return id; } /** * put your documentation comment here * @param tableName * @exception Exception */ public synchronized void createCounter (String tableName) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sInsert = "INSERT INTO UP_SEQUENCE (SEQUENCE_NAME,SEQUENCE_VALUE/*/) VALUES ('" + tableName + "',0)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::createCounter(): " + sInsert); stmt.executeUpdate(sInsert); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param tableName * @param value * @exception Exception */ public synchronized void setCounter (String tableName, int value) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sUpdate = "UPDATE UP_SEQUENCE SET SEQUENCE_VALUE=" + value + "WHERE SEQUENCE_NAME='" + tableName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setCounter(): " + sUpdate); stmt.executeUpdate(sUpdate); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param connection * @param autocommit */ static final protected void setAutoCommit (Connection connection, boolean autocommit) { try { if (connection.getMetaData().supportsTransactions()) connection.setAutoCommit(autocommit); } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); } } /** * put your documentation comment here * @param connection */ static final protected void commit (Connection connection) { try { if (connection.getMetaData().supportsTransactions()) connection.commit(); } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); } } /** * put your documentation comment here * @param connection */ static final protected void rollback (Connection connection) { try { if (connection.getMetaData().supportsTransactions()) connection.rollback(); } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); } } /** * UserPreferences */ public int getUserBrowserMapping (int userId, String userAgent) throws Exception { int profileId = 0; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT PROFILE_ID, USER_ID FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND USER_AGENT='" + userAgent + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserBrowserMapping(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { profileId = rs.getInt("PROFILE_ID"); } else { return 0; } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return profileId; } /** * put your documentation comment here * @param userId * @param userAgent * @param profileId * @exception Exception */ public void setUserBrowserMapping (int userId, String userAgent, int profileId) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); // remove the old mapping and add the new one Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_USER_UA_MAP WHERE USER_ID='" + userId + "' AND USER_AGENT='" + userAgent + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery); stmt.executeUpdate(sQuery); sQuery = "INSERT INTO UP_USER_UA_MAP (USER_ID,USER_AGENT,PROFILE_ID) VALUES (" + userId + ",'" + userAgent + "'," + profileId + ")"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery); stmt.executeUpdate(sQuery); // Commit the transaction commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param profileId * @return * @exception Exception */ public UserProfile getUserProfileById (int userId, int profileId) throws Exception { UserProfile upl = null; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILES WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileId(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { upl = new UserProfile(profileId, rs.getString("PROFILE_NAME"), rs.getString("DESCRIPTION"), rs.getInt("LAYOUT_ID"), rs.getInt("STRUCTURE_SS_ID"), rs.getInt("THEME_SS_ID")); } else { return null; } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return upl; } /** * put your documentation comment here * @param userId * @return * @exception Exception */ public Hashtable getUserProfileList (int userId) throws Exception { Hashtable pv = new Hashtable(); Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILES WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileList(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { UserProfile upl = new UserProfile(rs.getInt("PROFILE_ID"), rs.getString("PROFILE_NAME"), rs.getString("DESCRIPTION"), rs.getInt("LAYOUT_ID"), rs.getInt("STRUCTURE_SS_ID"), rs.getInt("THEME_SS_ID")); pv.put(new Integer(upl.getProfileId()), upl); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return pv; } /** * put your documentation comment here * @param userId * @param profile * @exception Exception */ public void setUserProfile (int userId, UserProfile profile) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { // this is ugly, but we have to know wether to do INSERT or UPDATE String sQuery = "SELECT USER_ID, PROFILE_NAME FROM UP_USER_PROFILES WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profile.getProfileId(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { sQuery = "UPDATE UP_USER_PROFILES SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID=" + profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='" + profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId(); } else { sQuery = "INSERT INTO UP_USER_PROFILES (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES (" + userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId() + "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')"; } } finally { rs.close(); } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile(): " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param profileId * @param stylesheetId * @return * @exception Exception */ public ThemeStylesheetUserPreferences getThemeStylesheetUserPreferences (int userId, int profileId, int stylesheetId) throws Exception { ThemeStylesheetUserPreferences tsup; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { // get stylesheet description ThemeStylesheetDescription tsd = getThemeStylesheetDescription(stylesheetId); // get user defined defaults String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_USER_SS_PARMS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { // stylesheet param tsd.setStylesheetParameterDefaultValue(rs.getString("PARAM_NAME"), rs.getString("PARAM_VAL")); // LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\""); } } finally { rs.close(); } tsup = new ThemeStylesheetUserPreferences(); tsup.setStylesheetId(stylesheetId); // fill stylesheet description with defaults for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); tsup.putParameterValue(pName, tsd.getStylesheetParameterDefaultValue(pName)); } for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); tsup.addChannelAttribute(pName, tsd.getChannelAttributeDefaultValue(pName)); } // get user preferences sQuery = "SELECT PARAM_NAME, PARAM_VAL, PARAM_TYPE, ULS.STRUCT_ID, CHAN_ID FROM UP_USER_SS_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int param_type = rs.getInt("PARAM_TYPE"); if (param_type == 1) { // stylesheet param LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_USER_SS_ATTS is corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString("PARAM_NAME") + "\", param_type=" + Integer.toString(param_type)); } else if (param_type == 2) { // folder attribute LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : folder attribute specified for the theme stylesheet! UP_USER_SS_ATTS corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString("PARAM_NAME") + "\", param_type=" + Integer.toString(param_type)); } else if (param_type == 3) { // channel attribute tsup.setChannelAttributeValue(getStructId(rs.getInt("STRUCT_ID"),rs.getInt("CHAN_ID")), rs.getString("PARAM_NAME"), rs.getString("PARAM_VAL")); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\""); } else { // unknown param type LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString("PARAM_NAME") + "\", param_type=" + Integer.toString(param_type)); } } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return tsup; } /** * put your documentation comment here * @param userId * @param profileId * @param stylesheetId * @return * @exception Exception */ public StructureStylesheetUserPreferences getStructureStylesheetUserPreferences (int userId, int profileId, int stylesheetId) throws Exception { StructureStylesheetUserPreferences ssup; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { // get stylesheet description StructureStylesheetDescription ssd = getStructureStylesheetDescription(stylesheetId); // get user defined defaults String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_USER_SS_PARMS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { // stylesheet param ssd.setStylesheetParameterDefaultValue(rs.getString("PARAM_NAME"), rs.getString("PARAM_VAL")); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\""); } } finally { rs.close(); } ssup = new StructureStylesheetUserPreferences(); ssup.setStylesheetId(stylesheetId); // fill stylesheet description with defaults for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); ssup.putParameterValue(pName, ssd.getStylesheetParameterDefaultValue(pName)); } for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); ssup.addChannelAttribute(pName, ssd.getChannelAttributeDefaultValue(pName)); } for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); ssup.addFolderAttribute(pName, ssd.getFolderAttributeDefaultValue(pName)); } // get user preferences sQuery = "SELECT PARAM_NAME, PARAM_VAL, PARAM_TYPE, ULS.STRUCT_ID, CHAN_ID FROM UP_USER_SS_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int param_type = rs.getInt("PARAM_TYPE"); if (param_type == 1) { // stylesheet param LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_USER_SS_ATTS is corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString("PARAM_NAME") + "\", param_type=" + Integer.toString(param_type)); } else if (param_type == 2) { // folder attribute ssup.setFolderAttributeValue(getStructId(rs.getInt("STRUCT_ID"),rs.getInt("CHAN_ID")), rs.getString("PARAM_NAME"), rs.getString("PARAM_VAL")); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\""); } else if (param_type == 3) { // channel attribute ssup.setChannelAttributeValue(getStructId(rs.getInt("STRUCT_ID"),rs.getInt("CHAN_ID")), rs.getString("PARAM_NAME"), rs.getString("PARAM_VAL")); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read channel attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\""); } else { // unknown param type LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString("PARAM_NAME") + "\", param_type=" + Integer.toString(param_type)); } } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return ssup; } /** * put your documentation comment here * @param node * @return */ static protected final String getTextChildNodeValue (Node node) { if (node == null) return null; NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i Node child = children.item(i); if (child.getNodeType() == Node.TEXT_NODE) return child.getNodeValue(); } return null; } /** * put your documentation comment here * @param userId * @param profileId * @param ssup * @exception Exception */ public void setStructureStylesheetUserPreferences (int userId, int profileId, StructureStylesheetUserPreferences ssup) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection int stylesheetId = ssup.getStylesheetId(); setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // write out params for (Enumeration e = ssup.getParameterValues().keys(); e.hasMoreElements();) { String pName = (String)e.nextElement(); // see if the parameter was already there String sQuery = "SELECT PARAM_VAL FROM UP_USER_SS_PARMS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_USER_SS_PARMS SET PARAM_VAL='" + ssup.getParameterValue(pName) + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName + "'"; } else { // insert sQuery = "INSERT INTO UP_USER_SS_PARMS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",1,'" + pName + "','" + ssup.getParameterValue(pName) + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } // write out folder attributes for (Enumeration e = ssup.getFolders(); e.hasMoreElements();) { String folderId = (String)e.nextElement(); for (Enumeration attre = ssup.getFolderAttributeNames(); attre.hasMoreElements();) { String pName = (String)attre.nextElement(); String pValue = ssup.getDefinedFolderAttributeValue(folderId, pName); if (pValue != null) { // store user preferences String sQuery = "SELECT PARAM_VAL FROM UP_USER_SS_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + folderId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_USER_SS_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + folderId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=2"; } else { // insert sQuery = "INSERT INTO UP_USER_SS_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",1,'" + folderId.substring(1) + "','" + pName + "',2,'" + pValue + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } } } // write out channel attributes for (Enumeration e = ssup.getChannels(); e.hasMoreElements();) { String channelId = (String)e.nextElement(); for (Enumeration attre = ssup.getChannelAttributeNames(); attre.hasMoreElements();) { String pName = (String)attre.nextElement(); String pValue = ssup.getDefinedChannelAttributeValue(channelId, pName); if (pValue != null) { // store user preferences String sQuery = "SELECT PARAM_VAL FROM UP_USER_SS_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_USER_SS_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; } else { // insert sQuery = "INSERT INTO UP_USER_SS_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",1,'" + channelId.substring(1) + "','" + pName + "',3,'" + pValue + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } } } // Commit the transaction commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param profileId * @param tsup * @exception Exception */ public void setThemeStylesheetUserPreferences (int userId, int profileId, ThemeStylesheetUserPreferences tsup) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection int stylesheetId = tsup.getStylesheetId(); setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // write out params for (Enumeration e = tsup.getParameterValues().keys(); e.hasMoreElements();) { String pName = (String)e.nextElement(); // see if the parameter was already there String sQuery = "SELECT PARAM_VAL FROM UP_USER_SS_PARMS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_USER_SS_PARMS SET PARAM_VAL='" + tsup.getParameterValue(pName) + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName + "'"; } else { // insert sQuery = "INSERT INTO UP_USER_SS_PARMS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",2,'" + pName + "','" + tsup.getParameterValue(pName) + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } // write out channel attributes for (Enumeration e = tsup.getChannels(); e.hasMoreElements();) { String channelId = (String)e.nextElement(); for (Enumeration attre = tsup.getChannelAttributeNames(); attre.hasMoreElements();) { String pName = (String)attre.nextElement(); String pValue = tsup.getDefinedChannelAttributeValue(channelId, pName); if (pValue != null) { // store user preferences String sQuery = "SELECT PARAM_VAL FROM UP_USER_SS_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_USER_SS_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; } else { // insert sQuery = "INSERT INTO UP_USER_SS_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",2,'" + channelId.substring(1) + "','" + pName + "',3,'" + pValue + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } } } // Commit the transaction commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param profile * @exception Exception */ public void updateUserProfile (int userId, UserProfile profile) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "UPDATE UP_USER_PROFILES SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID=" + profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='" + profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateUserProfile() : " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param profile * @return * @exception Exception */ public UserProfile addUserProfile (int userId, UserProfile profile) throws Exception { // generate an id for this profile Connection con = rdbmService.getConnection(); try { int id = getIncrementIntegerId("UP_USER_PROFILES"); profile.setProfileId(id); Statement stmt = con.createStatement(); try { String sQuery = "INSERT INTO UP_USER_PROFILES (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES (" + userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId() + "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addUserProfile(): " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return profile; } /** * put your documentation comment here * @param userId * @param profileId * @exception Exception */ public void deleteUserProfile (int userId, int profileId) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_USER_PROFILES WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param chanDoc * @return */ static final protected String serializeDOM (Document chanDoc) { StringWriter stringOut = null; try { OutputFormat format = new OutputFormat(chanDoc); //Serialize DOM stringOut = new StringWriter(); //Writer will be a String XMLSerializer serial = new XMLSerializer(stringOut, format); serial.asDOMSerializer(); // As a DOM Serializer serial.serialize(chanDoc.getDocumentElement()); } catch (java.io.IOException ioe) { LogService.instance().log(LogService.ERROR, ioe); } return stringOut.toString(); //LogService.instance().log(LogService.DEBUG, "STRXML = " + stringOut.toString()); } /** * * CoreStyleSheet * */ public void getMimeTypeList (Hashtable list) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT A.MIME_TYPE, A.MIME_TYPE_DESCRIPTION FROM UP_MIME_TYPES A, UP_SS_MAP B WHERE B.MIME_TYPE=A.MIME_TYPE"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getMimeTypeList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { list.put(rs.getString("MIME_TYPE"), rs.getString("MIME_TYPE_DESCRIPTION")); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * Obtain a list of structure stylesheet descriptions that have stylesheets for a given * mime type. * @param mimeType * @return a mapping from stylesheet names to structure stylesheet description objects */ public Hashtable getStructureStylesheetList (String mimeType) throws Exception { Connection con = rdbmService.getConnection(); Hashtable list = new Hashtable(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT A.SS_ID FROM UP_STRUCT_SS A, UP_THEME_SS B WHERE B.MIME_TYPE='" + mimeType + "' AND B.STRUCT_SS_ID=A.SS_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { StructureStylesheetDescription ssd = getStructureStylesheetDescription(rs.getInt("SS_ID")); if (ssd != null) list.put(new Integer(ssd.getId()), ssd); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return list; } /** * Obtain a list of theme stylesheet descriptions for a given structure stylesheet * @param structureStylesheetName * @return a map of stylesheet names to theme stylesheet description objects * @exception Exception */ public Hashtable getThemeStylesheetList (int structureStylesheetId) throws Exception { Connection con = rdbmService.getConnection(); Hashtable list = new Hashtable(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_THEME_SS WHERE STRUCT_SS_ID=" + structureStylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { ThemeStylesheetDescription tsd = getThemeStylesheetDescription(rs.getInt("SS_ID")); if (tsd != null) list.put(new Integer(tsd.getId()), tsd); } } finally { rs.close(); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return list; } /** * put your documentation comment here * @param stylesheetName * @exception Exception */ public void removeStructureStylesheetDescription (int stylesheetId) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { // detele all associated theme stylesheets String sQuery = "SELECT SS_ID FROM UP_THEME_SS WHERE STRUCT_SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { removeThemeStylesheetDescription(rs.getInt("SS_ID")); } } finally { rs.close(); } sQuery = "DELETE FROM UP_STRUCT_SS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // delete params sQuery = "DELETE FROM UP_STRUCT_PARAMS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // clean up user preferences // should we do something about profiles ? commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param stylesheetName * @exception Exception */ public void removeThemeStylesheetDescription (int stylesheetId) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_THEME_SS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // delete params sQuery = "DELETE FROM UP_THEME_PARAMS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // clean up user preferences sQuery = "DELETE FROM UP_USER_SS_PARMS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); sQuery = "DELETE FROM UP_USER_SS_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // nuke the profiles as well ? commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * put your documentation comment here * @param userId * @param doc * @exception Exception */ public void saveBookmarkXML (int userId, Document doc) throws Exception { StringWriter outString = new StringWriter(); XMLSerializer xsl = new XMLSerializer(outString, new OutputFormat(doc)); xsl.serialize(doc); Connection con = rdbmService.getConnection(); try { Statement statem = con.createStatement(); try { String sQuery = "UPDATE UPC_BOOKMARKS SET BOOKMARK_XML = '" + outString.toString() + "' WHERE PORTAL_USER_ID = " + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveBookmarkXML(): " + sQuery); statem.executeUpdate(sQuery); } finally { statem.close(); } } finally { rdbmService.releaseConnection(con); } } /** * Obtain ID for known structure stylesheet name * @param ssName name of the structure stylesheet * @return id or null if no stylesheet matches the name given. */ public Integer getStructureStylesheetId (String ssName) throws Exception { Integer id = null; Connection con = rdbmService.getConnection(); try { setAutoCommit(con, false); Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_STRUCT_SS WHERE SS_NAME='" + ssName + "'"; ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { id = new Integer(rs.getInt("SS_ID")); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return id; } /** * Obtain ID for known theme stylesheet name * @param ssName name of the theme stylesheet * @return id or null if no theme matches the name given. */ public Integer getThemeStylesheetId (String tsName) throws Exception { Integer id = null; Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_THEME_SS WHERE SS_NAME='" + tsName + "'"; ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { id = new Integer(rs.getInt("SS_ID")); } } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } return id; } /** * Remove (with cleanup) a theme stylesheet param * @param stylesheetId id of the theme stylesheet * @param pName name of the parameter * @param con active database connection */ private void removeThemeStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_THEME_PARAMS WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_USER_SS_PARMS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } /** * Remove (with cleanup) a theme stylesheet channel attribute * @param stylesheetId id of the theme stylesheet * @param pName name of the attribute * @param con active database connection */ private void removeThemeChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_THEME_PARAMS WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeChannelAttribute() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_USER_SS_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } /** * Updates an existing structure stylesheet description with a new one. Old stylesheet * description is found based on the Id provided in the parameter structure. * @param ssd new stylesheet description */ public void updateThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { int stylesheetId = tsd.getId(); String sQuery = "UPDATE UP_THEME_SS SET SS_NAME='" + tsd.getStylesheetName() + "',SS_URI='" + tsd.getStylesheetURI() + "',SS_DESCRIPTION_URI='" + tsd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + tsd.getStylesheetWordDescription() + "' WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // first, see what was there before HashSet oparams = new HashSet(); HashSet ocattrs = new HashSet(); sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_THEME_PARAMS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); Statement stmtOld = con.createStatement(); ResultSet rsOld = stmtOld.executeQuery(sQuery); try { while (rsOld.next()) { int type = rsOld.getInt("TYPE"); if (type == 1) { // stylesheet param String pName = rsOld.getString("PARAM_NAME"); oparams.add(pName); if (!tsd.containsParameterName(pName)) { // delete param removeThemeStylesheetParam(stylesheetId, pName, con); } else { // update param sQuery = "UPDATE UP_THEME_PARAMS SET PARAM_DEFAULT_VAL='" + tsd.getStylesheetParameterDefaultValue(pName) + "',PARAM_DESCRIPT='" + tsd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=1"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else if (type == 2) { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! DB is corrupt. (stylesheetId=" + stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + rsOld.getInt("TYPE") + ")."); } else if (type == 3) { // channel attribute String pName = rsOld.getString("PARAM_NAME"); ocattrs.add(pName); if (!tsd.containsChannelAttribute(pName)) { // delete channel attribute removeThemeChannelAttribute(stylesheetId, pName, con); } else { // update channel attribute sQuery = "UPDATE UP_THEME_PARAMS SET PARAM_DEFAULT_VAL='" + tsd.getChannelAttributeDefaultValue(pName) + "',PARAM_DESCRIPT='" + tsd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + rsOld.getInt("TYPE") + ")."); } } } finally { rsOld.close(); stmtOld.close(); } // look for new attributes/parameters // insert all stylesheet params for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!oparams.contains(pName)) { sQuery = "INSERT INTO UP_THEME_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // insert all channel attributes for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!ocattrs.contains(pName)) { sQuery = "INSERT INTO UP_THEME_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // Commit the transaction commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * Remove (with cleanup) a structure stylesheet param * @param stylesheetId id of the structure stylesheet * @param pName name of the parameter * @param con active database connection */ private void removeStructureStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_STRUCT_PARAMS WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_USER_SS_PARMS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } /** * Remove (with cleanup) a structure stylesheet folder attribute * @param stylesheetId id of the structure stylesheet * @param pName name of the attribute * @param con active database connection */ private void removeStructureFolderAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_STRUCT_PARAMS WHERE SS_ID=" + stylesheetId + " AND TYPE=2 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_USER_SS_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=2 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } /** * Remove (with cleanup) a structure stylesheet channel attribute * @param stylesheetId id of the structure stylesheet * @param pName name of the attribute * @param con active database connection */ private void removeStructureChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_STRUCT_PARAMS WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_USER_SS_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } /** * Updates an existing structure stylesheet description with a new one. Old stylesheet * description is found based on the Id provided in the parameter structure. * @param ssd new stylesheet description */ public void updateStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { int stylesheetId = ssd.getId(); String sQuery = "UPDATE UP_STRUCT_SS SET SS_NAME='" + ssd.getStylesheetName() + "',SS_URI='" + ssd.getStylesheetURI() + "',SS_DESCRIPTION_URI='" + ssd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + ssd.getStylesheetWordDescription() + "' WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // first, see what was there before HashSet oparams = new HashSet(); HashSet ofattrs = new HashSet(); HashSet ocattrs = new HashSet(); sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_STRUCT_PARAMS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); Statement stmtOld = con.createStatement(); ResultSet rsOld = stmtOld.executeQuery(sQuery); try { while (rsOld.next()) { int type = rsOld.getInt("TYPE"); if (type == 1) { // stylesheet param String pName = rsOld.getString("PARAM_NAME"); oparams.add(pName); if (!ssd.containsParameterName(pName)) { // delete param removeStructureStylesheetParam(stylesheetId, pName, con); } else { // update param sQuery = "UPDATE UP_STRUCT_PARAMS SET PARAM_DEFAULT_VAL='" + ssd.getStylesheetParameterDefaultValue(pName) + "',PARAM_DESCRIPT='" + ssd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=1"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else if (type == 2) { // folder attribute String pName = rsOld.getString("PARAM_NAME"); ofattrs.add(pName); if (!ssd.containsFolderAttribute(pName)) { // delete folder attribute removeStructureFolderAttribute(stylesheetId, pName, con); } else { // update folder attribute sQuery = "UPDATE UP_STRUCT_PARAMS SET PARAM_DEFAULT_VAL='" + ssd.getFolderAttributeDefaultValue(pName) + "',PARAM_DESCRIPT='" + ssd.getFolderAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "'AND TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else if (type == 3) { // channel attribute String pName = rsOld.getString("PARAM_NAME"); ocattrs.add(pName); if (!ssd.containsChannelAttribute(pName)) { // delete channel attribute removeStructureChannelAttribute(stylesheetId, pName, con); } else { // update channel attribute sQuery = "UPDATE UP_STRUCT_PARAMS SET PARAM_DEFAULT_VAL='" + ssd.getChannelAttributeDefaultValue(pName) + "',PARAM_DESCRIPT='" + ssd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + rsOld.getInt("TYPE") + ")."); } } } finally { rsOld.close(); stmtOld.close(); } // look for new attributes/parameters // insert all stylesheet params for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!oparams.contains(pName)) { sQuery = "INSERT INTO UP_STRUCT_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // insert all folder attributes for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!ofattrs.contains(pName)) { sQuery = "INSERT INTO UP_STRUCT_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName) + "',2)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // insert all channel attributes for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!ocattrs.contains(pName)) { sQuery = "INSERT INTO UP_STRUCT_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // Commit the transaction commit(con); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * Registers a NEW structure stylesheet with the database. * @param tsd Stylesheet description object */ public Integer addStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // we assume that this is a new stylesheet. int id = getIncrementIntegerId("UP_STRUCT_SS"); ssd.setId(id); String sQuery = "INSERT INTO UP_STRUCT_SS (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT) VALUES (" + id + ",'" + ssd.getStylesheetName() + "','" + ssd.getStylesheetURI() + "','" + ssd.getStylesheetDescriptionURI() + "','" + ssd.getStylesheetWordDescription() + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); // insert all stylesheet params for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_STRUCT_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // insert all folder attributes for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_STRUCT_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName) + "',2)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // insert all channel attributes for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_STRUCT_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // Commit the transaction commit(con); return new Integer(id); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } /** * Obtain structure stylesheet description object for a given structure stylesheet id * @para id id of the structure stylesheet * @return structure stylesheet description */ public StructureStylesheetDescription getStructureStylesheetDescription (int stylesheetId) throws Exception { StructureStylesheetDescription ssd = null; Connection con = rdbmService.getConnection(); Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT FROM UP_STRUCT_SS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { try { ssd = new StructureStylesheetDescription(); ssd.setId(stylesheetId); ssd.setStylesheetName(rs.getString("SS_NAME")); ssd.setStylesheetURI(rs.getString("SS_URI")); ssd.setStylesheetDescriptionURI(rs.getString("SS_DESCRIPTION_URI")); ssd.setStylesheetWordDescription(rs.getString("SS_DESCRIPTION_TEXT")); } finally { rs.close(); } } // retreive stylesheet params and attributes sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_STRUCT_PARAMS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int type = rs.getInt("TYPE"); if (type == 1) { // param ssd.addStylesheetParameter(rs.getString("PARAM_NAME"), rs.getString("PARAM_DEFAULT_VAL"), rs.getString("PARAM_DESCRIPT")); } else if (type == 2) { // folder attribute ssd.addFolderAttribute(rs.getString("PARAM_NAME"), rs.getString("PARAM_DEFAULT_VAL"), rs.getString("PARAM_DESCRIPT")); } else if (type == 3) { // channel attribute ssd.addChannelAttribute(rs.getString("PARAM_NAME"), rs.getString("PARAM_DEFAULT_VAL"), rs.getString("PARAM_DESCRIPT")); } else { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rs.getString("PARAM_NAME") + "\" type=" + rs.getInt("TYPE") + ")."); } } } finally { rs.close(); } } finally { stmt.close(); rdbmService.releaseConnection(con); } return ssd; } /** * Obtain theme stylesheet description object for a given theme stylesheet id * @para id id of the theme stylesheet * @return theme stylesheet description */ public ThemeStylesheetDescription getThemeStylesheetDescription (int stylesheetId) throws Exception { ThemeStylesheetDescription tsd = null; Connection con = rdbmService.getConnection(); Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_ICON_URI,SAMPLE_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS FROM UP_THEME_SS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { tsd = new ThemeStylesheetDescription(); tsd.setId(stylesheetId); tsd.setStylesheetName(rs.getString("SS_NAME")); tsd.setStylesheetURI(rs.getString("SS_URI")); tsd.setStylesheetDescriptionURI(rs.getString("SS_DESCRIPTION_URI")); tsd.setStylesheetWordDescription(rs.getString("SS_DESCRIPTION_TEXT")); tsd.setStructureStylesheetId(rs.getInt("STRUCT_SS_ID")); tsd.setSamplePictureURI(rs.getString("SAMPLE_URI")); tsd.setSampleIconURI(rs.getString("SAMPLE_ICON_URI")); tsd.setMimeType(rs.getString("MIME_TYPE")); tsd.setDeviceType(rs.getString("DEVICE_TYPE")); tsd.setSerializerName(rs.getString("SERIALIZER_NAME")); tsd.setCustomUserPreferencesManagerClass(rs.getString("UP_MODULE_CLASS")); } } finally { rs.close(); } // retreive stylesheet params and attributes sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_THEME_PARAMS WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int type = rs.getInt("TYPE"); if (type == 1) { // param tsd.addStylesheetParameter(rs.getString("PARAM_NAME"), rs.getString("PARAM_DEFAULT_VAL"), rs.getString("PARAM_DESCRIPT")); } else if (type == 3) { // channel attribute tsd.addChannelAttribute(rs.getString("PARAM_NAME"), rs.getString("PARAM_DEFAULT_VAL"), rs.getString("PARAM_DESCRIPT")); } else if (type == 2) { // folder attributes are not allowed here LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! Corrupted DB entry. (stylesheetId=" + stylesheetId + " param_name=\"" + rs.getString("PARAM_NAME") + "\" type=" + rs.getInt("TYPE") + ")."); } else { LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rs.getString("PARAM_NAME") + "\" type=" + rs.getInt("TYPE") + ")."); } } } finally { rs.close(); } } finally { stmt.close(); rdbmService.releaseConnection(con); } return tsd; } /** * Registers a NEW theme stylesheet with the database. * @param tsd Stylesheet description object */ public Integer addThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception { Connection con = rdbmService.getConnection(); try { // Set autocommit false for the connection setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // we assume that this is a new stylesheet. int id = getIncrementIntegerId("UP_THEME_SS"); tsd.setId(id); String sQuery = "INSERT INTO UP_THEME_SS (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_URI,SAMPLE_ICON_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS) VALUES (" + id + ",'" + tsd.getStylesheetName() + "','" + tsd.getStylesheetURI() + "','" + tsd.getStylesheetDescriptionURI() + "','" + tsd.getStylesheetWordDescription() + "'," + tsd.getStructureStylesheetId() + ",'" + tsd.getSamplePictureURI() + "','" + tsd.getSampleIconURI() + "','" + tsd.getMimeType() + "','" + tsd.getDeviceType() + "','" + tsd.getSerializerName() + "','" + tsd.getCustomUserPreferencesManagerClass() + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); // insert all stylesheet params for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_THEME_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // insert all channel attributes for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_THEME_PARAMS (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // Commit the transaction commit(con); return new Integer(id); } catch (Exception e) { // Roll back the transaction rollback(con); throw e; } finally { stmt.close(); } } finally { rdbmService.releaseConnection(con); } } }
package dev.blunch.blunch.activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; 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.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.facebook.FacebookSdk; import java.util.ArrayList; import java.util.List; import dev.blunch.blunch.R; import dev.blunch.blunch.adapters.MenuListAdapter; import dev.blunch.blunch.domain.User; import dev.blunch.blunch.services.CollaborativeMenuService; import dev.blunch.blunch.services.MenuService; import dev.blunch.blunch.services.PaymentMenuService; import dev.blunch.blunch.services.ServiceFactory; import dev.blunch.blunch.utils.Preferences; import dev.blunch.blunch.utils.Repository; @SuppressWarnings("all") public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { MenuService menuService; CollaborativeMenuService collaborativeMenuService; PaymentMenuService paymentMenuService; private String email; FloatingActionButton fab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); email = Preferences.getCurrentUserEmail(); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle("Buscar menús"); menuService = ServiceFactory.getMenuService(getApplicationContext()); collaborativeMenuService = ServiceFactory.getCollaborativeMenuService(getApplicationContext()); paymentMenuService = ServiceFactory.getPaymentMenuService(getApplicationContext()); 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); navigationView.getMenu().getItem(0).setChecked(true); setUserInfo(navigationView); initFragment(R.layout.content_list_menus); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setImageResource(R.drawable.add); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("Qué tipo de menú quieres dar de alta?") .setPositiveButton("Menú colaborativo", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(MainActivity.this, NewCollaborativeMenuActivity.class); startActivity(intent); } }) .setNegativeButton("Menú de pago", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(MainActivity.this, NewPaymentMenuActivity.class); startActivity(intent); } }); AlertDialog alert = builder.create(); alert.show(); } }); initializeSearchMenus(); } private void setUserInfo(NavigationView navigationView) { View headerView = navigationView.getHeaderView(0); User user = menuService.findUserByEmail(email); TextView userName = (TextView) headerView.findViewById(R.id.user_name_nav); try { userName.setText(user.getName()); ImageView userPhoto = (ImageView) headerView.findViewById(R.id.user_picture_nav); userPhoto.setImageDrawable(user.getImageRounded(getResources())); } catch (Exception e) { e.printStackTrace(); } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { Intent i = new Intent(); i.setAction(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); this.startActivity(i); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { 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.search_menus) { initFragment(R.layout.content_list_menus); Toast.makeText(getApplicationContext(), "Search menus", Toast.LENGTH_SHORT).show(); initializeSearchMenus(); } else if (id == R.id.my_menus) { initFragment(-1); Toast.makeText(getApplicationContext(), "My menus", Toast.LENGTH_SHORT).show(); initializeMyMenus(); } else if (id == R.id.collaborating_menus) { initFragment(-1); Toast.makeText(getApplicationContext(), "Collaborating menus", Toast.LENGTH_SHORT).show(); initializeCollaboratingMenus(); } else if (id == R.id.old_menus) { initFragment(R.layout.content_list_old_menus); Toast.makeText(getApplicationContext(), "Valoración de menus", Toast.LENGTH_SHORT).show(); initializeOldMenus(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } private void initFragment(int id) { LayoutInflater inflater = getLayoutInflater(); View v; if (id != -1) v = inflater.inflate(id, null); else v = new View(getApplicationContext()); FrameLayout frameLayout = (FrameLayout) findViewById(R.id.main_frame_layout); frameLayout.removeAllViews(); frameLayout.addView(v); } private void initializeSearchMenus() { Spinner spinner = (Spinner) findViewById(R.id.menu_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.menu_types, R.layout.spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { init(parent.getItemAtPosition(position).toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); menuService.setOnChangedListener(new Repository.OnChangedListener() { @Override public void onChanged(EventType type) { if (type.equals(EventType.Full)) { init("Todos"); } } }); } private void init(String filter) { List<dev.blunch.blunch.domain.Menu> menuList = new ArrayList<>(); switch (filter) { case "Todos": menuList.addAll(menuService.getMenusOrderedByDate()); break; case "Colaborativo": menuList.addAll(menuService.getCollaborativeMenusOrderedByDate()); break; case "De pago": menuList.addAll(menuService.getPaymentMenusOrderedByDate()); break; default: menuList.addAll(menuService.getMenusOrderedByDate()); break; } final MenuListAdapter menuListAdapter = new MenuListAdapter( getApplicationContext(), menuList, menuService.getUsers()); ListView listView = (ListView) findViewById(R.id.menu_list); listView.setAdapter(menuListAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dev.blunch.blunch.domain.Menu menu = menuListAdapter.getItem(position); String s = menu.getClass().getSimpleName(); switch (s) { case "CollaborativeMenu": Intent intent = new Intent(MainActivity.this, GetCollaborativeMenuActivity.class); intent.putExtra(GetCollaborativeMenuActivity.MENU_ID_KEY, menu.getId()); startActivity(intent); break; case "PaymentMenu": Intent intent2 = new Intent(MainActivity.this, GetPaymentMenuActivity.class); intent2.putExtra(GetPaymentMenuActivity.MENU_ID_KEY, menu.getId()); startActivity(intent2); break; default: break; } } }); } private void initializeCollaboratingMenus() { //TODO fill view setTitle("Menús en colaboración"); } private void initializeOldMenus() { setTitle("Valoración de menus"); Spinner spinner = (Spinner) findViewById(R.id.menu_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.old_menu_types, R.layout.spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { initOldMenus(parent.getItemAtPosition(position).toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); menuService.setOnChangedListener(new Repository.OnChangedListener() { @Override public void onChanged(EventType type) { if (type.equals(EventType.Full)) { initOldMenus("All"); } } }); } private void initOldMenus(String filter) { List<dev.blunch.blunch.domain.Menu> menuList = new ArrayList<>(); switch (filter) { case "No valorados": menuList.addAll(menuService.getNonValuedCollaboratedMenusOf(email)); break; case "Valorados": menuList.addAll(menuService.getValuedCollaboratedMenusOf(email)); break; case "Todos": menuList.addAll(menuService.getCollaboratedMenusOf(email)); break; default: menuList.addAll(menuService.getNonValuedCollaboratedMenusOf(email)); break; } final MenuListAdapter menuListAdapter = new MenuListAdapter( getApplicationContext(), menuList, menuService.getUsers()); ListView listView = (ListView) findViewById(R.id.menu_list); listView.setAdapter(menuListAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dev.blunch.blunch.domain.Menu menu = menuListAdapter.getItem(position); // TODO Access to valorations repositories and search if menu was valorated by current user String menuId = menu.getId(); String s = ""; // TODO Split Menus between NonValued and Valued. // Valued -> On click: Valoration Activity // NonValued -> On click: SnackBar notifying that Menu has already valorated. switch (s) { case "CollaborativeMenu": Intent intent = new Intent(MainActivity.this, GetCollaborativeMenuActivity.class); intent.putExtra(GetCollaborativeMenuActivity.MENU_ID_KEY, menu.getId()); startActivity(intent); break; case "PaymentMenu": Intent intent2 = new Intent(MainActivity.this, GetPaymentMenuActivity.class); intent2.putExtra(GetPaymentMenuActivity.MENU_ID_KEY, menu.getId()); startActivity(intent2); break; default: break; } } }); } private void initializeMyMenus() { //TODO fill view setTitle("Mis menús"); } @Override protected void onResume() { super.onResume(); init("Todos"); } }
package org.jpos.ee; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.hibernate.*; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.EntityKey; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.resource.transaction.spi.TransactionStatus; import org.hibernate.stat.SessionStatistics; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; import org.jpos.core.ConfigurationException; import org.jpos.ee.support.ModuleUtils; import org.jpos.space.Space; import org.jpos.space.SpaceFactory; import org.jpos.util.Log; import org.jpos.util.LogEvent; import org.jpos.util.Logger; import java.io.Closeable; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; @SuppressWarnings({"UnusedDeclaration"}) public class DB implements Closeable { Session session; Log log; String configModifier; private static Map<String,Semaphore> sfSems = Collections.synchronizedMap(new HashMap<>()); private static Map<String,Semaphore> mdSems = Collections.synchronizedMap(new HashMap<>()); private static String propFile; private static final String MODULES_CONFIG_PATH = "META-INF/org/jpos/ee/modules/"; private static Map<String,SessionFactory> sessionFactories = Collections.synchronizedMap(new HashMap<>()); private static Map<String,Metadata> metadatas = Collections.synchronizedMap(new HashMap<>()); /** * Creates DB Object using default Hibernate instance */ public DB() { this((String) null); } /** * Creates DB Object using a config <i>modifier</i>. * * The <i>configModifier</i> can take a number of different forms used to locate the <code>cfg/db.properties</code> file. * * <ul> * * <li>a filename prefix, i.e.: "mysql" used as modifier would pick the configuration from * <code>cfg/mysql-db.properties</code> instead of the default <code>cfg/db.properties</code> </li> * * <li>if a colon and a second modifier is present (e.g.: "mysql:v1"), the metadata is picked from * <code>META-INF/org/jpos/ee/modules/v1-*</code> instead of just * <code>META-INF/org/jpos/ee/modules/</code> </li> * * <li>finally, if the modifier ends with <code>.hbm.xml</code> (case insensitive), then all configuration * is picked from that config file.</li> * </ul> * * @param configModifier modifier */ public DB (String configModifier) { super(); this.configModifier = configModifier; sfSems.putIfAbsent(configModifier, new Semaphore(1)); mdSems.putIfAbsent(configModifier, new Semaphore(1)); } /** * Creates DB Object using default Hibernate instance * * @param log Log object */ public DB(Log log) { super(); setLog(log); } /** * Creates DB Object using default Hibernate instance * * @param log Log object * @param configModifier modifier */ public DB(Log log, String configModifier) { this(configModifier); setLog(log); } /** * @return Hibernate's session factory */ public SessionFactory getSessionFactory() { Semaphore sfSem = sfSems.get(configModifier); SessionFactory sf; String cm = configModifier != null ? configModifier : ""; try { if (!sfSem.tryAcquire(60, TimeUnit.SECONDS)) { throw new RuntimeException ("Unable to acquire lock"); } sf = sessionFactories.get(cm); if (sf == null) sessionFactories.put(cm, sf = newSessionFactory()); } catch (IOException | ConfigurationException | DocumentException | InterruptedException e) { throw new RuntimeException("Could not configure session factory", e); } finally { sfSem.release(); } return sf; } public static synchronized void invalidateSessionFactories() { sessionFactories.clear(); } private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException, InterruptedException { return getMetadata().buildSessionFactory(); } private void configureProperties(Configuration cfg) throws IOException { String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties"); Properties dbProps = loadProperties(propFile); if (dbProps != null) { cfg.addProperties(dbProps); } } private void configureMappings(Configuration cfg) throws ConfigurationException, IOException { try { List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/"); for (String moduleConfig : moduleConfigs) { addMappings(cfg, moduleConfig); } } catch (DocumentException e) { throw new ConfigurationException("Could not parse mappings document", e); } } private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException { Element module = readMappingElements(moduleConfig); if (module != null) { for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) { Element mapping = (Element) l.next(); parseMapping(cfg, mapping, moduleConfig); } } } private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException { final String resource = mapping.attributeValue("resource"); final String clazz = mapping.attributeValue("class"); if (resource != null) { cfg.addResource(resource); } else if (clazz != null) { try { cfg.addAnnotatedClass(ReflectHelper.classForName(clazz)); } catch (ClassNotFoundException e) { throw new ConfigurationException("Class " + clazz + " specified in mapping for module " + moduleName + " cannot be found"); } } else { throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName); } } private Element readMappingElements(String moduleConfig) throws DocumentException { SAXReader reader = new SAXReader(); final URL url = getClass().getClassLoader().getResource(moduleConfig); assert url != null; final Document doc = reader.read(url); return doc.getRootElement().element("mappings"); } private Properties loadProperties(String filename) throws IOException { Properties props = new Properties(); final String s = filename.replaceAll("/", "\\" + File.separator); final File f = new File(s); if (f.exists()) { props.load(new FileReader(f)); } return props; } /** * Creates database schema * * @param outputFile optional output file (may be null) * @param create true to actually issue the create statements */ public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException { try { // SchemaExport export = new SchemaExport(getMetadata()); SchemaExport export = new SchemaExport(); List<TargetType> targetTypes=new ArrayList<>(); if (outputFile != null) { export.setDelimiter(";"); if(outputFile.trim().equals("-")) { targetTypes.add(TargetType.STDOUT); } else { export.setOutputFile(outputFile); targetTypes.add(TargetType.SCRIPT); } } if (create) targetTypes.add(TargetType.DATABASE); if(targetTypes.size()>0) export.create(EnumSet.copyOf(targetTypes), getMetadata()); } catch (IOException | ConfigurationException | InterruptedException e) { throw new HibernateException("Could not create schema", e); } } /** * open a new HibernateSession if none exists * * @return HibernateSession associated with this DB object * @throws HibernateException */ public synchronized Session open() throws HibernateException { if (session == null) { session = getSessionFactory().openSession(); } return session; } /** * close hibernate session * * @throws HibernateException */ public synchronized void close() throws HibernateException { if (session != null) { session.close(); session = null; } } /** * @return session hibernate Session */ public Session session() { return session; } /** * handy method used to avoid having to call db.session().save (xxx) * * @param obj to save */ public void save(Object obj) throws HibernateException { session.save(obj); } /** * handy method used to avoid having to call db.session().saveOrUpdate (xxx) * * @param obj to save or update */ public void saveOrUpdate(Object obj) throws HibernateException { session.saveOrUpdate(obj); } public void delete(Object obj) { session.delete(obj); } /** * @return newly created Transaction * @throws HibernateException */ public synchronized Transaction beginTransaction() throws HibernateException { return session.beginTransaction(); } public synchronized void commit() { if (session() != null) { Transaction tx = session().getTransaction(); if (tx != null && tx.getStatus().isOneOf(TransactionStatus.ACTIVE)) { tx.commit(); } } } public synchronized void rollback() { if (session() != null) { Transaction tx = session().getTransaction(); if (tx != null && tx.getStatus().canRollback()) { tx.rollback(); } } } /** * @param timeout in seconds * @return newly created Transaction * @throws HibernateException */ public synchronized Transaction beginTransaction(int timeout) throws HibernateException { Transaction tx = session.getTransaction(); if (timeout > 0) tx.setTimeout(timeout); tx.begin(); return tx; } public synchronized Log getLog() { if (log == null) { log = Log.getLog("Q2", "DB"); // Q2 standard Logger } return log; } public synchronized void setLog(Log log) { this.log = log; } public static Object exec(DBAction action) throws Exception { try (DB db = new DB()) { db.open(); return action.exec(db); } } public static Object exec(String configModifier, DBAction action) throws Exception { try (DB db = new DB(configModifier)) { db.open(); return action.exec(db); } } public static Object execWithTransaction(DBAction action) throws Exception { try (DB db = new DB()) { db.open(); db.beginTransaction(); Object obj = action.exec(db); db.commit(); return obj; } } public static Object execWithTransaction(String configModifier, DBAction action) throws Exception { try (DB db = new DB(configModifier)) { db.open(); db.beginTransaction(); Object obj = action.exec(db); db.commit(); return obj; } } @SuppressWarnings("unchecked") public static <T> T unwrap (T proxy) { Hibernate.getClass(proxy); Hibernate.initialize(proxy); return (proxy instanceof HibernateProxy) ? (T) ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation() : proxy; } @SuppressWarnings({"unchecked"}) public void printStats() { if (getLog() != null) { LogEvent info = getLog().createInfo(); if (session != null) { info.addMessage("==== STATISTICS ===="); SessionStatistics statistics = session().getStatistics(); info.addMessage("==== ENTITIES ===="); Set<EntityKey> entityKeys = statistics.getEntityKeys(); for (EntityKey ek : entityKeys) { info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName())); } info.addMessage("==== COLLECTIONS ===="); Set<CollectionKey> collectionKeys = statistics.getCollectionKeys(); for (CollectionKey ck : collectionKeys) { info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole())); } info.addMessage("====================="); } else { info.addMessage("Session is not open"); } Logger.log(info); } } @Override public String toString() { return "DB{" + (configModifier != null ? configModifier : "") + '}'; } private Metadata getMetadata() throws IOException, ConfigurationException, DocumentException, InterruptedException { Semaphore mdSem = mdSems.get(configModifier); if (!mdSem.tryAcquire(60, TimeUnit.SECONDS)) throw new RuntimeException ("Unable to acquire lock"); String cm = configModifier != null ? configModifier : ""; Metadata md = metadatas.get(cm); try { if (md == null) { StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); String propFile; String dbPropertiesPrefix = ""; String metadataPrefix = ""; String hibCfg = null; if (cm.endsWith(".cfg.xml")) { hibCfg = cm; } else if (configModifier != null) { String[] ss = configModifier.split(":"); if (ss.length > 0) dbPropertiesPrefix = ss[0] + ":"; if (ss.length > 1) metadataPrefix = ss[1] + ":"; hibCfg = System.getProperty("HIBERNATE_CFG","/" + dbPropertiesPrefix + "hibernate.cfg.xml"); if (getClass().getClassLoader().getResource(hibCfg) == null) hibCfg = null; } if (hibCfg == null) hibCfg = System.getProperty("HIBERNATE_CFG","/hibernate.cfg.xml"); ssrb.configure(hibCfg); propFile = System.getProperty(dbPropertiesPrefix + "DB_PROPERTIES", "cfg/" + dbPropertiesPrefix + "db.properties"); Properties dbProps = loadProperties(propFile); if (dbProps != null) { for (Map.Entry entry : dbProps.entrySet()) { ssrb.applySetting((String) entry.getKey(), entry.getValue()); } } // if DBInstantiator has put db user name and/or password in Space, set Hibernate config accordingly Space sp = SpaceFactory.getSpace("tspace:dbconfig"); String user = (String) sp.inp(dbPropertiesPrefix +"connection.username"); String pass = (String) sp.inp(dbPropertiesPrefix +"connection.password"); if (user != null) ssrb.applySetting("hibernate.connection.username", user); if (pass != null) ssrb.applySetting("hibernate.connection.password", pass); MetadataSources mds = new MetadataSources(ssrb.build()); List<String> moduleConfigs = ModuleUtils.getModuleEntries(MODULES_CONFIG_PATH); for (String moduleConfig : moduleConfigs) { if (metadataPrefix.length() == 0 || moduleConfig.substring(MODULES_CONFIG_PATH.length()).startsWith(metadataPrefix)) { if ( (!metadataPrefix.contains(":") && moduleConfig.contains(":")) || (!moduleConfig.contains(":") && metadataPrefix.contains(":"))) continue; addMappings(mds, moduleConfig); } } md = mds.buildMetadata(); metadatas.put(cm, md); } } finally { mdSem.release(); } return md; } private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException { Element module = readMappingElements(moduleConfig); if (module != null) { for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) { Element mapping = (Element) l.next(); parseMapping(mds, mapping, moduleConfig); } } } private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException { final String resource = mapping.attributeValue("resource"); final String clazz = mapping.attributeValue("class"); if (resource != null) mds.addResource(resource); else if (clazz != null) mds.addAnnotatedClassName(clazz); else throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName); } }
package com.otus.alexeenko.l4; import com.sun.management.GarbageCollectionNotificationInfo; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; import java.lang.management.GarbageCollectorMXBean; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GCLogger { private static final Logger logger = Logger.getLogger("Log"); private static final Timer timer = new Timer(); private static final ReentrantLock locker = new ReentrantLock(); private static int young; private static int youngTime; private static int old; private static int oldTime; private static void initLog() throws Exception { System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tc %n%4$s: %5$s%6$s%n"); // pure log Path path = Paths.get("./logs"); //if directory exists? if (!Files.exists(path)) Files.createDirectories(path); // This block configure the logger with handler and formatter Handler fh = new FileHandler("./logs/Log.log", true); logger.addHandler(fh); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); logger.info("Start"); } private static void initGCMonitoring() { List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean gcbean : gcbeans) { NotificationEmitter emitter = (NotificationEmitter) gcbean; NotificationListener listener = (notification, handback) -> { if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) { GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData()); locker.lock(); try { if (isYoungGC(info.getGcName())) { young++; youngTime += info.getGcInfo().getDuration(); } else { old++; oldTime += info.getGcInfo().getDuration(); } } finally { locker.unlock(); } } }; emitter.addNotificationListener(listener, null, null); } } private static boolean isYoungGC(String name) { Pattern p = Pattern.compile("Scavenge|Young|ParNew|Copy"); Matcher m = p.matcher(name); return m.find(); } public static void run() throws Exception { initLog(); initGCMonitoring(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { locker.lock(); try { logger.info("\nNumber of calls Young GC - " + young + " duration - " + youngTime + " ms" + "\nNumber of calls Old GC - " + old + " duration - " + oldTime + " ms"); young = 0; youngTime = 0; old = 0; oldTime = 0; } finally { locker.unlock(); } } }, 60000, 60000); // one minute } }
// Sample plots using date / time formatting for axes // This file is part of PLplot. // PLplot is free software; you can redistribute it and/or modify // (at your option) any later version. // PLplot is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with PLplot; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package plplot.examples; import plplot.core.*; import java.util.*; class x29 { PLStream pls = new PLStream(); // main // Draws several plots which demonstrate the use of date / time formats // for the axis labels. // Time formatting is done using the system strftime routine. See the // documentation of this for full details of the available formats. // 1) Plotting temperature over a day (using hours / minutes) // 2) Plotting // Note: Times are stored as seconds since the epoch (usually // 1st Jan 1970). x29(String[] args) { // Parse command line arguments pls.parseopts(args, PLStream.PL_PARSE_FULL | PLStream.PL_PARSE_NOPROGRAM); // Initialize plplot pls.init(); plot1(); plot2(); plot3(); pls.end(); } // Plot a model diurnal cycle of temperature void plot1() { int i, npts; double xmin, xmax, ymin, ymax; double x[], y[]; // Data points every 10 minutes for 1 day npts = 145; x = new double[npts]; y = new double[npts]; xmin = 0; xmax = 60.0*60.0*24.0; // Number of seconds in a day ymin = 10.0; ymax = 20.0; for (i=0;i<npts;i++) { x[i] = xmax*((double) i/(double)npts); y[i] = 15.0 - 5.0*Math.cos( 2*Math.PI*((double) i / (double) npts)); } pls.adv(0); pls.vsta(); pls.wind(xmin, xmax, ymin, ymax); // Draw a box with ticks spaced every 3 hour in X and 1 degree C in Y. pls.col0(1); // Set time format to be hours:minutes pls.timefmt("%H:%M"); pls.box("bcnstd", 3.0*60*60, 3, "bcnstv", 1, 5); pls.col0(3); pls.lab("Time (hours:mins)", "Temperature (degC)", "#frPLplot Example 29 - Daily temperature"); pls.col0(4); pls.line(x, y); } // Plot the number of hours of daylight as a function of day for a year void plot2() { int j, npts; double xmin, xmax, ymin, ymax; double lat, p, d; double x[], y[]; // Latitude for London lat = 51.5; npts = 365; x = new double[npts]; y = new double[npts]; xmin = 0; xmax = npts*60.0*60.0*24.0; ymin = 0; ymax = 24; // Formula for hours of daylight from // "A Model Comparison for Daylength as a Function of Latitude and // Day of the Year", 1995, Ecological Modelling, 80, pp 87-95. for (j = 0; j < npts; j++) { x[j] = j*60.0*60.0*24.0; p = Math.asin(0.39795*Math.cos(0.2163108 + 2*Math.atan(0.9671396*Math.tan(0.00860*(j-186))))); d = 24.0 - (24.0/Math.PI)* Math.acos( (Math.sin(0.8333*Math.PI/180.0) + Math.sin(lat*Math.PI/180.0)*Math.sin(p)) / (Math.cos(lat*Math.PI/180.0)*Math.cos(p)) ); y[j] = d; } pls.col0(1); // Set time format to be abbreviated month name followed by day of month pls.timefmt("%b %d"); pls.env(xmin, xmax, ymin, ymax, 0, 40); pls.col0(3); pls.lab("Date", "Hours of daylight", "#frPLplot Example 29 - Hours of daylight at 51.5N"); pls.col0(4); pls.line(x, y); } void plot3() { int i, npts; double xmin, xmax, ymin, ymax; long tstart; double x[], y[]; TimeZone tz = TimeZone.getTimeZone("UTC"); Calendar cal = Calendar.getInstance(tz); cal.set(2005, 11, 1, 0, 0, 0); tstart = cal.getTimeInMillis()/1000; npts = 62; x = new double[npts]; y = new double[npts]; xmin = (double) tstart; xmax = xmin + npts*60.0*60.0*24.0; ymin = 0.0; ymax = 5.0; for (i = 0; i<npts; i++) { x[i] = xmin + i*60.0*60.0*24.0; y[i] = 1.0 + Math.sin( 2*Math.PI*( (double) i ) / 7.0 ) + Math.exp( ((double) Math.min(i,npts-i)) / 31.0); } pls.adv(0); pls.vsta(); pls.wind(xmin, xmax, ymin, ymax); pls.col0(1); // Set time format to be ISO 8601 standard YYYY-MM-HH. Note that this is // equivalent to %f for C99 compliant implementations of strftime. pls.timefmt("%Y-%m-%d"); // Draw a box with ticks spaced every 14 days in X and 1 hour in Y. pls.box("bcnstd", 14*24.0*60.0*60.0,14, "bcnstv", 1, 4); pls.col0(3); pls.lab("Date", "Hours of television watched", "#frPLplot Example 29 - Hours of television watched in Dec 2005 / Jan 2006"); pls.col0(4); pls.poin(x, y, 2); pls.line(x, y); } public static void main( String[] args ) { new x29( args ); } };
package org.jasig.portal; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.Element; import org.apache.xerces.dom.DocumentImpl; import org.apache.xerces.parsers.DOMParser; import java.io.StringWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Vector; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.jasig.portal.utils.DTDResolver; import org.jasig.portal.services.LogService; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.jasig.portal.utils.DocumentFactory; import org.jasig.portal.channels.CError; import org.jasig.portal.security.IPerson; import org.jasig.portal.security.ISecurityContext; import org.jasig.portal.utils.ICounterStore; import org.jasig.portal.utils.CounterStoreFactory; import org.jasig.portal.utils.ResourceLoader; /** * SQL implementation for the 2.x relational database model * @author George Lindholm * @version $Revision$ */ public class RDBMUserLayoutStore implements IUserLayoutStore { //This class is instantiated ONCE so NO class variables can be used to keep state between calls static int DEBUG = 0; protected static final String channelPrefix = "n"; protected static final String folderPrefix = "s"; protected IChannelRegistryStoreOld crsdb; protected ICounterStore csdb; /** * LayoutStructure * Encapsulate the layout structure */ protected final class LayoutStructure { private class StructureParameter { String name; String value; public StructureParameter(String name, String value) { this.name = name; this.value = value; } } int structId; int nextId; int childId; int chanId; String name; String type; boolean hidden; boolean unremovable; boolean immutable; ArrayList parameters; public LayoutStructure(int structId, int nextId,int childId,int chanId, String hidden, String unremovable, String immutable) { this.nextId = nextId; this.childId = childId; this.chanId = chanId; this.structId = structId; this.hidden = RDBMServices.dbFlag(hidden); this.immutable = RDBMServices.dbFlag(immutable); this.unremovable = RDBMServices.dbFlag(unremovable); if (DEBUG > 1) { System.err.println("New layout: id=" + structId + ", next=" + nextId + ", child=" + childId +", chan=" +chanId); } } public void addFolderData(String name, String type) { this.name = name; this.type = type; } public boolean isChannel () {return chanId != 0;} public void addParameter(String name, String value) { if (parameters == null) { parameters = new ArrayList(5); } parameters.add(new StructureParameter(name, value)); } public int getNextId () {return nextId;} public int getChildId () {return childId;} public int getChanId () {return chanId;} public Element getStructureDocument(DocumentImpl doc) throws Exception { Element structure = null; if (isChannel()) { structure = crsdb.getChannelXML(chanId, doc, channelPrefix + structId); if (structure == null) { // Can't find channel ChannelDefinition cd = new ChannelDefinition(chanId); cd.setTitle("Missing channel"); cd.setName("Missing channel"); structure = cd.getDocument(doc, channelPrefix + structId, "This channel no longer exists. You should remove it from your layout.", CError.CHANNEL_MISSING_EXCEPTION); } } else { structure = doc.createElement("folder"); doc.putIdentifier(folderPrefix + structId, structure); structure.setAttribute("ID", folderPrefix + structId); structure.setAttribute("name", name); structure.setAttribute("type", (type != null ? type : "regular")); } structure.setAttribute("hidden", (hidden ? "true" : "false")); structure.setAttribute("immutable", (immutable ? "true" : "false")); structure.setAttribute("unremovable", (unremovable ? "true" : "false")); if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { StructureParameter sp = (StructureParameter)parameters.get(i); if (!isChannel()) { // Folder structure.setAttribute(sp.name, sp.value); } else { // Channel NodeList nodeListParameters = structure.getElementsByTagName("parameter"); for (int j = 0; j < nodeListParameters.getLength(); j++) { Element parmElement = (Element)nodeListParameters.item(j); NamedNodeMap nm = parmElement.getAttributes(); String nodeName = nm.getNamedItem("name").getNodeValue(); if (nodeName.equals(sp.name)) { Node override = nm.getNamedItem("override"); if (override != null && override.getNodeValue().equals("yes")) { Node valueNode = nm.getNamedItem("value"); valueNode.setNodeValue(sp.value); } } } } } } return structure; } } public RDBMUserLayoutStore () throws Exception { crsdb = ChannelRegistryStoreFactoryOld.getChannelRegistryStoreOldImpl(); csdb = CounterStoreFactory.getCounterStoreImpl(); if (RDBMServices.supportsOuterJoins) { if (RDBMServices.joinQuery instanceof RDBMServices.JdbcDb) { RDBMServices.joinQuery.addQuery("layout", "{oj UP_LAYOUT_STRUCT ULS LEFT OUTER JOIN UP_LAYOUT_PARAM USP ON ULS.USER_ID = USP.USER_ID AND ULS.STRUCT_ID = USP.STRUCT_ID} WHERE"); RDBMServices.joinQuery.addQuery("ss_struct", "{oj UP_SS_STRUCT USS LEFT OUTER JOIN UP_SS_STRUCT_PAR USP ON USS.SS_ID=USP.SS_ID} WHERE"); RDBMServices.joinQuery.addQuery("ss_theme", "{oj UP_SS_THEME UTS LEFT OUTER JOIN UP_SS_THEME_PARM UTP ON UTS.SS_ID=UTP.SS_ID} WHERE"); } else if (RDBMServices.joinQuery instanceof RDBMServices.PostgreSQLDb) { RDBMServices.joinQuery.addQuery("layout", "UP_LAYOUT_STRUCT ULS LEFT OUTER JOIN UP_LAYOUT_PARAM USP ON ULS.USER_ID = USP.USER_ID AND ULS.STRUCT_ID = USP.STRUCT_ID WHERE"); RDBMServices.joinQuery.addQuery("ss_struct", "UP_SS_STRUCT USS LEFT OUTER JOIN UP_SS_STRUCT_PAR USP ON USS.SS_ID=USP.SS_ID WHERE"); RDBMServices.joinQuery.addQuery("ss_theme", "UP_SS_THEME UTS LEFT OUTER JOIN UP_SS_THEME_PARM UTP ON UTS.SS_ID=UTP.SS_ID WHERE"); } else if (RDBMServices.joinQuery instanceof RDBMServices.OracleDb) { RDBMServices.joinQuery.addQuery("layout", "UP_LAYOUT_STRUCT ULS, UP_LAYOUT_PARAM USP WHERE ULS.STRUCT_ID = USP.STRUCT_ID(+) AND ULS.USER_ID = USP.USER_ID AND"); RDBMServices.joinQuery.addQuery("ss_struct", "UP_SS_STRUCT USS, UP_SS_STRUCT_PAR USP WHERE USS.SS_ID=USP.SS_ID(+) AND"); RDBMServices.joinQuery.addQuery("ss_theme", "UP_SS_THEME UTS, UP_SS_THEME_PARM UTP WHERE UTS.SS_ID=UTP.SS_ID(+) AND"); } else { throw new Exception("Unknown database driver"); } } } /** * Registers a NEW structure stylesheet with the database. * @param tsd Stylesheet description object */ public Integer addStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception { Connection con = RDBMServices.getConnection(); try { // Set autocommit false for the connection RDBMServices.setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // we assume that this is a new stylesheet. int id = csdb.getIncrementIntegerId("UP_SS_STRUCT"); ssd.setId(id); String sQuery = "INSERT INTO UP_SS_STRUCT (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT) VALUES (" + id + ",'" + ssd.getStylesheetName() + "','" + ssd.getStylesheetURI() + "','" + ssd.getStylesheetDescriptionURI() + "','" + ssd.getStylesheetWordDescription() + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); // insert all stylesheet params for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // insert all folder attributes for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName) + "',2)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // insert all channel attributes for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // Commit the transaction RDBMServices.commit(con); return new Integer(id); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Registers a NEW theme stylesheet with the database. * @param tsd Stylesheet description object */ public Integer addThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception { Connection con = RDBMServices.getConnection(); try { // Set autocommit false for the connection RDBMServices.setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // we assume that this is a new stylesheet. int id = csdb.getIncrementIntegerId("UP_SS_THEME"); tsd.setId(id); String sQuery = "INSERT INTO UP_SS_THEME (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_URI,SAMPLE_ICON_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS) VALUES (" + id + ",'" + tsd.getStylesheetName() + "','" + tsd.getStylesheetURI() + "','" + tsd.getStylesheetDescriptionURI() + "','" + tsd.getStylesheetWordDescription() + "'," + tsd.getStructureStylesheetId() + ",'" + tsd.getSamplePictureURI() + "','" + tsd.getSampleIconURI() + "','" + tsd.getMimeType() + "','" + tsd.getDeviceType() + "','" + tsd.getSerializerName() + "','" + tsd.getCustomUserPreferencesManagerClass() + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); // insert all stylesheet params for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // insert all channel attributes for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id + ",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } // Commit the transaction RDBMServices.commit(con); return new Integer(id); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Update the theme stylesheet description. * @param stylesheetDescriptionURI * @param stylesheetURI * @param stylesheetId * @return true if update succeeded, otherwise false */ public boolean updateThemeStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI, int stylesheetId) { try { DOMParser parser = new DOMParser(); parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI))); Document stylesheetDescriptionXML = parser.getDocument(); String ssName = this.getRootElementTextValue(stylesheetDescriptionXML, "parentStructureStylesheet"); // should thrown an exception if (ssName == null) return false; // determine id of the parent structure stylesheet Integer ssId = getStructureStylesheetId(ssName); // stylesheet not found, should thrown an exception here if (ssId == null) return false; ThemeStylesheetDescription sssd = new ThemeStylesheetDescription(); sssd.setId(stylesheetId); sssd.setStructureStylesheetId(ssId.intValue()); String xmlStylesheetName = this.getName(stylesheetDescriptionXML); String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML); sssd.setStylesheetName(xmlStylesheetName); sssd.setStylesheetURI(stylesheetURI); sssd.setStylesheetDescriptionURI(stylesheetDescriptionURI); sssd.setStylesheetWordDescription(xmlStylesheetDescriptionText); sssd.setMimeType(this.getRootElementTextValue(stylesheetDescriptionXML, "mimeType")); LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting mimetype=\"" + sssd.getMimeType() + "\""); sssd.setSerializerName(this.getRootElementTextValue(stylesheetDescriptionXML, "serializer")); LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting serializerName=\"" + sssd.getSerializerName() + "\""); sssd.setCustomUserPreferencesManagerClass(this.getRootElementTextValue(stylesheetDescriptionXML, "userPreferencesModuleClass")); sssd.setSamplePictureURI(this.getRootElementTextValue(stylesheetDescriptionXML, "samplePictureURI")); sssd.setSampleIconURI(this.getRootElementTextValue(stylesheetDescriptionXML, "sampleIconURI")); sssd.setDeviceType(this.getRootElementTextValue(stylesheetDescriptionXML, "deviceType")); // populate parameter and attriute tables this.populateParameterTable(stylesheetDescriptionXML, sssd); this.populateChannelAttributeTable(stylesheetDescriptionXML, sssd); updateThemeStylesheetDescription(sssd); } catch (Exception e) { LogService.instance().log(LogService.DEBUG, e); return false; } return true; } /** * Update the structure stylesheet description * @param stylesheetDescriptionURI * @param stylesheetURI * @param stylesheetId * @return true if update succeeded, otherwise false */ public boolean updateStructureStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI, int stylesheetId) { try { DOMParser parser = new DOMParser(); parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI))); Document stylesheetDescriptionXML = parser.getDocument(); StructureStylesheetDescription fssd = new StructureStylesheetDescription(); String xmlStylesheetName = this.getName(stylesheetDescriptionXML); String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML); fssd.setId(stylesheetId); fssd.setStylesheetName(xmlStylesheetName); fssd.setStylesheetURI(stylesheetURI); fssd.setStylesheetDescriptionURI(stylesheetDescriptionURI); fssd.setStylesheetWordDescription(xmlStylesheetDescriptionText); // populate parameter and attriute tables this.populateParameterTable(stylesheetDescriptionXML, fssd); this.populateFolderAttributeTable(stylesheetDescriptionXML, fssd); this.populateChannelAttributeTable(stylesheetDescriptionXML, fssd); // now write out the database record updateStructureStylesheetDescription(fssd); } catch (Exception e) { LogService.instance().log(LogService.DEBUG, e); return false; } return true; } /** * Add a structure stylesheet description * @param stylesheetDescriptionURI * @param stylesheetURI * @return */ public Integer addStructureStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI) { // need to read in the description file to obtain information such as name, word description and media list try { DOMParser parser = new DOMParser(); parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI))); Document stylesheetDescriptionXML = parser.getDocument(); StructureStylesheetDescription fssd = new StructureStylesheetDescription(); String xmlStylesheetName = this.getName(stylesheetDescriptionXML); String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML); fssd.setStylesheetName(xmlStylesheetName); fssd.setStylesheetURI(stylesheetURI); fssd.setStylesheetDescriptionURI(stylesheetDescriptionURI); fssd.setStylesheetWordDescription(xmlStylesheetDescriptionText); // populate parameter and attriute tables this.populateParameterTable(stylesheetDescriptionXML, fssd); this.populateFolderAttributeTable(stylesheetDescriptionXML, fssd); this.populateChannelAttributeTable(stylesheetDescriptionXML, fssd); // now write out the database record // first the basic record //UserLayoutStoreFactory.getUserLayoutStoreImpl().addStructureStylesheetDescription(xmlStylesheetName, stylesheetURI, stylesheetDescriptionURI, xmlStylesheetDescriptionText); return addStructureStylesheetDescription(fssd); } catch (Exception e) { LogService.instance().log(LogService.DEBUG, e); } return null; } /** * Add theme stylesheet description * @param stylesheetDescriptionURI * @param stylesheetURI * @return */ public Integer addThemeStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI) { // need to read iN the description file to obtain information such as name, word description and mime type list try { DOMParser parser = new DOMParser(); parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI))); Document stylesheetDescriptionXML = parser.getDocument(); LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : stylesheet name = " + this.getName(stylesheetDescriptionXML)); LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : stylesheet description = " + this.getDescription(stylesheetDescriptionXML)); String ssName = this.getRootElementTextValue(stylesheetDescriptionXML, "parentStructureStylesheet"); // should thrown an exception if (ssName == null) return null; // determine id of the parent structure stylesheet Integer ssId = getStructureStylesheetId(ssName); // stylesheet not found, should thrown an exception here if (ssId == null) return null; ThemeStylesheetDescription sssd = new ThemeStylesheetDescription(); sssd.setStructureStylesheetId(ssId.intValue()); String xmlStylesheetName = this.getName(stylesheetDescriptionXML); String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML); sssd.setStylesheetName(xmlStylesheetName); sssd.setStylesheetURI(stylesheetURI); sssd.setStylesheetDescriptionURI(stylesheetDescriptionURI); sssd.setStylesheetWordDescription(xmlStylesheetDescriptionText); sssd.setMimeType(this.getRootElementTextValue(stylesheetDescriptionXML, "mimeType")); LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting mimetype=\"" + sssd.getMimeType() + "\""); sssd.setSerializerName(this.getRootElementTextValue(stylesheetDescriptionXML, "serializer")); LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting serializerName=\"" + sssd.getSerializerName() + "\""); sssd.setCustomUserPreferencesManagerClass(this.getRootElementTextValue(stylesheetDescriptionXML, "userPreferencesModuleClass")); sssd.setSamplePictureURI(this.getRootElementTextValue(stylesheetDescriptionXML, "samplePictureURI")); sssd.setSampleIconURI(this.getRootElementTextValue(stylesheetDescriptionXML, "sampleIconURI")); sssd.setDeviceType(this.getRootElementTextValue(stylesheetDescriptionXML, "deviceType")); // populate parameter and attriute tables this.populateParameterTable(stylesheetDescriptionXML, sssd); this.populateChannelAttributeTable(stylesheetDescriptionXML, sssd); return addThemeStylesheetDescription(sssd); } catch (Exception e) { LogService.instance().log(LogService.DEBUG, e); } return null; } /** * Add a user profile * @param person * @param profile * @return userProfile * @exception Exception */ public UserProfile addUserProfile (IPerson person, UserProfile profile) throws Exception { int userId = person.getID(); // generate an id for this profile Connection con = RDBMServices.getConnection(); try { int id = csdb.getIncrementIntegerId("UP_USER_PROFILE"); profile.setProfileId(id); Statement stmt = con.createStatement(); try { String sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES (" + userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId() + "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addUserProfile(): " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return profile; } /** * Checks if a channel has been approved * @param approved Date * @return boolean Channel is approved */ protected static boolean channelApproved(java.sql.Timestamp approvedDate) { java.sql.Timestamp rightNow = new java.sql.Timestamp(System.currentTimeMillis()); return (approvedDate != null && rightNow.after(approvedDate)); } /** * Create a layout * @param doc * @param stmt * @param root * @param userId * @param profileId * @param layoutId * @param structId * @param ap * @exception java.sql.SQLException */ protected final void createLayout (HashMap layoutStructure, DocumentImpl doc, Element root, int structId) throws java.sql.SQLException, Exception { while (structId != 0) { if (DEBUG>1) { System.err.println("CreateLayout(" + structId + ")"); } LayoutStructure ls = (LayoutStructure) layoutStructure.get(new Integer(structId)); Element structure = ls.getStructureDocument(doc); root.appendChild(structure); if (!ls.isChannel()) { // Folder createLayout(layoutStructure, doc, structure, ls.getChildId()); } structId = ls.getNextId(); } } /** * convert true/false into Y/N for database * @param value to check * @result boolean */ protected static final boolean xmlBool (String value) { return (value != null && value.equals("true") ? true : false); } public void deleteUserProfile(IPerson person, int profileId) throws Exception { int userId = person.getID(); deleteUserProfile(userId,profileId); } private void deleteUserProfile(int userId, int profileId) throws Exception { Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery); stmt.executeUpdate(sQuery); // remove profile mappings sQuery= "DELETE FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery); stmt.executeUpdate(sQuery); // remove parameter information sQuery= "DELETE FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery); stmt.executeUpdate(sQuery); sQuery= "DELETE FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Dump a document tree structure on stdout * @param node * @param indent */ public static final void dumpDoc (Node node, String indent) { if (node == null) { return; } if (node instanceof Element) { System.err.print(indent + "element: tag=" + ((Element)node).getTagName() + " "); } else if (node instanceof Document) { System.err.print("document:"); } else { System.err.print(indent + "node:"); } System.err.println("name=" + node.getNodeName() + " value=" + node.getNodeValue()); NamedNodeMap nm = node.getAttributes(); if (nm != null) { for (int i = 0; i < nm.getLength(); i++) { System.err.println(indent + " " + nm.item(i).getNodeName() + ": '" + nm.item(i).getNodeValue() + "'"); } System.err.println(indent + " } if (node.hasChildNodes()) { dumpDoc(node.getFirstChild(), indent + " "); } dumpDoc(node.getNextSibling(), indent); } /** * * CoreStyleSheet * */ public Hashtable getMimeTypeList () throws Exception { Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT A.MIME_TYPE, A.MIME_TYPE_DESCRIPTION FROM UP_MIME_TYPE A, UP_SS_MAP B WHERE B.MIME_TYPE=A.MIME_TYPE"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getMimeTypeList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { Hashtable list = new Hashtable(); while (rs.next()) { list.put(rs.getString("MIME_TYPE"), rs.getString("MIME_TYPE_DESCRIPTION")); } return list; } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Return the next available channel structure id for a user * @parameter userId * @result */ public String generateNewChannelSubscribeId (IPerson person) throws Exception { return getNextStructId(person, channelPrefix); } /** * Return the next available folder structure id for a user * @param person * @return * @exception Exception */ public String generateNewFolderId (IPerson person) throws Exception { return getNextStructId(person, folderPrefix); } /** * Return the next available structure id for a user * @param person * @param prefix * @return next free structure ID * @exception Exception */ protected String getNextStructId (IPerson person, String prefix) throws Exception { int userId = person.getID(); Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId; for (int i = 0; i < 25; i++) { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); int currentStructId; try { rs.next(); currentStructId = rs.getInt(1); } finally { rs.close(); } int nextStructId = currentStructId + 1; try { String sUpdate = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + userId + " AND NEXT_STRUCT_ID=" + currentStructId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sUpdate); stmt.executeUpdate(sUpdate); return prefix + nextStructId; } catch (SQLException sqle) { // Assume a concurrent update. Try again after some random amount of milliseconds. Thread.sleep(java.lang.Math.round(java.lang.Math.random()* 3 * 1000)); // Retry in up to 3 seconds } } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } throw new SQLException("Unable to generate a new structure id for user " + userId); } /** * Return the Structure ID tag * @param structId * @param chanId * @return ID tag */ protected String getStructId(int structId, int chanId) { if (chanId == 0) { return folderPrefix + structId; } else { return channelPrefix + structId; } } /** * Obtain structure stylesheet description object for a given structure stylesheet id * @para id id of the structure stylesheet * @return structure stylesheet description */ public StructureStylesheetDescription getStructureStylesheetDescription (int stylesheetId) throws Exception { StructureStylesheetDescription ssd = null; Connection con = RDBMServices.getConnection(); Statement stmt = con.createStatement(); try { int dbOffset = 0; String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT"; if (RDBMServices.supportsOuterJoins) { sQuery += ",TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM " + RDBMServices.joinQuery.getQuery("ss_struct"); dbOffset = 4; } else { sQuery += " FROM UP_SS_STRUCT USS WHERE"; } sQuery += " USS.SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { ssd = new StructureStylesheetDescription(); ssd.setId(stylesheetId); ssd.setStylesheetName(rs.getString(1)); ssd.setStylesheetURI(rs.getString(2)); ssd.setStylesheetDescriptionURI(rs.getString(3)); ssd.setStylesheetWordDescription(rs.getString(4)); } if (!RDBMServices.supportsOuterJoins) { rs.close(); // retrieve stylesheet params and attributes sQuery = "SELECT TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery); rs = stmt.executeQuery(sQuery); } while (true) { if (!RDBMServices.supportsOuterJoins && !rs.next()) { break; } int type = rs.getInt(dbOffset + 1); if (rs.wasNull()){ break; } if (type == 1) { // param ssd.addStylesheetParameter(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4)); } else if (type == 2) { // folder attribute ssd.addFolderAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4)); } else if (type == 3) { // channel attribute ssd.addChannelAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4)); } else { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + rs.getInt(dbOffset + 1) + ")."); } if (RDBMServices.supportsOuterJoins && !rs.next()) { break; } } } finally { rs.close(); } } finally { stmt.close(); RDBMServices.releaseConnection(con); } return ssd; } /** * Obtain ID for known structure stylesheet name * @param ssName name of the structure stylesheet * @return id or null if no stylesheet matches the name given. */ public Integer getStructureStylesheetId (String ssName) throws Exception { Connection con = RDBMServices.getConnection(); try { RDBMServices.setAutoCommit(con, false); Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_SS_STRUCT WHERE SS_NAME='" + ssName + "'"; ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { int id = rs.getInt("SS_ID"); if (rs.wasNull()) { id = 0; } return new Integer(id); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return null; } /** * Obtain a list of structure stylesheet descriptions that have stylesheets for a given * mime type. * @param mimeType * @return a mapping from stylesheet names to structure stylesheet description objects */ public Hashtable getStructureStylesheetList (String mimeType) throws Exception { Connection con = RDBMServices.getConnection(); Hashtable list = new Hashtable(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT A.SS_ID FROM UP_SS_STRUCT A, UP_SS_THEME B WHERE B.MIME_TYPE='" + mimeType + "' AND B.STRUCT_SS_ID=A.SS_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheeInfotList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { StructureStylesheetDescription ssd = getStructureStylesheetDescription(rs.getInt("SS_ID")); if (ssd != null) list.put(new Integer(ssd.getId()), ssd); } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return list; } /** * Obtain a list of strcture stylesheet descriptions registered on the system * @return a <code>Hashtable</code> mapping stylesheet id (<code>Integer</code> objects) to {@link StructureStylesheetDescription} objects * @exception Exception */ public Hashtable getStructureStylesheetList() throws Exception { Connection con = RDBMServices.getConnection(); Hashtable list = new Hashtable(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_SS_STRUCT"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheeList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { StructureStylesheetDescription ssd = getStructureStylesheetDescription(rs.getInt("SS_ID")); if (ssd != null) list.put(new Integer(ssd.getId()), ssd); } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return list; } public StructureStylesheetUserPreferences getStructureStylesheetUserPreferences (IPerson person, int profileId, int stylesheetId) throws Exception { int userId = person.getID(); StructureStylesheetUserPreferences ssup; Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { // get stylesheet description StructureStylesheetDescription ssd = getStructureStylesheetDescription(stylesheetId); // get user defined defaults String subSelectString = "SELECT LAYOUT_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + subSelectString); int layoutId; ResultSet rs = stmt.executeQuery(subSelectString); try { rs.next(); layoutId = rs.getInt(1); if (rs.wasNull()) { layoutId = 0; } } finally { rs.close(); } if (layoutId == 0) { // First time, grab the default layout for this user String sQuery = "SELECT USER_DFLT_USR_ID FROM UP_USER WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery); rs = stmt.executeQuery(sQuery); try { rs.next(); userId = rs.getInt(1); } finally { rs.close(); } } String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { // stylesheet param ssd.setStylesheetParameterDefaultValue(rs.getString(1), rs.getString(2)); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\""); } } finally { rs.close(); } ssup = new StructureStylesheetUserPreferences(); ssup.setStylesheetId(stylesheetId); // fill stylesheet description with defaults for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); ssup.putParameterValue(pName, ssd.getStylesheetParameterDefaultValue(pName)); } for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); ssup.addChannelAttribute(pName, ssd.getChannelAttributeDefaultValue(pName)); } for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); ssup.addFolderAttribute(pName, ssd.getFolderAttributeDefaultValue(pName)); } // get user preferences sQuery = "SELECT PARAM_NAME, PARAM_VAL, PARAM_TYPE, ULS.STRUCT_ID, CHAN_ID FROM UP_SS_USER_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int param_type = rs.getInt(3); int structId = rs.getInt(4); if (rs.wasNull()) { structId = 0; } int chanId = rs.getInt(5); if (rs.wasNull()) { chanId = 0; } if (param_type == 1) { // stylesheet param LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_SS_USER_ATTS is corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString(1) + "\", param_type=" + Integer.toString(param_type)); } else if (param_type == 2) { // folder attribute ssup.setFolderAttributeValue(getStructId(structId,chanId), rs.getString(1), rs.getString(2)); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\""); } else if (param_type == 3) { // channel attribute ssup.setChannelAttributeValue(getStructId(structId,chanId), rs.getString(1), rs.getString(2)); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read channel attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\""); } else { // unknown param type LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString(1) + "\", param_type=" + Integer.toString(param_type)); } } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return ssup; } /** * Obtain theme stylesheet description object for a given theme stylesheet id * @para id id of the theme stylesheet * @return theme stylesheet description */ public ThemeStylesheetDescription getThemeStylesheetDescription (int stylesheetId) throws Exception { ThemeStylesheetDescription tsd = null; Connection con = RDBMServices.getConnection(); Statement stmt = con.createStatement(); try { int dbOffset = 0; String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_ICON_URI,SAMPLE_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS"; if (RDBMServices.supportsOuterJoins) { sQuery += ",TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM " + RDBMServices.joinQuery.getQuery("ss_theme"); dbOffset = 11; } else { sQuery += " FROM UP_SS_THEME UTS WHERE"; } sQuery += " UTS.SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { tsd = new ThemeStylesheetDescription(); tsd.setId(stylesheetId); tsd.setStylesheetName(rs.getString(1)); tsd.setStylesheetURI(rs.getString(2)); tsd.setStylesheetDescriptionURI(rs.getString(3)); tsd.setStylesheetWordDescription(rs.getString(4)); int ssId = rs.getInt(5); if (rs.wasNull()) { ssId = 0; } tsd.setStructureStylesheetId(ssId); tsd.setSampleIconURI(rs.getString(6)); tsd.setSamplePictureURI(rs.getString(7)); tsd.setMimeType(rs.getString(8)); tsd.setDeviceType(rs.getString(9)); tsd.setSerializerName(rs.getString(10)); tsd.setCustomUserPreferencesManagerClass(rs.getString(11)); } if (!RDBMServices.supportsOuterJoins) { rs.close(); // retrieve stylesheet params and attributes sQuery = "SELECT TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery); rs = stmt.executeQuery(sQuery); } while (true) { if (!RDBMServices.supportsOuterJoins && !rs.next()) { break; } int type = rs.getInt(dbOffset + 1); if (rs.wasNull()) { break; } if (type == 1) { // param tsd.addStylesheetParameter(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4)); } else if (type == 3) { // channel attribute tsd.addChannelAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4)); } else if (type == 2) { // folder attributes are not allowed here LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! Corrupted DB entry. (stylesheetId=" + stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + type + ")."); } else { LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + type + ")."); } if (RDBMServices.supportsOuterJoins && !rs.next()) { break; } } } finally { rs.close(); } } finally { stmt.close(); RDBMServices.releaseConnection(con); } return tsd; } /** * Obtain ID for known theme stylesheet name * @param ssName name of the theme stylesheet * @return id or null if no theme matches the name given. */ public Integer getThemeStylesheetId (String tsName) throws Exception { Integer id = null; Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE SS_NAME='" + tsName + "'"; ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { id = new Integer(rs.getInt("SS_ID")); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return id; } /** * Obtain a list of theme stylesheet descriptions for a given structure stylesheet * @param structureStylesheetName * @return a map of stylesheet names to theme stylesheet description objects * @exception Exception */ public Hashtable getThemeStylesheetList (int structureStylesheetId) throws Exception { Connection con = RDBMServices.getConnection(); Hashtable list = new Hashtable(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE STRUCT_SS_ID=" + structureStylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { ThemeStylesheetDescription tsd = getThemeStylesheetDescription(rs.getInt("SS_ID")); if (tsd != null) list.put(new Integer(tsd.getId()), tsd); } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return list; } /** * Obtain a list of theme stylesheet descriptions registered on the system * @return a <code>Hashtable</code> mapping stylesheet id (<code>Integer</code> objects) to {@link ThemeStylesheetDescription} objects * @exception Exception */ public Hashtable getThemeStylesheetList() throws Exception { Connection con = RDBMServices.getConnection(); Hashtable list = new Hashtable(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT SS_ID FROM UP_SS_THEME"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetList() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { ThemeStylesheetDescription tsd = getThemeStylesheetDescription(rs.getInt("SS_ID")); if (tsd != null) list.put(new Integer(tsd.getId()), tsd); } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return list; } public ThemeStylesheetUserPreferences getThemeStylesheetUserPreferences (IPerson person, int profileId, int stylesheetId) throws Exception { int userId = person.getID(); ThemeStylesheetUserPreferences tsup; Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { // get stylesheet description ThemeStylesheetDescription tsd = getThemeStylesheetDescription(stylesheetId); // get user defined defaults String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { // stylesheet param tsd.setStylesheetParameterDefaultValue(rs.getString(1), rs.getString(2)); // LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\""); } } finally { rs.close(); } tsup = new ThemeStylesheetUserPreferences(); tsup.setStylesheetId(stylesheetId); // fill stylesheet description with defaults for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); tsup.putParameterValue(pName, tsd.getStylesheetParameterDefaultValue(pName)); } for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); tsup.addChannelAttribute(pName, tsd.getChannelAttributeDefaultValue(pName)); } // get user preferences sQuery = "SELECT PARAM_TYPE, PARAM_NAME, PARAM_VAL, ULS.STRUCT_ID, CHAN_ID FROM UP_SS_USER_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery); rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int param_type = rs.getInt(1); if (rs.wasNull()) { param_type = 0; } int structId = rs.getInt(4); if (rs.wasNull()) { structId = 0; } int chanId = rs.getInt(5); if (rs.wasNull()) { chanId = 0; } if (param_type == 1) { // stylesheet param LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_SS_USER_ATTS is corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type)); } else if (param_type == 2) { // folder attribute LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : folder attribute specified for the theme stylesheet! UP_SS_USER_ATTS corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type)); } else if (param_type == 3) { // channel attribute tsup.setChannelAttributeValue(getStructId(structId,chanId), rs.getString(2), rs.getString(3)); //LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\""); } else { // unknown param type LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId=" + Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId) + ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type)); } } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return tsup; } // private helper modules that retreive information from the DOM structure of the description files private String getName (Document descr) { NodeList names = descr.getElementsByTagName("name"); Node name = null; for (int i = names.getLength() - 1; i >= 0; i name = names.item(i); if (name.getParentNode().getLocalName().equals("stylesheetdescription")) break; else name = null; } if (name != null) { return this.getTextChildNodeValue(name); } else { LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getName() : no \"name\" element was found under the \"stylesheetdescription\" node!"); return null; } } private String getRootElementTextValue (Document descr, String elementName) { NodeList names = descr.getElementsByTagName(elementName); Node name = null; for (int i = names.getLength() - 1; i >= 0; i name = names.item(i); if (name.getParentNode().getLocalName().equals("stylesheetdescription")) break; else name = null; } if (name != null) { return this.getTextChildNodeValue(name); } else { LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getRootElementTextValue() : no \"" + elementName + "\" element was found under the \"stylesheetdescription\" node!"); return null; } } private String getDescription (Document descr) { NodeList descriptions = descr.getElementsByTagName("description"); Node description = null; for (int i = descriptions.getLength() - 1; i >= 0; i description = descriptions.item(i); if (description.getParentNode().getLocalName().equals("stylesheetdescription")) break; else description = null; } if (description != null) { return this.getTextChildNodeValue(description); } else { LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getName() : no \"description\" element was found under the \"stylesheetdescription\" node!"); return null; } } private void populateParameterTable (Document descr, CoreStylesheetDescription csd) { NodeList parametersNodes = descr.getElementsByTagName("parameters"); Node parametersNode = null; for (int i = parametersNodes.getLength() - 1; i >= 0; i parametersNode = parametersNodes.item(i); if (parametersNode.getParentNode().getLocalName().equals("stylesheetdescription")) break; else parametersNode = null; } if (parametersNode != null) { NodeList children = parametersNode.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("parameter")) { Element parameter = (Element)children.item(i); // process a <parameter> node String name = parameter.getAttribute("name"); String description = null; String defaultvalue = null; NodeList pchildren = parameter.getChildNodes(); for (int j = pchildren.getLength() - 1; j >= 0; j Node pchild = pchildren.item(j); if (pchild.getNodeType() == Node.ELEMENT_NODE) { if (pchild.getLocalName().equals("defaultvalue")) { defaultvalue = this.getTextChildNodeValue(pchild); } else if (pchild.getLocalName().equals("description")) { description = this.getTextChildNodeValue(pchild); } } } LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateParameterTable() : adding a stylesheet parameter : (\"" + name + "\",\"" + defaultvalue + "\",\"" + description + "\")"); csd.addStylesheetParameter(name, defaultvalue, description); } } } } private void populateFolderAttributeTable (Document descr, StructureStylesheetDescription cxsd) { NodeList parametersNodes = descr.getElementsByTagName("parameters"); NodeList folderattributesNodes = descr.getElementsByTagName("folderattributes"); Node folderattributesNode = null; for (int i = folderattributesNodes.getLength() - 1; i >= 0; i folderattributesNode = folderattributesNodes.item(i); if (folderattributesNode.getParentNode().getLocalName().equals("stylesheetdescription")) break; else folderattributesNode = null; } if (folderattributesNode != null) { NodeList children = folderattributesNode.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("attribute")) { Element attribute = (Element)children.item(i); // process a <attribute> node String name = attribute.getAttribute("name"); String description = null; String defaultvalue = null; NodeList pchildren = attribute.getChildNodes(); for (int j = pchildren.getLength() - 1; j >= 0; j Node pchild = pchildren.item(j); if (pchild.getNodeType() == Node.ELEMENT_NODE) { if (pchild.getLocalName().equals("defaultvalue")) { defaultvalue = this.getTextChildNodeValue(pchild); } else if (pchild.getLocalName().equals("description")) { description = this.getTextChildNodeValue(pchild); } } } LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateFolderAttributeTable() : adding a stylesheet folder attribute : (\"" + name + "\",\"" + defaultvalue + "\",\"" + description + "\")"); cxsd.addFolderAttribute(name, defaultvalue, description); } } } } private void populateChannelAttributeTable (Document descr, CoreXSLTStylesheetDescription cxsd) { NodeList channelattributesNodes = descr.getElementsByTagName("channelattributes"); Node channelattributesNode = null; for (int i = channelattributesNodes.getLength() - 1; i >= 0; i channelattributesNode = channelattributesNodes.item(i); if (channelattributesNode.getParentNode().getLocalName().equals("stylesheetdescription")) break; else channelattributesNode = null; } if (channelattributesNode != null) { NodeList children = channelattributesNode.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("attribute")) { Element attribute = (Element)children.item(i); // process a <attribute> node String name = attribute.getAttribute("name"); String description = null; String defaultvalue = null; NodeList pchildren = attribute.getChildNodes(); for (int j = pchildren.getLength() - 1; j >= 0; j Node pchild = pchildren.item(j); if (pchild.getNodeType() == Node.ELEMENT_NODE) { if (pchild.getLocalName().equals("defaultvalue")) { defaultvalue = this.getTextChildNodeValue(pchild); } else if (pchild.getLocalName().equals("description")) { description = this.getTextChildNodeValue(pchild); } } } LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateChannelAttributeTable() : adding a stylesheet channel attribute : (\"" + name + "\",\"" + defaultvalue + "\",\"" + description + "\")"); cxsd.addChannelAttribute(name, defaultvalue, description); } } } } private Vector getVectorOfSimpleTextElementValues (Document descr, String elementName) { Vector v = new Vector(); // find "stylesheetdescription" node, take the first one Element stylesheetdescriptionElement = (Element)(descr.getElementsByTagName("stylesheetdescription")).item(0); if (stylesheetdescriptionElement == null) { LogService.instance().log(LogService.ERROR, "Could not obtain <stylesheetdescription> element"); return null; } NodeList elements = stylesheetdescriptionElement.getElementsByTagName(elementName); for (int i = elements.getLength() - 1; i >= 0; i v.add(this.getTextChildNodeValue(elements.item(i))); // LogService.instance().log(LogService.DEBUG,"adding "+this.getTextChildNodeValue(elements.item(i))+" to the \""+elementName+"\" vector."); } return v; } private String getTextChildNodeValue (Node node) { if (node == null) return null; NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i Node child = children.item(i); if (child.getNodeType() == Node.TEXT_NODE) return child.getNodeValue(); } return null; } /** * UserPreferences */ private int getUserBrowserMapping (IPerson person, String userAgent) throws Exception { int userId = person.getID(); int profileId = 0; Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT PROFILE_ID, USER_ID FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND USER_AGENT='" + userAgent + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserBrowserMapping(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { profileId = rs.getInt("PROFILE_ID"); if (rs.wasNull()) { profileId = 0; } } else { return 0; } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return profileId; } public Document getUserLayout (IPerson person, UserProfile profile) throws Exception { int userId = person.getID(); int realUserId = userId; ResultSet rs; Connection con = RDBMServices.getConnection(); RDBMServices.setAutoCommit(con, false); // May speed things up, can't hurt try { DocumentImpl doc = new DocumentImpl(); Element root = doc.createElement("layout"); Statement stmt = con.createStatement(); try { long startTime = System.currentTimeMillis(); // eventually, we need to fix template layout implementations so you can just do this: // int layoutId=profile.getLayoutId(); // but for now: String subSelectString = "SELECT LAYOUT_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profile.getProfileId(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + subSelectString); int layoutId; rs = stmt.executeQuery(subSelectString); try { rs.next(); layoutId = rs.getInt(1); if (rs.wasNull()) { layoutId = 0; } } finally { rs.close(); } if (layoutId == 0) { // First time, grab the default layout for this user String sQuery = "SELECT USER_DFLT_USR_ID, USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery); rs = stmt.executeQuery(sQuery); try { rs.next(); userId = rs.getInt(1); layoutId = rs.getInt(2); } finally { rs.close(); } // Make sure the next struct id is set in case the user adds a channel sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery); int nextStructId; rs = stmt.executeQuery(sQuery); try { rs.next(); nextStructId = rs.getInt(1); } finally { rs.close(); } sQuery = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + realUserId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery); stmt.executeUpdate(sQuery); /* insert row(s) into up_ss_user_atts */ sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE USER_ID=" + realUserId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery); stmt.executeUpdate(sQuery); String Insert = "INSERT INTO UP_SS_USER_ATTS (USER_ID, PROFILE_ID, SS_ID, SS_TYPE, STRUCT_ID, PARAM_NAME, PARAM_TYPE, PARAM_VAL) "+ " SELECT "+realUserId+", USUA.PROFILE_ID, USUA.SS_ID, USUA.SS_TYPE, USUA.STRUCT_ID, USUA.PARAM_NAME, USUA.PARAM_TYPE, USUA.PARAM_VAL "+ " FROM UP_SS_USER_ATTS USUA WHERE USUA.USER_ID="+userId; LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + Insert); stmt.executeUpdate(Insert); RDBMServices.commit(con); // Make sure it appears in the store } int firstStructId = -1; String sQuery = "SELECT INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID=" + userId + " AND LAYOUT_ID = " + layoutId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery); rs = stmt.executeQuery(sQuery); try { rs.next(); firstStructId = rs.getInt(1); } finally { rs.close(); } String sql = "SELECT ULS.STRUCT_ID,ULS.NEXT_STRUCT_ID,ULS.CHLD_STRUCT_ID,ULS.CHAN_ID,ULS.NAME,ULS.TYPE,ULS.HIDDEN,"+ "ULS.UNREMOVABLE,ULS.IMMUTABLE"; if (RDBMServices.supportsOuterJoins) { sql += ",USP.STRUCT_PARM_NM,USP.STRUCT_PARM_VAL FROM " + RDBMServices.joinQuery.getQuery("layout"); } else { sql += " FROM UP_LAYOUT_STRUCT ULS WHERE "; } sql += " ULS.USER_ID=" + userId + " AND ULS.LAYOUT_ID=" + layoutId + " ORDER BY ULS.STRUCT_ID"; HashMap layoutStructure = new HashMap(); ArrayList chanIds = new ArrayList(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sql); StringBuffer structParms = new StringBuffer(); rs = stmt.executeQuery(sql); try { int lastStructId = 0; LayoutStructure ls = null; String sepChar = ""; if (rs.next()) { int structId = rs.getInt(1); if (rs.wasNull()) { structId = 0; } readLayout: while (true) { if (DEBUG > 1) System.err.println("Found layout structureID " + structId); int nextId = rs.getInt(2); if (rs.wasNull()) { nextId = 0; } int childId = rs.getInt(3); if (rs.wasNull()) { childId = 0; } int chanId = rs.getInt(4); if (rs.wasNull()) { chanId = 0; } ls = new LayoutStructure(structId, nextId, childId, chanId, rs.getString(7),rs.getString(8),rs.getString(9)); layoutStructure.put(new Integer(structId), ls); lastStructId = structId; if (!ls.isChannel()) { ls.addFolderData(rs.getString(5), rs.getString(6)); } else { chanIds.add(new Integer(chanId)); // For later } if (RDBMServices.supportsOuterJoins) { do { String name = rs.getString(10); String value = rs.getString(11); // Oracle JDBC requires us to do this for longs if (name != null) { // may not be there because of the join ls.addParameter(name, value); } if (!rs.next()) { break readLayout; } structId = rs.getInt(1); if (rs.wasNull()) { structId = 0; } } while (structId == lastStructId); } else { // Do second SELECT later on for structure parameters if (ls.isChannel()) { structParms.append(sepChar + ls.chanId); sepChar = ","; } if (rs.next()) { structId = rs.getInt(1); if (rs.wasNull()) { structId = 0; } } else { break readLayout; } } } // while } } finally { rs.close(); } // We have to retrieve the channel defition after the layout structure // since retrieving the channel data from the DB may interfere with the // layout structure ResultSet (in other words, Oracle is a pain to program for) if (chanIds.size() > 0) { RDBMServices.PreparedStatement pstmtChannel = crsdb.getChannelPstmt(con); try { RDBMServices.PreparedStatement pstmtChannelParm = crsdb.getChannelParmPstmt(con); try { // Pre-prime the channel pump for (int i = 0; i < chanIds.size(); i++) { int chanId = ((Integer) chanIds.get(i)).intValue(); crsdb.getChannel(chanId, true, pstmtChannel, pstmtChannelParm); if (DEBUG > 1) { System.err.println("Precached " + chanId); } } } finally { if (pstmtChannelParm != null) { pstmtChannelParm.close(); } } } finally { pstmtChannel.close(); } chanIds.clear(); } if (!RDBMServices.supportsOuterJoins) { // Pick up structure parameters sql = "SELECT STRUCT_ID, STRUCT_PARM_NM,STRUCT_PARM_VAL FROM UP_LAYOUT_PARAM WHERE USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId + " AND STRUCT_ID IN (" + structParms.toString() + ") ORDER BY STRUCT_ID"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sql); rs = stmt.executeQuery(sql); try { if (rs.next()) { int structId = rs.getInt(1); readParm: while(true) { LayoutStructure ls = (LayoutStructure)layoutStructure.get(new Integer(structId)); int lastStructId = structId; do { ls.addParameter(rs.getString(2), rs.getString(3)); if (!rs.next()) { break readParm; } } while ((structId = rs.getInt(1)) == lastStructId); } } } finally { rs.close(); } } if (layoutStructure.size() > 0) { // We have a layout to work with createLayout(layoutStructure, doc, root, firstStructId); layoutStructure.clear(); long stopTime = System.currentTimeMillis(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): Layout document for user " + userId + " took " + (stopTime - startTime) + " milliseconds to create"); doc.appendChild(root); if (DEBUG > 1) { System.err.println("--> created document"); dumpDoc(doc, ""); System.err.println("< } } } finally { stmt.close(); } return doc; } finally { RDBMServices.releaseConnection(con); } } public UserProfile getUserProfileById (IPerson person, int profileId) throws Exception { int userId = person.getID(); Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileById(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { int layoutId = rs.getInt(5); if (rs.wasNull()) { layoutId = 0; } int structSsId = rs.getInt(6); if (rs.wasNull()) { structSsId = 0; } int themeSsId = rs.getInt(7); if (rs.wasNull()) { themeSsId = 0; } return new UserProfile(profileId, rs.getString(3), rs.getString(4), layoutId, structSsId, themeSsId); } else { throw new Exception("Unable to find User Profile for user " + userId + " and profile " + profileId); } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } public Hashtable getUserProfileList (IPerson person) throws Exception { int userId = person.getID(); Hashtable pv = new Hashtable(); Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileList(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { int layoutId = rs.getInt(5); if (rs.wasNull()) { layoutId = 0; } int structSsId = rs.getInt(6); if (rs.wasNull()) { structSsId = 0; } int themeSsId = rs.getInt(7); if (rs.wasNull()) { themeSsId = 0; } UserProfile upl = new UserProfile(rs.getInt(2), rs.getString(3), rs.getString(4), layoutId, structSsId, themeSsId); pv.put(new Integer(upl.getProfileId()), upl); } } finally { rs.close(); } } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } return pv; } /** * Remove (with cleanup) a structure stylesheet channel attribute * @param stylesheetId id of the structure stylesheet * @param pName name of the attribute * @param con active database connection */ private void removeStructureChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } /** * Remove (with cleanup) a structure stylesheet folder attribute * @param stylesheetId id of the structure stylesheet * @param pName name of the attribute * @param con active database connection */ private void removeStructureFolderAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=2 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=2 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } public void removeStructureStylesheetDescription (int stylesheetId) throws Exception { Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { // detele all associated theme stylesheets String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE STRUCT_SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { removeThemeStylesheetDescription(rs.getInt("SS_ID")); } } finally { rs.close(); } sQuery = "DELETE FROM UP_SS_STRUCT WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // delete params sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); RDBMServices.commit(con); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Remove (with cleanup) a structure stylesheet param * @param stylesheetId id of the structure stylesheet * @param pName name of the parameter * @param con active database connection */ private void removeStructureStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } /** * Remove (with cleanup) a theme stylesheet channel attribute * @param stylesheetId id of the theme stylesheet * @param pName name of the attribute * @param con active database connection */ private void removeThemeChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeChannelAttribute() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=3 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } public void removeThemeStylesheetDescription (int stylesheetId) throws Exception { Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_SS_THEME WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // delete params sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // nuke all of the profiles that use it sQuery = "SELECT USER_ID,PROFILE_ID FROM UP_USER_PROFILE WHERE THEME_SS_ID="+stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureThemeStylesheetDescription() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { while (rs.next()) { deleteUserProfile(rs.getInt("USER_ID"),rs.getInt("PROFILE_ID")); } } finally { rs.close(); } // clean up user preferences - directly ( in case of loose params ) sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); RDBMServices.commit(con); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Remove (with cleanup) a theme stylesheet param * @param stylesheetId id of the theme stylesheet * @param pName name of the parameter * @param con active database connection */ private void removeThemeStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException { Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); // clean up user preference tables sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery); stmt.executeQuery(sQuery); } finally { stmt.close(); } } public void saveBookmarkXML (IPerson person, Document doc) throws Exception { int userId = person.getID(); StringWriter outString = new StringWriter(); XMLSerializer xsl = new XMLSerializer(outString, new OutputFormat(doc)); xsl.serialize(doc); Connection con = RDBMServices.getConnection(); try { Statement statem = con.createStatement(); try { String sQuery = "UPDATE UPC_BOOKMARKS SET BOOKMARK_XML = '" + outString.toString() + "' WHERE PORTAL_USER_ID = " + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveBookmarkXML(): " + sQuery); statem.executeUpdate(sQuery); } finally { statem.close(); } } finally { RDBMServices.releaseConnection(con); } } protected final int saveStructure (Node node, RDBMServices.PreparedStatement structStmt, RDBMServices.PreparedStatement parmStmt) throws java.sql.SQLException { if (node == null || node.getNodeName().equals("parameter")) { // No more or parameter node return 0; } Element structure = (Element)node; int saveStructId = Integer.parseInt(structure.getAttribute("ID").substring(1)); int nextStructId = 0; int childStructId = 0; String sQuery; if (DEBUG > 0) { LogService.instance().log(LogService.DEBUG, "-->" + node.getNodeName() + "@" + saveStructId); } if (node.hasChildNodes()) { childStructId = saveStructure(node.getFirstChild(), structStmt, parmStmt); } nextStructId = saveStructure(node.getNextSibling(), structStmt, parmStmt); structStmt.clearParameters(); structStmt.setInt(1, saveStructId); structStmt.setInt(2, nextStructId); structStmt.setInt(3, childStructId); String externalId = structure.getAttribute("external_id"); if (externalId != null && externalId.trim().length() > 0) { structStmt.setString(4, externalId.trim()); } else { structStmt.setNull(4, java.sql.Types.VARCHAR); } if (node.getNodeName().equals("channel")) { int chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue()); structStmt.setInt(5, chanId); structStmt.setNull(6,java.sql.Types.VARCHAR); } else { structStmt.setNull(5,java.sql.Types.NUMERIC); structStmt.setString(6, RDBMServices.sqlEscape(structure.getAttribute("name"))); } String structType = structure.getAttribute("type"); if (structType.length() > 0) { structStmt.setString(7, structType); } else { structStmt.setNull(7,java.sql.Types.VARCHAR); } structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden")))); structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable")))); structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable")))); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + structStmt); structStmt.executeUpdate(); NodeList parameters = node.getChildNodes(); if (parameters != null) { for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeName().equals("parameter")) { Element parmElement = (Element)parameters.item(i); NamedNodeMap nm = parmElement.getAttributes(); String nodeName = nm.getNamedItem("name").getNodeValue(); String nodeValue = nm.getNamedItem("value").getNodeValue(); Node override = nm.getNamedItem("override"); if (DEBUG > 0) { System.err.println(nodeName + "=" + nodeValue); } if (override == null || !override.getNodeValue().equals("yes")) { if (DEBUG > 0) System.err.println("Not saving channel defined parameter value " + nodeName); } else { parmStmt.clearParameters(); parmStmt.setInt(1, saveStructId); parmStmt.setString(2, nodeName); parmStmt.setString(3, nodeValue); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + parmStmt); parmStmt.executeUpdate(); } } } } return saveStructId; } public void setStructureStylesheetUserPreferences (IPerson person, int profileId, StructureStylesheetUserPreferences ssup) throws Exception { int userId = person.getID(); Connection con = RDBMServices.getConnection(); try { // Set autocommit false for the connection int stylesheetId = ssup.getStylesheetId(); RDBMServices.setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // write out params for (Enumeration e = ssup.getParameterValues().keys(); e.hasMoreElements();) { String pName = (String)e.nextElement(); // see if the parameter was already there String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_SS_USER_PARM SET PARAM_VAL='" + ssup.getParameterValue(pName) + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName + "'"; } else { // insert sQuery = "INSERT INTO UP_SS_USER_PARM (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",1,'" + pName + "','" + ssup.getParameterValue(pName) + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } // write out folder attributes for (Enumeration e = ssup.getFolders(); e.hasMoreElements();) { String folderId = (String)e.nextElement(); for (Enumeration attre = ssup.getFolderAttributeNames(); attre.hasMoreElements();) { String pName = (String)attre.nextElement(); String pValue = ssup.getDefinedFolderAttributeValue(folderId, pName); if (pValue != null) { // store user preferences String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + folderId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + folderId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=2"; } else { // insert sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",1,'" + folderId.substring(1) + "','" + pName + "',2,'" + pValue + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } } } // write out channel attributes for (Enumeration e = ssup.getChannels(); e.hasMoreElements();) { String channelId = (String)e.nextElement(); for (Enumeration attre = ssup.getChannelAttributeNames(); attre.hasMoreElements();) { String pName = (String)attre.nextElement(); String pValue = ssup.getDefinedChannelAttributeValue(channelId, pName); if (pValue != null) { // store user preferences String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; } else { // insert sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",1,'" + channelId.substring(1) + "','" + pName + "',3,'" + pValue + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } } } // Commit the transaction RDBMServices.commit(con); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } public void setThemeStylesheetUserPreferences (IPerson person, int profileId, ThemeStylesheetUserPreferences tsup) throws Exception { int userId = person.getID(); Connection con = RDBMServices.getConnection(); try { // Set autocommit false for the connection int stylesheetId = tsup.getStylesheetId(); RDBMServices.setAutoCommit(con, false); Statement stmt = con.createStatement(); try { // write out params for (Enumeration e = tsup.getParameterValues().keys(); e.hasMoreElements();) { String pName = (String)e.nextElement(); // see if the parameter was already there String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_SS_USER_PARM SET PARAM_VAL='" + tsup.getParameterValue(pName) + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName + "'"; } else { // insert sQuery = "INSERT INTO UP_SS_USER_PARM (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",2,'" + pName + "','" + tsup.getParameterValue(pName) + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } // write out channel attributes for (Enumeration e = tsup.getChannels(); e.hasMoreElements();) { String channelId = (String)e.nextElement(); for (Enumeration attre = tsup.getChannelAttributeNames(); attre.hasMoreElements();) { String pName = (String)attre.nextElement(); String pValue = tsup.getDefinedChannelAttributeValue(channelId, pName); if (pValue != null) { // store user preferences String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); if (rs.next()) { // update sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName + "' AND PARAM_TYPE=3"; } else { // insert sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES (" + userId + "," + profileId + "," + stylesheetId + ",2,'" + channelId.substring(1) + "','" + pName + "',3,'" + pValue + "')"; } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery); stmt.executeUpdate(sQuery); } } } // Commit the transaction RDBMServices.commit(con); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } public void setUserBrowserMapping (IPerson person, String userAgent, int profileId) throws Exception { int userId = person.getID(); Connection con = RDBMServices.getConnection(); try { // Set autocommit false for the connection RDBMServices.setAutoCommit(con, false); // remove the old mapping and add the new one Statement stmt = con.createStatement(); try { String sQuery = "DELETE FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND USER_AGENT='" + userAgent + "'"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery); stmt.executeUpdate(sQuery); sQuery = "INSERT INTO UP_USER_UA_MAP (USER_ID,USER_AGENT,PROFILE_ID) VALUES (" + userId + ",'" + userAgent + "'," + profileId + ")"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery); stmt.executeUpdate(sQuery); // Commit the transaction RDBMServices.commit(con); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Save the user layout * @param person * @param profileId * @param layoutXML * @throws Exception */ public void setUserLayout (IPerson person, UserProfile profile, Document layoutXML, boolean channelsAdded) throws Exception { int userId = person.getID(); int profileId=profile.getProfileId(); int layoutId=0; ResultSet rs; Connection con = RDBMServices.getConnection(); try { RDBMServices.setAutoCommit(con, false); // Need an atomic update here Statement stmt = con.createStatement(); try { long startTime = System.currentTimeMillis(); // eventually we want to be able to just get layoutId from the profile, but because of the // template user layouts we have to do this for now ... String query = "SELECT LAYOUT_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + query); rs = stmt.executeQuery(query); try { rs.next(); layoutId = rs.getInt(1); if (rs.wasNull()) { layoutId = 0; } } finally { rs.close(); } boolean firstLayout = false; if (layoutId == 0) { // First personal layout for this user/profile layoutId = 1; firstLayout = true; } String selectString = "USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId; String sSql = "DELETE FROM UP_LAYOUT_PARAM WHERE " + selectString; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql); stmt.executeUpdate(sSql); sSql = "DELETE FROM UP_LAYOUT_STRUCT WHERE " + selectString; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql); stmt.executeUpdate(sSql); if (DEBUG > 1) { System.err.println("--> saving document"); dumpDoc(layoutXML.getFirstChild().getFirstChild(), ""); System.err.println("< } RDBMServices.PreparedStatement structStmt = new RDBMServices.PreparedStatement(con, "INSERT INTO UP_LAYOUT_STRUCT " + "(USER_ID, LAYOUT_ID, STRUCT_ID, NEXT_STRUCT_ID, CHLD_STRUCT_ID,EXTERNAL_ID,CHAN_ID,NAME,TYPE,HIDDEN,IMMUTABLE,UNREMOVABLE) " + "VALUES ("+ userId + "," + layoutId + ",?,?,?,?,?,?,?,?,?,?)"); try { RDBMServices.PreparedStatement parmStmt = new RDBMServices.PreparedStatement(con, "INSERT INTO UP_LAYOUT_PARAM " + "(USER_ID, LAYOUT_ID, STRUCT_ID, STRUCT_PARM_NM, STRUCT_PARM_VAL) " + "VALUES ("+ userId + "," + layoutId + ",?,?,?)"); try { int firstStructId = saveStructure(layoutXML.getFirstChild().getFirstChild(), structStmt, parmStmt); sSql = "UPDATE UP_USER_LAYOUT SET INIT_STRUCT_ID=" + firstStructId + " WHERE " + selectString; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql); stmt.executeUpdate(sSql); // Update the last time the user saw the list of available channels if (channelsAdded) { sSql = "UPDATE UP_USER SET LST_CHAN_UPDT_DT=" + RDBMServices.sqlTimeStamp() + " WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql); stmt.executeUpdate(sSql); } if (firstLayout) { int defaultUserId; int defaultLayoutId; // Have to copy some of data over from the default user String sQuery = "SELECT USER_DFLT_USR_ID,USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + userId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery); rs = stmt.executeQuery(sQuery); try { rs.next(); defaultUserId = rs.getInt(1); defaultLayoutId = rs.getInt(2); } finally { rs.close(); } sQuery = "UPDATE UP_USER_PROFILE SET LAYOUT_ID=1 WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery); stmt.executeUpdate(sQuery); } long stopTime = System.currentTimeMillis(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): Layout document for user " + userId + " took " + (stopTime - startTime) + " milliseconds to save"); } finally { parmStmt.close(); } } finally { structStmt.close(); } } finally { stmt.close(); } RDBMServices.commit(con); } catch (Exception e) { RDBMServices.rollback(con); throw e; } finally { RDBMServices.releaseConnection(con); } } public void setUserProfile (IPerson person, UserProfile profile) throws Exception { int userId = person.getID(); Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { // this is ugly, but we have to know wether to do INSERT or UPDATE String sQuery = "SELECT USER_ID, PROFILE_NAME FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profile.getProfileId(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile() : " + sQuery); ResultSet rs = stmt.executeQuery(sQuery); try { if (rs.next()) { sQuery = "UPDATE UP_USER_PROFILE SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID=" + profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='" + profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId(); } else { sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES (" + userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId() + "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')"; } } finally { rs.close(); } LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile(): " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Updates an existing structure stylesheet description with a new one. Old stylesheet * description is found based on the Id provided in the parameter structure. * @param ssd new stylesheet description */ public void updateStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception { Connection con = RDBMServices.getConnection(); try { // Set autocommit false for the connection RDBMServices.setAutoCommit(con, false); Statement stmt = con.createStatement(); try { int stylesheetId = ssd.getId(); String sQuery = "UPDATE UP_SS_STRUCT SET SS_NAME='" + ssd.getStylesheetName() + "',SS_URI='" + ssd.getStylesheetURI() + "',SS_DESCRIPTION_URI='" + ssd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + ssd.getStylesheetWordDescription() + "' WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // first, see what was there before HashSet oparams = new HashSet(); HashSet ofattrs = new HashSet(); HashSet ocattrs = new HashSet(); sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); Statement stmtOld = con.createStatement(); ResultSet rsOld = stmtOld.executeQuery(sQuery); try { while (rsOld.next()) { int type = rsOld.getInt("TYPE"); if (type == 1) { // stylesheet param String pName = rsOld.getString("PARAM_NAME"); oparams.add(pName); if (!ssd.containsParameterName(pName)) { // delete param removeStructureStylesheetParam(stylesheetId, pName, con); } else { // update param sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getStylesheetParameterDefaultValue(pName) + "',PARAM_DESCRIPT='" + ssd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=1"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else if (type == 2) { // folder attribute String pName = rsOld.getString("PARAM_NAME"); ofattrs.add(pName); if (!ssd.containsFolderAttribute(pName)) { // delete folder attribute removeStructureFolderAttribute(stylesheetId, pName, con); } else { // update folder attribute sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getFolderAttributeDefaultValue(pName) + "',PARAM_DESCRIPT='" + ssd.getFolderAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "'AND TYPE=2"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else if (type == 3) { // channel attribute String pName = rsOld.getString("PARAM_NAME"); ocattrs.add(pName); if (!ssd.containsChannelAttribute(pName)) { // delete channel attribute removeStructureChannelAttribute(stylesheetId, pName, con); } else { // update channel attribute sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getChannelAttributeDefaultValue(pName) + "',PARAM_DESCRIPT='" + ssd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type + ")."); } } } finally { rsOld.close(); stmtOld.close(); } // look for new attributes/parameters // insert all stylesheet params for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!oparams.contains(pName)) { sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // insert all folder attributes for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!ofattrs.contains(pName)) { sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName) + "',2)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // insert all channel attributes for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!ocattrs.contains(pName)) { sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // Commit the transaction RDBMServices.commit(con); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } /** * Updates an existing structure stylesheet description with a new one. Old stylesheet * description is found based on the Id provided in the parameter structure. * @param ssd new stylesheet description */ public void updateThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception { Connection con = RDBMServices.getConnection(); try { // Set autocommit false for the connection RDBMServices.setAutoCommit(con, false); Statement stmt = con.createStatement(); try { int stylesheetId = tsd.getId(); String sQuery = "UPDATE UP_SS_THEME SET SS_NAME='" + tsd.getStylesheetName() + "',SS_URI='" + tsd.getStylesheetURI()+ "',SS_DESCRIPTION_URI='" + tsd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + tsd.getStylesheetWordDescription() + "',SAMPLE_ICON_URI='"+tsd.getSampleIconURI()+"',SAMPLE_URI='"+tsd.getSamplePictureURI()+"',MIME_TYPE='"+tsd.getMimeType()+"',DEVICE_TYPE='"+tsd.getDeviceType()+"',SERIALIZER_NAME='"+tsd.getSerializerName()+"',UP_MODULE_CLASS='"+tsd.getCustomUserPreferencesManagerClass()+"' WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); // first, see what was there before HashSet oparams = new HashSet(); HashSet ocattrs = new HashSet(); sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); Statement stmtOld = con.createStatement(); ResultSet rsOld = stmtOld.executeQuery(sQuery); try { while (rsOld.next()) { int type = rsOld.getInt("TYPE"); if (type == 1) { // stylesheet param String pName = rsOld.getString("PARAM_NAME"); oparams.add(pName); if (!tsd.containsParameterName(pName)) { // delete param removeThemeStylesheetParam(stylesheetId, pName, con); } else { // update param sQuery = "UPDATE UP_SS_THEME_PARM SET PARAM_DEFAULT_VAL='" + tsd.getStylesheetParameterDefaultValue(pName) + "',PARAM_DESCRIPT='" + tsd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=1"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else if (type == 2) { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! DB is corrupt. (stylesheetId=" + stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type + ")."); } else if (type == 3) { // channel attribute String pName = rsOld.getString("PARAM_NAME"); ocattrs.add(pName); if (!tsd.containsChannelAttribute(pName)) { // delete channel attribute removeThemeChannelAttribute(stylesheetId, pName, con); } else { // update channel attribute sQuery = "UPDATE UP_SS_THEME_PARM SET PARAM_DEFAULT_VAL='" + tsd.getChannelAttributeDefaultValue(pName) + "',PARAM_DESCRIPT='" + tsd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId + " AND PARAM_NAME='" + pName + "' AND TYPE=3"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery); stmt.executeUpdate(sQuery); } } else { LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId=" + stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type + ")."); } } } finally { rsOld.close(); stmtOld.close(); } // look for new attributes/parameters // insert all stylesheet params for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!oparams.contains(pName)) { sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName) + "',1)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // insert all channel attributes for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) { String pName = (String)e.nextElement(); if (!ocattrs.contains(pName)) { sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId + ",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName) + "',3)"; LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery); stmt.executeUpdate(sQuery); } } // Commit the transaction RDBMServices.commit(con); } catch (Exception e) { // Roll back the transaction RDBMServices.rollback(con); throw e; } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } public void updateUserProfile (IPerson person, UserProfile profile) throws Exception { int userId = person.getID(); Connection con = RDBMServices.getConnection(); try { Statement stmt = con.createStatement(); try { String sQuery = "UPDATE UP_USER_PROFILE SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID=" + profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='" + profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId(); LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateUserProfile() : " + sQuery); stmt.executeUpdate(sQuery); } finally { stmt.close(); } } finally { RDBMServices.releaseConnection(con); } } public void setSystemBrowserMapping (String userAgent, int profileId) throws Exception { this.setUserBrowserMapping(systemUser, userAgent, profileId); } private int getSystemBrowserMapping (String userAgent) throws Exception { return getUserBrowserMapping(systemUser, userAgent); } public UserProfile getUserProfile (IPerson person, String userAgent) throws Exception { int profileId = getUserBrowserMapping(person, userAgent); if (profileId == 0) return null; return this.getUserProfileById(person, profileId); } public UserProfile getSystemProfile (String userAgent) throws Exception { int profileId = getSystemBrowserMapping(userAgent); if (profileId == 0) return null; UserProfile up = this.getUserProfileById(systemUser, profileId); up.setSystemProfile(true); return up; } public UserProfile getSystemProfileById (int profileId) throws Exception { UserProfile up = this.getUserProfileById(systemUser, profileId); up.setSystemProfile(true); return up; } public Hashtable getSystemProfileList () throws Exception { Hashtable pl = this.getUserProfileList(systemUser); for (Enumeration e = pl.elements(); e.hasMoreElements();) { UserProfile up = (UserProfile)e.nextElement(); up.setSystemProfile(true); } return pl; } public void updateSystemProfile (UserProfile profile) throws Exception { this.updateUserProfile(systemUser, profile); } public UserProfile addSystemProfile (UserProfile profile) throws Exception { return addUserProfile(systemUser, profile); } public void deleteSystemProfile (int profileId) throws Exception { this.deleteUserProfile(systemUser, profileId); } private class SystemUser implements IPerson { public void setID(int sID) {} public int getID() {return 0;} public void setFullName(String sFullName) {} public String getFullName() {return "uPortal System Account";} public Object getAttribute (String key) {return null;} public void setAttribute (String key, Object value) {} public Enumeration getAttributes () {return null;} public Enumeration getAttributeNames () {return null;} public boolean isGuest() {return(false);} public ISecurityContext getSecurityContext() { return(null); } public void setSecurityContext(ISecurityContext context) {} } private IPerson systemUser = new SystemUser(); // We should be getting this from the uPortal public UserPreferences getUserPreferences (IPerson person, int profileId) throws Exception { UserPreferences up = null; UserProfile profile = this.getUserProfileById(person, profileId); if (profile != null) { up = getUserPreferences(person, profile); } return (up); } public UserPreferences getUserPreferences (IPerson person, UserProfile profile) throws Exception { int profileId = profile.getProfileId(); UserPreferences up = new UserPreferences(profile); up.setStructureStylesheetUserPreferences(getStructureStylesheetUserPreferences(person, profileId, profile.getStructureStylesheetId())); up.setThemeStylesheetUserPreferences(getThemeStylesheetUserPreferences(person, profileId, profile.getThemeStylesheetId())); return up; } public void putUserPreferences (IPerson person, UserPreferences up) throws Exception { // store profile UserProfile profile = up.getProfile(); this.updateUserProfile(person, profile); this.setStructureStylesheetUserPreferences(person, profile.getProfileId(), up.getStructureStylesheetUserPreferences()); this.setThemeStylesheetUserPreferences(person, profile.getProfileId(), up.getThemeStylesheetUserPreferences()); } }
package io.typebrook.fiveminsmore.gpx; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import com.github.johnkil.print.PrintView; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.google.maps.android.clustering.ClusterManager; import com.unnamed.b.atv.model.TreeNode; import io.ticofab.androidgpxparser.parser.domain.Gpx; import io.ticofab.androidgpxparser.parser.domain.Track; import io.ticofab.androidgpxparser.parser.domain.WayPoint; import io.typebrook.fiveminsmore.MapsManager; import io.typebrook.fiveminsmore.R; import io.typebrook.fiveminsmore.model.CustomMarker; import io.typebrook.fiveminsmore.utils.MapUtils; public class GpxHolder extends TreeNode.BaseNodeViewHolder<GpxHolder.GpxTreeItem> { private static final String TAG = "GpxHolder"; private PrintView arrowView; private CheckBox nodeSelector; private MapsManager manager; public GpxHolder(Context context) { super(context); } public GpxHolder(Context context, MapsManager manager) { super(context); this.manager = manager; } @Override public View createNodeView(final TreeNode node, final GpxTreeItem value) { final LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.holder_gpx_tree, null, false); ImageView iconView = (ImageView) view.findViewById(R.id.tree_item_icon); iconView.setImageResource(value.icon); TextView textView = (TextView) view.findViewById(R.id.tree_item_text); textView.setText(value.text); arrowView = (PrintView) view.findViewById(R.id.arrow_icon); if (node.isLeaf()) { arrowView.setVisibility(View.GONE); } nodeSelector = (CheckBox) view.findViewById(R.id.node_selector); nodeSelector.setOnCheckedChangeListener(getCheckListener(node, value)); view.findViewById(R.id.btn_delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nodeSelector.setChecked(false); getTreeView().removeNode(node); manager.clusterTheMarkers(); } }); if (node.isLeaf()) view.setOnClickListener(getClickListener(value)); return view; } private View.OnClickListener getClickListener(final GpxTreeItem value) { return new View.OnClickListener() { @Override public void onClick(View v) { switch (value.type) { case ITEM_TYPE_TRACK: MapUtils.zoomToPolyline(manager.getCurrentMap(), value.polylines[0]); break; case ITEM_TYPE_WAYPOINT: MapUtils.zoomToMarker(manager.getCurrentMap(), value.marker); break; } } }; } private CompoundButton.OnCheckedChangeListener getCheckListener (final TreeNode node, final GpxTreeItem value) { return new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { node.setSelected(isChecked); for (TreeNode n : node.getChildren()) { getTreeView().selectNode(n, isChecked); } for (int mapCode = 0; mapCode < manager.getMapsNum(); mapCode++) { switch (value.type) { case ITEM_TYPE_GPX: manager.getClusterManager(mapCode).cluster(); break; case ITEM_TYPE_TRACK: if (isChecked) { value.polylines[mapCode] = manager.getMap(mapCode) .addPolyline(value.trkOpts); MapUtils.zoomToPolyline(manager.getMap(mapCode), value.polylines[mapCode]); } else if (value.polylines[mapCode] == null) { break; } else { value.polylines[mapCode].remove(); value.polylines[mapCode] = null; } break; case ITEM_TYPE_WAYPOINT: if (isChecked) { value.isMarkers[mapCode] = true; manager.getClusterManager(mapCode).addItem(value.marker); } else if (!value.isMarkers[mapCode]) { break; } else { value.isMarkers[mapCode] = false; manager.getClusterManager(mapCode).removeItem(value.marker); } break; } } } }; } @Override public void toggle(boolean active) { arrowView.setIconText(context.getResources().getString(active ? R.string.ic_keyboard_arrow_down : R.string.ic_keyboard_arrow_right)); } // CheckBox @Override public void toggleSelectionMode(boolean editModeEnabled) { nodeSelector.setChecked(mNode.isSelected()); } public static class GpxTreeItem { public int type; public int icon; public String text; // attribute for GPX public Gpx gpx; // attribute for WayPoint public CustomMarker marker; public boolean[] isMarkers = {false, false}; // attribute for Track public PolylineOptions trkOpts; public Polyline[] polylines = {null, null}; public GpxTreeItem(Builder builder) { type = builder.type; icon = builder.icon; text = builder.text; gpx = builder.gpx; marker = builder.marker; trkOpts = builder.trkOpts; } public static class Builder { private int type; private int icon; private String text; private Gpx gpx; private CustomMarker marker; private PolylineOptions trkOpts; public Builder setType(int type) { this.type = type; return this; } public Builder setIcon(int icon) { this.icon = icon; return this; } public Builder setText(String text) { this.text = text; return this; } public Builder setGpx(Gpx gpx) { this.gpx = gpx; return this; } public Builder setMarker(WayPoint wpt) { this.marker = GpxUtils.waypt2Marker(wpt); return this; } public Builder setTrkOpts(PolylineOptions opts) { this.trkOpts = opts; return this; } public GpxTreeItem build() { return new GpxTreeItem(this); } } } public static final int ITEM_TYPE_GPX = 1; public static final int ITEM_TYPE_TRACK = 2; public static final int ITEM_TYPE_WAYPOINT = 3; public static final int ITEM_ICON_GPX = R.drawable.ic_folder_black_24dp; public static final int ITEM_ICON_WAYPOINT = R.drawable.ic_place_black_24dp; public static final int ITEM_ICON_TRACK = R.drawable.ic_timeline_black_24dp; }
package org.kravemir.gradle.sass; import org.gradle.api.Plugin; import org.gradle.api.Project; public class SassPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getExtensions().add("sass", project.container( SassCompileTask.class, name -> project.getTasks().create(name + "Sass", SassCompileTask.class, task -> task.setGroup("sass")) )); } }
package io.hawt.sample; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import org.apache.aries.blueprint.container.BlueprintContainerImpl; import org.apache.camel.CamelException; import org.apache.camel.util.CamelContextHelper; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Slf4jLog; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebInfConfiguration; import org.eclipse.jetty.webapp.WebXmlConfiguration; import org.mortbay.jetty.plugin.JettyWebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.management.MBeanServer; import java.io.File; import java.lang.management.ManagementFactory; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A simple bootstrap class */ public class Main { private static final transient Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { try { System.setProperty("org.eclipse.jetty.util.log.class", Slf4jLog.class.getName()); Log.setLog(new Slf4jLog("jetty")); int port = Integer.parseInt(System.getProperty("jettyPort", "8080")); String contextPath = System.getProperty("context", "/hawtio"); if (!contextPath.startsWith("/")) { contextPath = "/" + contextPath; } String sourcePath = "src/main/webapp"; String webappOutdir = System.getProperty("webapp-outdir", "target/hawtio-web-1.3-SNAPSHOT"); String webXml = sourcePath + "/WEB-INF/web.xml"; require(fileExists(webXml), "No web.xml could be found for $webXml"); String pathSeparator = File.pathSeparator; String classpath = System.getProperty("java.class.path", ""); ImmutableList<String> classpaths = ImmutableList.copyOf(Arrays.asList(classpath.split(pathSeparator))); Iterable<String> jarNames = Iterables.filter(classpaths, new Predicate<String>() { public boolean apply(String path) { return isScannedWebInfLib(path); } }); Iterable<File> allFiles = Iterables.transform(jarNames, new Function<String, File>() { public File apply(String path) { return new File(path); } }); Iterable<File> files = Iterables.filter(allFiles, new Predicate<File>() { public boolean apply(File file) { return file != null && file.exists(); } }); Iterable<File> jars = Iterables.filter(files, new Predicate<File>() { public boolean apply(File file) { return file.isFile(); } }); Iterable<File> extraClassDirs = Iterables.filter(files, new Predicate<File>() { public boolean apply(File file) { return file.isDirectory(); } }); JettyWebAppContext context = new JettyWebAppContext(); context.setWebInfLib(ImmutableList.copyOf(jars)); Configuration[] contextConfigs = {new WebXmlConfiguration(), new WebInfConfiguration()}; context.setConfigurations(contextConfigs); context.setDescriptor(webXml); context.setResourceBases(new String[] {sourcePath, webappOutdir}); context.setContextPath(contextPath); context.setParentLoaderPriority(true); // lets try disable the memory mapped file which causes issues // on Windows when using mvn -Pwatch if (System.getProperty("jettyUseFileLock", "").toLowerCase().equals("false")) { LOG.info("Disabling the use of the Jetty file lock for static content to try fix incremental grunt compilation on Windows"); context.setCopyWebDir(true); context.setInitParameter("useFileMappedBuffer", "false"); } Server server = new Server(port); server.setHandler(context); // enable JMX MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); MBeanContainer mbeanContainer = new MBeanContainer(mbeanServer); if (server.getContainer() != null) { server.getContainer().addEventListener(mbeanContainer); } server.addBean(mbeanContainer); // lets initialise blueprint List<URL> resourcePaths = new ArrayList<URL>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resources = classLoader.getResources("OSGI-INF/blueprint/blueprint.xml"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); String text = url.toString(); if (text.contains("karaf")) { LOG.info("Ignoring karaf based blueprint file " + text); } else if (text.contains("hawtio-system")) { LOG.info("Ignoring hawtio-system"); } else { resourcePaths.add(url); } } LOG.info("Loading Blueprint contexts " + resourcePaths); Map<String, String> properties = new HashMap<String, String>(); BlueprintContainerImpl container = new BlueprintContainerImpl(classLoader, resourcePaths, properties, true); if (args.length == 0 || !args[0].equals("nospring")) { // now lets startup a spring application context LOG.info("starting spring application context"); ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Object activemq = appContext.getBean("activemq"); LOG.info("created activemq: " + activemq); appContext.start(); LOG.warn("Don't run with scissors!"); LOG.error("Someone somewhere is not using Fuse! :)", new CamelException("My exception message")); // now lets force an exception with a stack trace from camel... try { CamelContextHelper.getMandatoryEndpoint(null, null); } catch (Throwable e) { LOG.error("Expected exception for testing: " + e, e); } } // lets connect to fabric println(""); println(""); println("OPEN: http://localhost:" + port + contextPath + " using web app source path: " + webappOutdir); println(""); println(""); LOG.info("starting jetty"); server.start(); LOG.info("Joining the jetty server thread..."); server.join(); } catch (Throwable e) { LOG.error(e.getMessage(), e); } } /** * Returns true if the file exists */ public static boolean fileExists(String path) { File file = new File(path); return file.exists() && file.isFile(); } /** * Returns true if the directory exists */ public static boolean directoryExists(String path) { File file = new File(path); return file.exists() && file.isDirectory(); } public static void require(boolean flag, String message) { if (!flag) { throw new IllegalStateException(message); } } /** * Returns true if we should scan this lib for annotations */ public static boolean isScannedWebInfLib(String path) { return path.endsWith("kool/website/target/classes"); //return path.contains("kool") //return true } public static void println(Object message) { System.out.println(message); } }
package org.jfree.chart.util; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; /** * A custom number formatter that formats numbers as hexadecimal strings. * There are some limitations, so be careful using this class. * * @since 1.0.6 */ public class HexNumberFormat extends NumberFormat { /** Number of hexadecimal digits for a byte. */ public static final int BYTE = 2; /** Number of hexadecimal digits for a word. */ public static final int WORD = 4; /** Number of hexadecimal digits for a double word. */ public static final int DWORD = 8; /** Number of hexadecimal digits for a quad word. */ public static final int QWORD = 16; /** The number of digits (shorter strings will be left padded). */ private int m_numDigits = DWORD; /** * Creates a new instance with 8 digits. */ public HexNumberFormat() { this(DWORD); } /** * Creates a new instance with the specified number of digits. * @param digits the digits. */ public HexNumberFormat(int digits) { super(); this.m_numDigits = digits; } /** * Returns the number of digits. * * @return The number of digits. */ public final int getNumberOfDigits() { return this.m_numDigits; } /** * Sets the number of digits. * * @param digits the number of digits. */ public void setNumberOfDigits(int digits) { this.m_numDigits = digits; } /** * Formats the specified number as a hexadecimal string. The decimal * fraction is ignored. * * @param number the number to format. * @param toAppendTo the buffer to append to (ignored here). * @param pos the field position (ignored here). * * @return The string buffer. */ @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { return format((long) number, toAppendTo, pos); } /** * Formats the specified number as a hexadecimal string. The decimal * fraction is ignored. * * @param number the number to format. * @param toAppendTo the buffer to append to (ignored here). * @param pos the field position (ignored here). * * @return The string buffer. */ @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { String l_hex = Long.toHexString(number).toUpperCase(); int l_pad = this.m_numDigits - l_hex.length(); l_pad = (0 < l_pad) ? l_pad : 0; StringBuffer l_extended = new StringBuffer("0x"); for (int i = 0; i < l_pad; i++) { l_extended.append(0); } l_extended.append(l_hex); return l_extended; } /** * Parsing is not implemented, so this method always returns * <code>null</code>. * * @param source ignored. * @param parsePosition ignored. * * @return Always <code>null</code>. */ @Override public Number parse (String source, ParsePosition parsePosition) { return null; // don't bother with parsing } }
package com.example.rollingball.app; import com.hackoeur.jglm.Vec3; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.LinkedList; public class Scene implements IUpdatable, IDrawable { private Vec3 _gravity_in_m_per_s_s = new Vec3( 0.0f, -9.8f, 0.0f); public LinkedList<GameObject> game_objects = new LinkedList< GameObject >( ); public boolean to_exit = false; public Camera camera = new Camera( this ); public Lighting lighting = new Lighting(); public InputManager input_manager = new InputManager( this ); public SceneManager scene_manager = null; protected Message[] _massages; public Scene( final SceneManager scene_manager_ ) { scene_manager = scene_manager_; } void push( GameObject game_object ) { game_objects.push( game_object ); } void message( Message message ) { } @Override public void update( final float delta_time_in_seconds ) { input_manager.update( delta_time_in_seconds ); camera.update( delta_time_in_seconds ); for ( GameObject g : game_objects ) { g.update( delta_time_in_seconds ); g.effect_gravity( _gravity_in_m_per_s_s ); } _update_collision(); } @Override public void draw() { lighting.draw(); for ( GameObject g : game_objects ) g.draw(); } public void on_resume() { for ( GameObject g : game_objects ) g.on_resume(); } protected void _update_collision() { // LinkedList<GameObject> _object = new LinkedList< GameObject >(); for ( int na = 0; na < game_objects.size(); ++na ) for ( int nb = na + 1; nb < game_objects.size(); ++nb ) _collision(game_objects.get( na ),game_objects.get( nb )); } protected void _collision(GameObject a, GameObject b) { if ( a instanceof RigidBodyGameObject && b instanceof RigidBodyGameObject ) _collision_body_body( ( RigidBodyGameObject )a, ( RigidBodyGameObject )b ); else if ( a instanceof RigidBodyGameObject && b instanceof FieldGameObject ) _collision_body_field( ( RigidBodyGameObject )a, ( FieldGameObject )b); else if ( b instanceof RigidBodyGameObject && a instanceof FieldGameObject ) _collision_body_field( ( RigidBodyGameObject )b, ( FieldGameObject )a); } protected void _collision_body_body(RigidBodyGameObject a,RigidBodyGameObject b) { for ( BoundingSphere ab : a.collision_boundings ) for ( BoundingSphere bb : b.collision_boundings ) if ( ab.intersect_bool( bb ) ) { a.forces.add( b.velocity.cross( b.velocity ).multiply( b.mass * 0.5f ) ); b.forces.add( a.velocity.cross( a.velocity ).multiply( a.mass * 0.5f ) ); } } protected void _collision_body_field( RigidBodyGameObject a, FieldGameObject b ) { for ( BoundingSphere ab : a.collision_boundings ) { final int field_x = (int)a.position.getX(); final int field_z = (int)a.position.getZ(); // a x z if ( field_x < 0 || field_x >= b.length_x() || field_z < 0 || field_z >= b.length_z() ) continue; { final float field_y = b.field_planes.get( field_x ).get( field_z ); final Vec3 floor_position = new Vec3( a.position.getX(), field_y, a.position.getZ() ); final float distance = ab.intersect_field( floor_position ); if ( distance <= 0.0f ) { //a.forces.add( new Vec3( 0.0f, -0.5f * a.mass * a.velocity.getY() * a.velocity.getY(), 0.0f ) ); a.velocity = new Vec3( a.velocity.getX(), -0.3f * a.velocity.getY(), a.velocity.getZ() ); a.position = a.position.subtract( new Vec3( 0.0f, distance, 0.0f ) ); } } { // X + 1 if ( field_x < b.length_x() - 2 ) { final int field_xm = field_x + 1; final float field_y = b.field_planes.get( field_xm ).get( field_z ); final Vec3 wall_position = new Vec3( field_xm, 0, field_z ); final Vec3 wall_normal = new Vec3( -1.0f, 0.0f, 0.0f ); final float distance = ab.intersect_field( wall_position, wall_normal ); if ( distance <= 0.0f && field_y <= ab.position().getY() ) { a.velocity = new Vec3( -a.velocity.getX(), a.velocity.getY(), a.velocity.getZ() ); a.position = a.position.subtract( new Vec3( distance, 0.0f, 0.0f ) ); } } // X - 1 if ( field_x > 0 ) { final int field_xm = field_x - 1; final float field_y = b.field_planes.get( field_xm ).get( field_z ); final Vec3 wall_position = new Vec3( field_xm, 0, field_z ); final Vec3 wall_normal = new Vec3( +1.0f, 0.0f, 0.0f ); final float distance = ab.intersect_field( wall_position, wall_normal ); if ( distance <= 0.0f && field_y <= ab.position().getY() ) { a.velocity = new Vec3( -a.velocity.getX(), a.velocity.getY(), a.velocity.getZ() ); a.position = a.position.subtract( new Vec3( distance, 0.0f, 0.0f ) ); } } } { // Z + 1 if ( field_z < b.length_z() - 2 ) { final int field_zm = field_z + 1; final float field_y = b.field_planes.get( field_x ).get( field_zm ); final Vec3 wall_position = new Vec3( field_x, 0, field_zm ); final Vec3 wall_normal = new Vec3( 0.0f, 0.0f, -1.0f ); final float distance = ab.intersect_field( wall_position, wall_normal ); if ( distance <= 0.0f && field_y <= ab.position().getY() ) { a.velocity = new Vec3( a.velocity.getX(), a.velocity.getY(), -a.velocity.getZ() ); a.position = a.position.subtract( new Vec3( 0.0f, 0.0f, distance ) ); } } // X - 1 if ( field_z > 0 ) { final int field_zm = field_z - 1; final float field_y = b.field_planes.get( field_x ).get( field_zm ); final Vec3 wall_position = new Vec3( field_x, 0, field_zm ); final Vec3 wall_normal = new Vec3( 0.0f, 0.0f, +1.0f ); final float distance = ab.intersect_field( wall_position, wall_normal ); if ( distance <= 0.0f && field_y <= ab.position().getY() ) { a.velocity = new Vec3( a.velocity.getX(), a.velocity.getY(), -a.velocity.getZ() ); a.position = a.position.subtract( new Vec3( 0.0f, 0.0f, distance ) ); } } } } } }
package it.polito.mad.countonme; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.utils.ColorTemplate; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import it.polito.mad.countonme.business.Balance; import it.polito.mad.countonme.database.ExpensesListLoader; import it.polito.mad.countonme.database.SharingActivityLoader; import it.polito.mad.countonme.exceptions.DataLoaderException; import it.polito.mad.countonme.interfaces.IOnDataListener; import it.polito.mad.countonme.models.*; public class BalanceFragment extends BaseFragment implements IOnDataListener { private static NumberFormat mFormatter = new DecimalFormat("#0.00"); BarChart barChart; ArrayList<BarEntry> BARENTRY; ArrayList<String> BarEntryLabels; BarDataSet Bardataset; BarData BARDATA; TextView tvMySpend; TextView tvMyCredit; TextView tvMyDebt; LinearLayout mOwesLayout; List<Debt> DebtList; private List<Expense> mExpenseList; private Map<String, User> mUsers; private SharingActivityLoader mSharingActivityLoader; private ExpensesListLoader mExpensesListLoader; private List<DebtValue> mDebtValueList; @Override public void onAttach(Context context) { super.onAttach(context); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.balance_fragment, container, false); if (savedInstanceState != null) setData(savedInstanceState.getString(AppConstants.SHARING_ACTIVITY_KEY)); else { Bundle args = getArguments(); if (args != null) setData(args.getString(AppConstants.SHARING_ACTIVITY_KEY)); } tvMySpend = (TextView) view.findViewById(R.id.my_spend); tvMyCredit = (TextView) view.findViewById(R.id.my_credit); tvMyDebt = (TextView) view.findViewById(R.id.my_debt); barChart = (BarChart) view.findViewById(R.id.balance_chart); mOwesLayout = (LinearLayout) view.findViewById( R.id.owes_container ); mSharingActivityLoader = new SharingActivityLoader(); mSharingActivityLoader.setOnDataListener( this ); mExpensesListLoader = new ExpensesListLoader(); mExpensesListLoader.setOnDataListener( this ); return view; } @Override public void onData( Object data ) { if( data instanceof SharingActivity ) { mUsers = ( (SharingActivity) data ).getUsers(); try { mExpensesListLoader.loadExpensesList( (String) getData() ); } catch (DataLoaderException e) { e.printStackTrace(); } catch (Exception exp) {} } else { mExpenseList = ( ArrayList<Expense> ) data; FillChart(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(AppConstants.SHARING_ACTIVITY_KEY, (String) getData()); } @Override public void onResume() { super.onResume(); adjustActionBar(); try { mSharingActivityLoader.loadSharingActivity( (String) getData() ); } catch (DataLoaderException e) { e.printStackTrace(); } } @Override public void onStop() { super.onStop(); } private void adjustActionBar() { ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.balance_title); setHasOptionsMenu(true); } private void FillChart() { BARENTRY = new ArrayList<>(); BarEntryLabels = new ArrayList<String>(); FillData(); Bardataset = new BarDataSet(BARENTRY, "Members"); BARDATA = new BarData(BarEntryLabels, Bardataset); Bardataset.setColors(ColorTemplate.COLORFUL_COLORS); barChart.setData(BARDATA); barChart.invalidate(); barChart.animateY(3000); barChart.setDescription("Credits"); BARDATA.notifyDataChanged(); } private void FillData() { if ( mExpenseList != null && mUsers != null && mExpenseList.size() != 0 && mUsers.size() != 0) { Balance BalanceClass = new Balance(mExpenseList, mUsers); tvMySpend.setText(String.valueOf(BalanceClass.GetMySpend())); tvMyCredit.setText(String.valueOf(BalanceClass.GetMyCredit())); tvMyDebt.setText(String.valueOf(BalanceClass.GetMyDept())); DebtList = BalanceClass.getDebtList(); AddDebtsToBARENTRY(); mDebtValueList = BalanceClass.GetOwsList(DebtList); fillOwes(); } } private void AddDebtsToBARENTRY() { int Index = 0; for (Iterator<Debt> i = DebtList.iterator(); i.hasNext(); ) { Debt item = i.next(); BARENTRY.add(new BarEntry(item.getCredit().intValue(), Index)); String Name = item.getUser().getName(); if (Name == null) Name = item.getUser().getEmail(); BarEntryLabels.add(Name); Index++; } } private void fillOwes() { LayoutInflater myInflater = LayoutInflater.from( getActivity() ); for ( DebtValue debt: mDebtValueList ) { View child = myInflater.inflate(R.layout.debt_item, null); TextView tvDebter = (TextView) child.findViewById( R.id.debter_name); TextView tvAmout = (TextView) child.findViewById(R.id.owes_amount); TextView tvSpendName = (TextView) child.findViewById(R.id.spend_name); String Debter = ""; if(debt.getDebterUser().getName()!=null) Debter = debt.getDebterUser().getName(); else Debter = debt.getDebterUser().getEmail(); String Spend = ""; if(debt.getUser().getName()!=null) Spend = debt.getUser().getName(); else Spend = debt.getUser().getEmail(); tvDebter.setText(Debter); tvSpendName.setText(Spend); tvAmout.setText( mFormatter.format( debt.getAmount() ) + "" ); mOwesLayout.addView( child ); } } }
package com.gh4a.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.AttrRes; import android.support.annotation.ColorInt; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.design.widget.AppBarLayout; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentActivity; import android.support.v4.os.ParcelableCompat; import android.support.v4.os.ParcelableCompatCreatorCallbacks; import android.support.v4.view.AbsSavedState; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.Editable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.gh4a.ProgressDialogTask; import com.gh4a.R; import com.gh4a.utils.UiUtils; import org.eclipse.egit.github.core.User; import java.io.IOException; import java.util.Set; public class EditorBottomSheet extends FrameLayout implements View.OnClickListener, View.OnTouchListener, AppBarLayout.OnOffsetChangedListener { public interface Callback { @StringRes int getCommentEditorHintResId(); void onSendCommentInBackground(String comment) throws IOException; void onCommentSent(); FragmentActivity getActivity(); CoordinatorLayout getRootLayout(); } public interface OnToggleAdvancedModeListener { void onToggleAdvancedMode(boolean advancedMode); } private TabLayout mTabs; private ToggleableBottomSheetBehavior mBehavior; private View mAdvancedEditorContainer; private CommentEditor mBasicEditor; private CommentEditor mAdvancedEditor; private MarkdownButtonsBar mMarkdownButtons; private MarkdownPreviewWebView mPreviewWebView; private ImageView mAdvancedEditorToggle; private OnToggleAdvancedModeListener mOnToggleAdvancedMode; private Callback mCallback; private View mResizingView; private @ColorInt int mHighlightColor = Color.TRANSPARENT; private int mBasicPeekHeight; private int mAdvancedPeekHeight; private int mLatestOffset; private int mTopShadowHeight; private BottomSheetBehavior.BottomSheetCallback mBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { if (mAdvancedEditorContainer != null && newState == BottomSheetBehavior.STATE_COLLAPSED) { setAdvancedEditorVisible(false); } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }; public EditorBottomSheet(Context context) { super(context); initialize(); } public EditorBottomSheet(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public EditorBottomSheet(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(); } private void initialize() { final Resources res = getResources(); mBasicPeekHeight = res.getDimensionPixelSize(R.dimen.comment_editor_peek_height); mAdvancedPeekHeight = res.getDimensionPixelSize(R.dimen.comment_advanced_editor_peek_height); mTopShadowHeight = res.getDimensionPixelSize(R.dimen.bottom_sheet_top_shadow_height); View view = View.inflate(getContext(), R.layout.editor_bottom_sheet, this); mAdvancedEditorToggle = (ImageView) view.findViewById(R.id.iv_advanced_editor_toggle); mAdvancedEditorToggle.setOnClickListener(this); View sendButton = view.findViewById(R.id.send_button); sendButton.setOnClickListener(this); mBasicEditor = (CommentEditor) view.findViewById(R.id.et_basic_editor); mBasicEditor.addTextChangedListener( new UiUtils.ButtonEnableTextWatcher(mBasicEditor, sendButton)); post(new Runnable() { @Override public void run() { getBehavior().setBottomSheetCallback(mBehaviorCallback); resetPeekHeight(); } }); } public void setOnToggleAdvancedModeListener(OnToggleAdvancedModeListener listener) { this.mOnToggleAdvancedMode = listener; } public void setCallback(Callback callback) { mCallback = callback; mBasicEditor.setCommentEditorHintResId(mCallback.getCommentEditorHintResId()); if (mAdvancedEditor != null) { mAdvancedEditor.setCommentEditorHintResId(mCallback.getCommentEditorHintResId()); } } public void setLocked(boolean locked) { mBasicEditor.setLocked(locked); if (mAdvancedEditor != null) { mAdvancedEditor.setLocked(locked); } } public void setMentionUsers(Set<User> users) { mBasicEditor.setMentionUsers(users); if (mAdvancedEditor != null) { mAdvancedEditor.setMentionUsers(users); } } public void setHighlightColor(@AttrRes int colorAttrId) { mHighlightColor = UiUtils.resolveColor(getContext(), colorAttrId); if (mMarkdownButtons != null) { mMarkdownButtons.setButtonsBackgroundColor(mHighlightColor); } } public void addQuote(CharSequence text) { if (isInAdvancedMode()) { mAdvancedEditor.addQuote(text); } mBasicEditor.addQuote(text); } @Override public boolean onTouch(View view, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: getBehavior().setEnabled(false); break; case MotionEvent.ACTION_UP: getBehavior().setEnabled(true); break; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_advanced_editor_toggle: setAdvancedMode(!isInAdvancedMode()); break; case R.id.send_button: new CommentTask(getCommentText().toString()).schedule(); UiUtils.hideImeForView(mCallback.getActivity().getCurrentFocus()); break; } } @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { mLatestOffset = appBarLayout.getTotalScrollRange() + verticalOffset; if (mLatestOffset >= 0) { updatePeekHeight(isInAdvancedMode()); } } public void setResizingView(View view) { mResizingView = view; } public boolean isExpanded() { return getBehavior().getState() == BottomSheetBehavior.STATE_EXPANDED && getBehavior().getPeekHeight() != getHeight(); } public void resetPeekHeight() { mLatestOffset = 0; updatePeekHeight(isInAdvancedMode()); } private void updatePeekHeight(boolean isInAdvancedMode) { // Set the bottom padding to make the bottom appear as not moving while the // AppBarLayout pushes it down or up. setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), mLatestOffset); final int peekHeight = isInAdvancedMode ? mAdvancedPeekHeight : mBasicPeekHeight; if (mResizingView != null) { mResizingView.setPadding(mResizingView.getPaddingLeft(), mResizingView.getPaddingTop(), mResizingView.getPaddingRight(), peekHeight + mLatestOffset - mTopShadowHeight); } // Update peek height to keep the bottom sheet at unchanged position getBehavior().setPeekHeight(peekHeight + mLatestOffset); } public void setAdvancedMode(final boolean visible) { if (mAdvancedEditor == null) { if (!visible) { return; } initAdvancedMode(); } if (visible) { // Showing editor has to be done before updating peek height so when it expands the // user can immediately see the content setAdvancedEditorVisible(true); } // Expand bottom sheet through message queue so the animation can play. post(new Runnable() { @Override public void run() { updatePeekHeight(visible); getBehavior().setState(visible ? BottomSheetBehavior.STATE_EXPANDED : BottomSheetBehavior.STATE_COLLAPSED); } }); } public boolean isInAdvancedMode() { return mAdvancedEditorContainer != null && mAdvancedEditorContainer.getVisibility() == View.VISIBLE; } public void setCommentText(CharSequence text, boolean clearFocus) { if (isInAdvancedMode()) { mAdvancedEditor.setText(text); if (clearFocus) { mAdvancedEditor.clearFocus(); } } else { mBasicEditor.setText(text); if (clearFocus) { mBasicEditor.clearFocus(); } } } private Editable getCommentText() { if (isInAdvancedMode()) { return mAdvancedEditor.getText(); } return mBasicEditor.getText(); } private void setAdvancedEditorVisible(boolean visible) { mAdvancedEditorContainer.setVisibility(visible ? View.VISIBLE : View.GONE); mBasicEditor.setVisibility(visible ? View.GONE : View.VISIBLE); mTabs.setVisibility(visible ? View.VISIBLE : View.GONE); if (visible) { mAdvancedEditor.setText(mBasicEditor.getText()); mAdvancedEditor.requestFocus(); mAdvancedEditor.setSelection(mAdvancedEditor.getText().length()); } else { mBasicEditor.setText(mAdvancedEditor.getText()); mBasicEditor.requestFocus(); mBasicEditor.setSelection(mBasicEditor.getText().length()); } mAdvancedEditorToggle.setImageResource(UiUtils.resolveDrawable(getContext(), visible ? R.attr.collapseIcon : R.attr.expandIcon)); if (mOnToggleAdvancedMode != null) { mOnToggleAdvancedMode.onToggleAdvancedMode(visible); } } private void initAdvancedMode() { ViewStub stub = (ViewStub) findViewById(R.id.advanced_editor_stub); mAdvancedEditorContainer = stub.inflate(); ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager); viewPager.setAdapter(new AdvancedEditorPagerAdapter(getContext())); mTabs = (TabLayout) findViewById(R.id.tabs); mTabs.setupWithViewPager(viewPager); LinearLayout tabStrip = (LinearLayout) mTabs.getChildAt(0); for (int i = 0; i < tabStrip.getChildCount(); i++) { View tab = tabStrip.getChildAt(i); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tab.getLayoutParams(); lp.width = LinearLayout.LayoutParams.WRAP_CONTENT; lp.weight = 1; tab.setLayoutParams(lp); } mAdvancedEditor = (CommentEditor) mAdvancedEditorContainer.findViewById(R.id.editor); mAdvancedEditor.addTextChangedListener( new UiUtils.ButtonEnableTextWatcher(mAdvancedEditor, findViewById(R.id.send_button))); if (mCallback != null) { mAdvancedEditor.setCommentEditorHintResId(mCallback.getCommentEditorHintResId()); } mAdvancedEditor.setLocked(mBasicEditor.isLocked()); mAdvancedEditor.setMentionUsers(mBasicEditor.getMentionUsers()); mMarkdownButtons = (MarkdownButtonsBar) mAdvancedEditorContainer.findViewById(R.id.markdown_buttons); mMarkdownButtons.setEditText(mAdvancedEditor); if (mHighlightColor != Color.TRANSPARENT) { mMarkdownButtons.setButtonsBackgroundColor(mHighlightColor); } mPreviewWebView = (MarkdownPreviewWebView) findViewById(R.id.preview); mPreviewWebView.setEditText(mAdvancedEditor); mMarkdownButtons.setBottomSheetBehavior(getBehavior()); mAdvancedEditorContainer.findViewById(R.id.editor_scroller).setOnTouchListener(this); mPreviewWebView.setOnTouchListener(this); mAdvancedEditor.setOnTouchListener(this); viewPager.setOnTouchListener(this); } private ToggleableBottomSheetBehavior getBehavior() { if (mBehavior == null) { mBehavior = (ToggleableBottomSheetBehavior) BottomSheetBehavior.from(this); } return mBehavior; } private class CommentTask extends ProgressDialogTask<Void> { private final String mText; public CommentTask(String text) { super(mCallback.getActivity(), mCallback.getRootLayout(), R.string.saving_comment); mText = text; } @Override protected ProgressDialogTask<Void> clone() { return new CommentTask(mText); } @Override protected Void run() throws IOException { mCallback.onSendCommentInBackground(mText); return null; } @Override protected void onSuccess(Void result) { mCallback.onCommentSent(); setCommentText(null, true); setAdvancedMode(false); } @Override protected String getErrorMessage() { return getContext().getString(R.string.issue_error_comment); } } private static class AdvancedEditorPagerAdapter extends PagerAdapter { private static final int[] TITLES = new int[] { R.string.edit, R.string.preview }; private Context mContext; public AdvancedEditorPagerAdapter(Context context) { mContext = context; } @Override public Object instantiateItem(ViewGroup container, int position) { @IdRes int resId = 0; switch (position) { case 0: resId = R.id.comment_container; break; case 1: resId = R.id.preview; break; } return container.findViewById(resId); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public CharSequence getPageTitle(int position) { return mContext.getString(TITLES[position]); } @Override public int getCount() { return TITLES.length; } } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final SavedState ss = new SavedState(superState); ss.isInAdvancedMode = isInAdvancedMode(); ss.commentText = getCommentText().toString(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state instanceof SavedState) { final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setAdvancedMode(ss.isInAdvancedMode); mBasicEditor.setText(ss.commentText); if (mAdvancedEditor != null) { mAdvancedEditor.setText(ss.commentText); } } else { super.onRestoreInstanceState(state); } } private static class SavedState extends AbsSavedState { boolean isInAdvancedMode; String commentText; public SavedState(Parcel source, ClassLoader loader) { super(source, loader); isInAdvancedMode = source.readByte() == 1; commentText = source.readString(); } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeByte((byte) (isInAdvancedMode ? 1 : 0)); out.writeString(commentText); } public static final Parcelable.Creator<SavedState> CREATOR = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() { @Override public SavedState createFromParcel(Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }); } }
package jp.blanktar.ruumusic.service; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.annotation.WorkerThread; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; import android.media.RemoteControlClient; import android.media.audiofx.BassBoost; import android.media.audiofx.Equalizer; import android.media.audiofx.LoudnessEnhancer; import android.media.audiofx.PresetReverb; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.view.KeyEvent; import android.widget.Toast; import jp.blanktar.ruumusic.R; import jp.blanktar.ruumusic.client.AudioPreferenceActivity; import jp.blanktar.ruumusic.client.MainActivity; import jp.blanktar.ruumusic.util.RuuDirectory; import jp.blanktar.ruumusic.util.RuuFile; import jp.blanktar.ruumusic.util.RuuFileBase; @WorkerThread public class RuuService extends Service implements SharedPreferences.OnSharedPreferenceChangeListener{ public final static String ACTION_PLAY = "jp.blanktar.ruumusic.PLAY"; public final static String ACTION_PLAY_RECURSIVE = "jp.blanktar.ruumusic.PLAY_RECURSIVE"; public final static String ACTION_PLAY_SEARCH = "jp.blanktar.ruumusic.PLAY_SEARCH"; public final static String ACTION_PAUSE = "jp.blanktar.ruumusic.PAUSE"; public final static String ACTION_PLAY_PAUSE = "jp.blanktar.ruumusic.PLAY_PAUSE"; public final static String ACTION_NEXT = "jp.blanktar.ruumusic.NEXT"; public final static String ACTION_PREV = "jp.blanktar.ruumusic.PREV"; public final static String ACTION_SEEK = "jp.blanktar.ruumusic.SEEK"; public final static String ACTION_REPEAT = "jp.blanktar.ruumusic.REPEAT"; public final static String ACTION_SHUFFLE = "jp.blanktar.ruumusic.SHUFFLE"; public final static String ACTION_PING = "jp.blanktar.ruumusic.PING"; public final static String ACTION_STATUS = "jp.blanktar.ruumusic.STATUS"; public final static String ACTION_FAILED_PLAY = "jp.blanktar.ruumusic.FAILED_PLAY"; public final static String ACTION_NOT_FOUND = "jp.blanktar.ruumusic.NOT_FOUND"; private MediaPlayer player; private MediaPlayer endOfListSE; private MediaPlayer errorSE; private Timer deathTimer; private static RemoteControlClient remoteControlClient; private Playlist playlist; private String repeatMode = "off"; private boolean shuffleMode = false; private boolean ready = false; private boolean loadingWait = false; private boolean errored = false; private boolean playingFromLastest = true; private BassBoost bassBoost = null; private PresetReverb presetReverb = null; private LoudnessEnhancer loudnessEnhancer = null; private Equalizer equalizer = null; @Override @Nullable public IBinder onBind(@Nullable Intent intent){ throw null; } @Override public void onCreate(){ player = new MediaPlayer(); endOfListSE = MediaPlayer.create(getApplicationContext(), R.raw.eol); errorSE = MediaPlayer.create(getApplicationContext(), R.raw.err); final SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); repeatMode = preference.getString("repeat_mode", "off"); shuffleMode = preference.getBoolean("shuffle_mode", false); String recursive = preference.getString("recursive_path", null); if(recursive != null){ try{ playlist = Playlist.getRecursive(getApplicationContext(), recursive); if(shuffleMode){ playlist.shuffle(false); } }catch(RuuFileBase.CanNotOpen | Playlist.EmptyDirectory e){ playlist = null; } } if(playlist == null){ String searchQuery = preference.getString("search_query", null); String searchPath = preference.getString("search_path", null); if(searchQuery != null && searchPath != null){ try{ playlist = Playlist.getSearchResults(getApplicationContext(), searchPath, searchQuery); if(shuffleMode){ playlist.shuffle(false); } }catch(RuuFileBase.CanNotOpen | Playlist.EmptyDirectory e){ playlist = null; } } } String last_play = preference.getString("last_play_music", ""); if(!last_play.equals("")){ if(playlist != null){ try{ playlist.goMusic(new RuuFile(getApplicationContext(), last_play)); }catch(RuuFileBase.CanNotOpen | Playlist.NotFound e){ playlist = null; } }else{ try{ playlist = Playlist.getByMusicPath(getApplicationContext(), last_play); }catch(RuuFileBase.CanNotOpen | Playlist.EmptyDirectory e){ playlist = null; } } if(playlist != null){ load(new MediaPlayer.OnPreparedListener(){ @Override public void onPrepared(@Nullable MediaPlayer mp){ ready = true; player.seekTo(preference.getInt("last_play_position", 0)); if(loadingWait){ play(); loadingWait = false; }else{ sendStatus(); } } }); } } player.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){ @Override public void onCompletion(@Nullable MediaPlayer mp){ if(repeatMode.equals("one")){ player.pause(); play(); }else{ try{ playlist.goNext(); playCurrent(); }catch(Playlist.EndOfList e){ if(repeatMode.equals("off")){ player.pause(); player.seekTo(0); pause(); }else{ if(shuffleMode){ playlist.shuffle(false); }else{ playlist.goFirst(); } playCurrent(); } } } } }); player.setOnErrorListener(new MediaPlayer.OnErrorListener(){ @Override public boolean onError(@Nullable MediaPlayer mp, int what, int extra){ player.reset(); if(!errored && playlist != null){ String realName = playlist.getCurrent().getRealPath(); Intent sendIntent = new Intent(); sendIntent.setAction(ACTION_FAILED_PLAY); sendIntent.putExtra("path", (realName == null ? playlist.getCurrent().getFullPath() : realName)); getBaseContext().sendBroadcast(sendIntent); sendStatus(); if(!errorSE.isPlaying()){ errorSE.start(); } } ready = false; errored = true; removePlayingNotification(); return true; } }); registerReceiver(broadcastReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)); updateAudioEffect(); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).registerOnSharedPreferenceChangeListener(this); startDeathTimer(); } @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId){ if(intent != null){ switch(intent.getAction()){ case ACTION_PLAY: play(intent.getStringExtra("path")); break; case ACTION_PLAY_RECURSIVE: try{ playlist = Playlist.getRecursive(getApplicationContext(), intent.getStringExtra("path")); }catch(RuuFileBase.CanNotOpen e){ showToast(String.format(getString(R.string.cant_open_dir), intent.getStringExtra("path"))); break; }catch(Playlist.EmptyDirectory e){ showToast(String.format(getString(R.string.has_not_music), intent.getStringExtra("path"))); break; } if(shuffleMode){ playlist.shuffle(false); } playCurrent(); break; case ACTION_PLAY_SEARCH: try{ playlist = Playlist.getSearchResults(getApplicationContext(), intent.getStringExtra("path"), intent.getStringExtra("query")); }catch(RuuFileBase.CanNotOpen e){ showToast(String.format(getString(R.string.cant_open_dir), intent.getStringExtra("path"))); break; }catch(Playlist.EmptyDirectory e){ showToast(String.format(getString(R.string.has_not_music), intent.getStringExtra("path"))); break; } if(shuffleMode){ playlist.shuffle(false); } playCurrent(); break; case ACTION_PAUSE: pause(); break; case ACTION_PLAY_PAUSE: if(player.isPlaying()){ pause(); }else{ play(); } break; case ACTION_SEEK: seek(intent.getIntExtra("newtime", -1)); break; case ACTION_REPEAT: setRepeatMode(intent.getStringExtra("mode")); break; case ACTION_SHUFFLE: setShuffleMode(intent.getBooleanExtra("mode", false)); break; case ACTION_PING: sendStatus(); break; case ACTION_NEXT: next(); break; case ACTION_PREV: prev(); break; } } return START_NOT_STICKY; } @Override public void onDestroy(){ removePlayingNotification(); unregisterReceiver(broadcastReceiver); MediaButtonReceiver.onStopService(getApplicationContext()); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).unregisterOnSharedPreferenceChangeListener(this); saveStatus(); } @Override public void onSharedPreferenceChanged(@NonNull SharedPreferences preference, @NonNull String key){ if(key.startsWith(AudioPreferenceActivity.PREFERENCE_PREFIX)){ updateAudioEffect(); }else if(key.equals("root_directory")){ updateRoot(); } } private void sendStatus(){ Intent sendIntent = new Intent(); sendIntent.setAction(ACTION_STATUS); sendIntent.putExtra("repeat", repeatMode); sendIntent.putExtra("shuffle", shuffleMode); if(playlist != null){ sendIntent.putExtra("path", playlist.getCurrent().getFullPath()); sendIntent.putExtra("recursivePath", playlist.type == Playlist.Type.RECURSIVE ? playlist.path.getFullPath() : null); sendIntent.putExtra("searchPath", playlist.type == Playlist.Type.SEARCH ? playlist.path.getFullPath() : null); sendIntent.putExtra("searchQuery", playlist.query); } if(ready){ sendIntent.putExtra("playing", player.isPlaying()); sendIntent.putExtra("duration", player.getDuration()); sendIntent.putExtra("current", player.getCurrentPosition()); sendIntent.putExtra("basetime", System.currentTimeMillis() - player.getCurrentPosition()); } getBaseContext().sendBroadcast(sendIntent); } private void saveStatus(){ if(playlist != null){ PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() .putString("last_play_music", playlist.getCurrent().getFullPath()) .putInt("last_play_position", player.getCurrentPosition()) .putString("recursive_path", playlist.type == Playlist.Type.RECURSIVE ? playlist.path.getFullPath() : null) .putString("search_query", playlist.query) .putString("search_path", playlist.type == Playlist.Type.SEARCH ? playlist.path.getFullPath() : null) .apply(); } } private void removeSavedStatus(){ PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() .putString("last_play_music", "") .putInt("last_play_position", 0) .putString("recursive_path", null) .apply(); } @NonNull private Notification makeNotification(){ int playpause_icon = player.isPlaying() ? R.drawable.ic_pause_for_notif : R.drawable.ic_play_for_notif; String playpause_text = player.isPlaying() ? "pause" : "play"; PendingIntent playpause_pi = PendingIntent.getService(getApplicationContext(), 0, (new Intent(getApplicationContext(), RuuService.class)).setAction(player.isPlaying() ? ACTION_PAUSE : ACTION_PLAY), 0); PendingIntent prev_pi = PendingIntent.getService(getApplicationContext(), 0, (new Intent(getApplicationContext(), RuuService.class)).setAction(ACTION_PREV), 0); PendingIntent next_pi = PendingIntent.getService(getApplicationContext(), 0, (new Intent(getApplicationContext(), RuuService.class)).setAction(ACTION_NEXT), 0); Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.setAction(MainActivity.ACTION_OPEN_PLAYER); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); String parentPath; try{ parentPath = playlist.path.getRuuPath(); }catch(RuuFileBase.OutOfRootDirectory e){ parentPath = ""; } return new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(R.drawable.ic_play_notification) .setColor(0xff333333) .setTicker(playlist.getCurrent().getName()) .setContentTitle(playlist.getCurrent().getName()) .setContentText(parentPath) .setContentIntent(contentIntent) .setPriority(Notification.PRIORITY_MIN) .setVisibility(Notification.VISIBILITY_PUBLIC) .setCategory(Notification.CATEGORY_TRANSPORT) .addAction(R.drawable.ic_prev_for_notif, "prev", prev_pi) .addAction(playpause_icon, playpause_text, playpause_pi) .addAction(R.drawable.ic_next_for_notif, "next", next_pi) .build(); } private void updatePlayingNotification(){ if(!player.isPlaying()){ return; } startForeground(1, makeNotification()); } private void removePlayingNotification(){ if(player.isPlaying()){ return; } stopForeground(true); if(Build.VERSION.SDK_INT >= 16 && playlist != null){ ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).notify(1, makeNotification()); } } private void updateMediaMetadata(){ if(remoteControlClient != null && Build.VERSION.SDK_INT >= 14){ String pathStr; try{ pathStr = playlist.path.getRuuPath(); }catch(RuuFileBase.OutOfRootDirectory e){ pathStr = ""; } remoteControlClient.editMetadata(true) .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playlist.getCurrent().getName()) .putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, player.getDuration()) .putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, pathStr) .apply(); remoteControlClient.setPlaybackState(player.isPlaying() ? RemoteControlClient.PLAYSTATE_PLAYING : RemoteControlClient.PLAYSTATE_PAUSED); } } private void updateRoot(){ RuuDirectory root; try{ root = RuuDirectory.rootDirectory(getApplicationContext()); }catch(RuuFileBase.CanNotOpen e){ root = null; } if(playlist != null && (root == null || !root.contains(playlist.path))){ if(player.isPlaying()){ stopForeground(true); }else{ ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1); } player.reset(); removeSavedStatus(); ready = false; playlist = null; sendStatus(); }else if(player.isPlaying()){ updatePlayingNotification(); updateMediaMetadata(); }else{ ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1); } } private void play(){ if(playlist != null){ if(ready){ errored = false; ((AudioManager)getSystemService(Context.AUDIO_SERVICE)).requestAudioFocus(focusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); player.start(); sendStatus(); updatePlayingNotification(); updateMediaMetadata(); saveStatus(); stopDeathTimer(); MediaButtonReceiver.onStartService(getApplicationContext()); }else if(!errored){ loadingWait = true; }else{ playCurrent(); } } } private void play(@Nullable String path){ if(path == null){ play(); return; } if(playlist != null && playlist.type == Playlist.Type.SIMPLE){ RuuFile file; try{ file = new RuuFile(getApplicationContext(), path); }catch(RuuFileBase.CanNotOpen e){ showToast(String.format(getString(R.string.cant_open_dir), path)); return; } if(playlist.getCurrent().equals(file)){ if(ready){ if(player.isPlaying()){ player.pause(); } player.seekTo(0); play(); return; }else if(!errored){ loadingWait = true; return; } } } try{ playlist = Playlist.getByMusicPath(getApplicationContext(), path); }catch(RuuFileBase.CanNotOpen e){ showToast(String.format(getString(R.string.cant_open_dir), e.path)); return; }catch(Playlist.EmptyDirectory e){ showToast(String.format(getString(R.string.has_not_music), path)); return; } playCurrent(); } private void playCurrent(){ if(playlist != null && (playingFromLastest || ready || errored)){ load(new MediaPlayer.OnPreparedListener(){ @Override public void onPrepared(MediaPlayer mp){ ready = true; playingFromLastest = false; errored = false; play(); } }); } } private void load(@NonNull MediaPlayer.OnPreparedListener onPrepared){ ready = false; player.reset(); String realName = playlist.getCurrent().getRealPath(); if(realName == null){ showToast(String.format(getString(R.string.music_not_found), playlist.getCurrent().getFullPath())); return; } try{ player.setDataSource(realName); player.setOnPreparedListener(onPrepared); player.prepareAsync(); }catch(IOException e){ showToast(String.format(getString(R.string.failed_open_music), realName)); } } private void pause(){ player.pause(); sendStatus(); removePlayingNotification(); updateMediaMetadata(); saveStatus(); startDeathTimer(); ((AudioManager)getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(focusListener); } private void seek(int newtime){ if(0 <= newtime && newtime <= player.getDuration()){ player.seekTo(newtime); sendStatus(); saveStatus(); } } private void setRepeatMode(@NonNull String mode){ if(mode.equals("off") || mode.equals("loop") || mode.equals("one")){ repeatMode = mode; sendStatus(); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() .putString("repeat_mode", repeatMode) .apply(); } } private void setShuffleMode(boolean mode){ if(playlist != null){ if(mode){ playlist.shuffle(true); }else{ playlist.sort(); } } shuffleMode = mode; sendStatus(); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() .putBoolean("shuffle_mode", shuffleMode) .apply(); } private void next(){ if(playlist != null){ try{ playlist.goNext(); playCurrent(); }catch(Playlist.EndOfList e){ if(repeatMode.equals("loop")){ if(shuffleMode){ playlist.shuffle(false); }else{ playlist.goFirst(); } playCurrent(); }else{ showToast(getString(R.string.last_of_directory)); if(!endOfListSE.isPlaying()){ endOfListSE.start(); } } } } } private void prev(){ if(playlist != null){ if(player.getCurrentPosition() >= 3000){ seek(0); }else{ try{ playlist.goPrev(); playCurrent(); }catch(Playlist.EndOfList e){ if(repeatMode.equals("loop")){ if(shuffleMode){ playlist.shuffle(false); }else{ playlist.goLast(); } playCurrent(); }else{ showToast(getString(R.string.first_of_directory)); if(!endOfListSE.isPlaying()){ endOfListSE.start(); } } } } } } private void showToast(@NonNull final String message){ final Handler handler = new Handler(); (new Thread(new Runnable(){ @Override public void run(){ handler.post(new Runnable(){ @Override public void run(){ Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } }); } })).start(); } private void startDeathTimer(){ stopDeathTimer(); final Handler handler = new Handler(); deathTimer = new Timer(true); deathTimer.schedule(new TimerTask(){ @Override public void run(){ handler.post(new Runnable(){ @Override public void run(){ if(!player.isPlaying()){ stopSelf(); } } }); } }, 60 * 1000); } private void stopDeathTimer(){ if(deathTimer != null){ deathTimer.cancel(); deathTimer = null; } } private void updateAudioEffect(){ if(getPreference(AudioPreferenceActivity.PREFERENCE_BASSBOOST_ENABLED, false)){ if(bassBoost == null){ bassBoost = new BassBoost(0, player.getAudioSessionId()); } bassBoost.setStrength((short)getPreference(AudioPreferenceActivity.PREFERENCE_BASSBOOST_LEVEL, 0)); bassBoost.setEnabled(true); }else if(bassBoost != null){ bassBoost.release(); bassBoost = null; } if(getPreference(AudioPreferenceActivity.PREFERENCE_REVERB_ENABLED, false)){ if(presetReverb == null){ presetReverb = new PresetReverb(0, player.getAudioSessionId()); } presetReverb.setPreset((short)getPreference(AudioPreferenceActivity.PREFERENCE_REVERB_TYPE, 0)); presetReverb.setEnabled(true); }else if(presetReverb != null){ presetReverb.release(); presetReverb = null; } if(Build.VERSION.SDK_INT >= 19 && getPreference(AudioPreferenceActivity.PREFERENCE_LOUDNESS_ENABLED, false)){ if(loudnessEnhancer == null){ loudnessEnhancer = new LoudnessEnhancer(player.getAudioSessionId()); } loudnessEnhancer.setTargetGain(getPreference(AudioPreferenceActivity.PREFERENCE_LOUDNESS_LEVEL, 0)); loudnessEnhancer.setEnabled(true); }else if(loudnessEnhancer != null){ loudnessEnhancer.release(); loudnessEnhancer = null; } if(getPreference(AudioPreferenceActivity.PREFERENCE_EQUALIZER_ENABLED, false)){ if(equalizer == null){ equalizer = new Equalizer(0, player.getAudioSessionId()); } for(short i=0; i<equalizer.getNumberOfBands(); i++){ equalizer.setBandLevel(i, (short)getPreference(AudioPreferenceActivity.PREFERENCE_EQUALIZER_VALUE + i, (equalizer.getBandLevelRange()[0] + equalizer.getBandLevelRange()[1])/2)); } equalizer.setEnabled(true); }else if(equalizer != null){ equalizer.release(); equalizer = null; } } private boolean getPreference(@NonNull String key, boolean default_value){ return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(key, default_value); } private int getPreference(@NonNull String key, int default_value){ return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt(key, default_value); } private final AudioManager.OnAudioFocusChangeListener focusListener = new AudioManager.OnAudioFocusChangeListener(){ @Override public void onAudioFocusChange(int focusChange){ if(focusChange == AudioManager.AUDIOFOCUS_LOSS){ pause(); } } }; private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){ @Override public void onReceive(@Nullable Context context, @NonNull Intent intent){ if(intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)){ pause(); } } }; public static class MediaButtonReceiver extends BroadcastReceiver{ private static ComponentName componentName; private static boolean serviceRunning = false; private static boolean activityRunning = false; @Override @WorkerThread public void onReceive(@NonNull Context context, @NonNull Intent intent){ if(intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)){ KeyEvent keyEvent = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if(keyEvent.getAction() != KeyEvent.ACTION_UP){ return; } switch(keyEvent.getKeyCode()){ case KeyEvent.KEYCODE_MEDIA_PLAY: sendIntent(context, ACTION_PLAY); break; case KeyEvent.KEYCODE_MEDIA_PAUSE: sendIntent(context, ACTION_PAUSE); break; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: case KeyEvent.KEYCODE_HEADSETHOOK: sendIntent(context, ACTION_PLAY_PAUSE); break; case KeyEvent.KEYCODE_MEDIA_NEXT: sendIntent(context, ACTION_NEXT); break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: sendIntent(context, ACTION_PREV); break; } } } @WorkerThread private void sendIntent(@NonNull Context context, @NonNull String event){ context.startService((new Intent(context, RuuService.class)).setAction(event)); } private static void registation(@NonNull Context context){ if(componentName == null){ AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); componentName = new ComponentName(context.getPackageName(), MediaButtonReceiver.class.getName()); audioManager.registerMediaButtonEventReceiver(componentName); if(Build.VERSION.SDK_INT >= 14 && remoteControlClient == null){ Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(componentName); remoteControlClient = new RemoteControlClient(PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0)); remoteControlClient.setTransportControlFlags( RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS); audioManager.registerRemoteControlClient(remoteControlClient); } } } @WorkerThread public static void onStartService(@NonNull Context context){ serviceRunning = true; registation(context); } @UiThread public static void onStartActivity(@NonNull Context context){ activityRunning = true; registation(context); } private static void unregistation(@NonNull Context context){ if(componentName != null && !serviceRunning && !activityRunning){ AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); audioManager.unregisterMediaButtonEventReceiver(componentName); componentName = null; if(remoteControlClient != null && Build.VERSION.SDK_INT >= 14){ audioManager.unregisterRemoteControlClient(remoteControlClient); remoteControlClient = null; } } } @WorkerThread public static void onStopService(@NonNull Context context){ serviceRunning = false; unregistation(context); } @UiThread public static void onStopActivity(@NonNull Context context){ activityRunning = false; unregistation(context); } } }
package com.martin.knowledgebase; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Path; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.RelativeLayout; import android.widget.TextView; public class Snackbar { private RelativeLayout mSnackbar; private TextView mSnackButton, mSnackText; private Context mContext; private boolean mVisible; public Snackbar(RelativeLayout snackbar, String text, Context context) { mSnackbar = snackbar; mSnackButton = (TextView) mSnackbar.findViewById(R.id.snackbar_button); mSnackText = (TextView) mSnackbar.findViewById(R.id.snackbar_text); mSnackText.setText(text); mContext = context; mSnackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { hideSnackbar(); } }); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, mContext.getResources().getDisplayMetrics()); mSnackbar.setY(mSnackbar.getY() + px); mSnackbar.setVisibility(View.VISIBLE); mVisible = false; } public Snackbar(RelativeLayout snackbar, Context context) { mSnackbar = snackbar; mSnackButton = (TextView) mSnackbar.findViewById(R.id.snackbar_button); mSnackText = (TextView) mSnackbar.findViewById(R.id.snackbar_text); mContext = context; mSnackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { hideSnackbar(); } }); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, mContext.getResources().getDisplayMetrics()); mSnackbar.setY(mSnackbar.getY() + px); mSnackbar.setVisibility(View.VISIBLE); mVisible = false; } public void show() { if (mContext != null) { if (!mVisible) { float px = -TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, mContext.getResources().getDisplayMetrics()); moveSnackbar(px); mVisible = true; } } else { Log.e("Snackbar", "Reference to old Context - reinstantiate Snackbar with current Context"); } } public void setText(String text) { mSnackText.setText(text); } public void hideSnackbar() { if (mContext != null) { float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, mContext.getResources().getDisplayMetrics()); moveSnackbar(px); mVisible = false; } else { Log.e("Snackbar", "Reference to old Context - reinstantiate Snackbar with current Context"); } } private void moveSnackbar(float px) { Path p = new Path(); ObjectAnimator sbAnimator; p.moveTo(mSnackbar.getX(), mSnackbar.getY()); p.rLineTo(0, px); sbAnimator = ObjectAnimator.ofFloat(mSnackbar, View.X, View.Y, p); sbAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); sbAnimator.start(); } }
package cgeo.geocaching.connector.gc; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.settings.Settings; import android.graphics.Bitmap; /** * icon decoder for cache icons * */ final class IconDecoder { private static final int CT_TRADITIONAL = 0; private static final int CT_MULTI = 1; private static final int CT_MYSTERY = 2; private static final int CT_EVENT = 3; private static final int CT_EARTH = 4; private static final int CT_FOUND = 5; private static final int CT_OWN = 6; private static final int CT_CITO = 7; private static final int CT_WEBCAM = 8; private static final int CT_MEGAEVENT = 9; private static final int CT_WHERIGO = 10; private static final int CT_VIRTUAL = 11; private static final int CT_LETTERBOX = 12; private IconDecoder() { throw new IllegalStateException("utility class"); } static boolean parseMapPNG(final Geocache cache, final Bitmap bitmap, final UTFGridPosition xy, final int zoomlevel) { final int topX = xy.getX() * 4; final int topY = xy.getY() * 4; final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); if ((topX < 0) || (topY < 0) || (topX + 4 > bitmapWidth) || (topY + 4 > bitmapHeight)) { return false; //out of image position } int numberOfDetections = 9; //for level 12 and 13 if (zoomlevel < 12) { numberOfDetections = 5; } if (zoomlevel > 13) { numberOfDetections = 9; } final int[] pngType = new int[numberOfDetections]; for (int x = topX; x < topX + 4; x++) { for (int y = topY; y < topY + 4; y++) { final int color = bitmap.getPixel(x, y); if ((color >>> 24) != 255) { continue; //transparent pixels (or semi_transparent) are only shadows of border } final int r = (color & 0xFF0000) >> 16; final int g = (color & 0xFF00) >> 8; final int b = color & 0xFF; if (isPixelDuplicated(r, g, b, zoomlevel)) { continue; } final int type; if (zoomlevel < 12) { type = getCacheTypeFromPixel11(r, g, b); } else if (zoomlevel > 13) { type = getCacheTypeFromPixel14(r, g, b); } else { type = getCacheTypeFromPixel13(r, g, b); } pngType[type]++; } } int type = -1; int count = 0; for (int x = 0; x < pngType.length; x++) { if (pngType[x] > count) { count = pngType[x]; type = x; } } if (count > 1) { // 2 pixels need to detect same type and we say good to go switch (type) { case CT_TRADITIONAL: cache.setType(CacheType.TRADITIONAL, zoomlevel); return true; case CT_MULTI: cache.setType(CacheType.MULTI, zoomlevel); return true; case CT_MYSTERY: cache.setType(CacheType.MYSTERY, zoomlevel); return true; case CT_EVENT: cache.setType(CacheType.EVENT, zoomlevel); return true; case CT_EARTH: cache.setType(CacheType.EARTH, zoomlevel); return true; case CT_FOUND: cache.setFound(true); return true; case CT_OWN: cache.setOwnerUserId(Settings.getUserName()); return true; case CT_MEGAEVENT: cache.setType(CacheType.MEGA_EVENT, zoomlevel); return true; case CT_CITO: cache.setType(CacheType.CITO, zoomlevel); return true; case CT_WEBCAM: cache.setType(CacheType.WEBCAM, zoomlevel); return true; case CT_WHERIGO: cache.setType(CacheType.WHERIGO, zoomlevel); return true; case CT_VIRTUAL: cache.setType(CacheType.VIRTUAL, zoomlevel); return true; case CT_LETTERBOX: cache.setType(CacheType.LETTERBOX, zoomlevel); return true; } } return false; } /** * A method that returns true if pixel color appears on more than one cache type and shall be excluded from parsing * * @param r * red value * @param g * green value * @param b * blue value * @param zoomlevel * zoom level of map * @return true if parsing should not be performed */ private static boolean isPixelDuplicated(final int r, final int g, final int b, final int zoomlevel) { if ((r == g) && (g == b)) { return true; } if (zoomlevel < 12) { return false; } if (zoomlevel > 13) { if ((r == 252) && (b == 252) && (g == 251) || (r == 206) && (b == 219) && (g == 230) || (r == 178) && (b == 198) && (g == 215) || (r == 162) && (b == 186) && (g == 209) || (r == 187) && (b == 205) && (g == 222) || (r == 216) && (b == 226) && (g == 235) || (r == 253) && (b == 254) && (g == 254) || (r == 243) && (b == 247) && (g == 249) || (r == 136) && (b == 166) && (g == 195) || (r == 254) && (b == 255) && (g == 255) || (r == 222) && (b == 231) && (g == 239) || (r == 240) && (b == 244) && (g == 248) || (r == 194) && (b == 209) && (g == 221) || (r == 153) && (b == 178) && (g == 199) || (r == 228) && (b == 238) && (g == 242) || (r == 109) && (b == 165) && (g == 141) || (r == 124) && (b == 194) && (g == 165) || (r == 206) && (b == 229) && (g == 220) || (r == 199) && (b == 224) && (g == 210) || (r == 252) && (b == 253) && (g == 254) || (r == 244) && (b == 247) && (g == 243) || (r == 197) && (b == 212) && (g == 227) || (r == 171) && (b == 172) && (g == 172) || (r == 160) && (b == 161) && (g == 161) || (r == 232) && (b == 249) && (g == 250) || (r == 253) && (b == 241) && (g == 227) || (r == 254) && (b == 248) && (g == 240) || (r == 72) && (b == 112) && (g == 48) || (r == 251) && (b == 239) && (g == 217) || (r == 214) && (b == 239) && (g == 244) || (r == 202) && (b == 214) && (g == 194) || (r == 168) && (b == 186) && (g == 156) || (r == 254) && (b == 249) && (g == 247) || (r == 132) && (b == 166) && (g == 130) || (r == 238) && (b == 238) && (g == 233) || (r == 241) && (b == 252) && (g == 253) || (r == 101) && (b == 135) && (g == 80) || (r == 193) && (b == 208) && (g == 184) || (r == 251) && (b == 253) && (g == 252)) { return true; } return false; } //zoom level 12, 13 if ((r == 247) && (b == 249) && (g == 251) || (r == 253) && (b == 254) && (g == 254) || (r == 252) && (b == 253) && (g == 254) || (r == 241) && (b == 249) && (g == 251) || (r == 249) && (b == 252) && (g == 253) || (r == 251) && (b == 253) && (g == 253) || (r == 254) && (b == 253) && (g == 253)) { return true; } return false; } private static int getCacheTypeFromPixel13(final int r, final int g, final int b) { if (b < 139) { if (r < 115) { if (b < 82) { if (r < 63) { if (r < 20) { if (r < 4) { return g < 137 ? CT_TRADITIONAL : CT_CITO; } return g < 150 ? CT_TRADITIONAL : CT_CITO; } return CT_EARTH; } if (g < 149) { return r < 88 ? CT_EARTH : CT_FOUND; } return CT_EVENT; } if (g < 138) { if (r < 37) { return CT_CITO; } if (b < 126) { if (r < 72) { if (r < 44) { return g < 90 ? CT_EVENT : CT_CITO; } return CT_EVENT; } return CT_EARTH; } if (g < 90) { return CT_EVENT; } return g < 120 ? CT_CITO : CT_EVENT; } if (g < 166) { return r < 75 ? CT_TRADITIONAL : CT_EARTH; } if (r < 62) { if (g < 175) { return CT_CITO; } return r < 48 ? CT_OWN : CT_CITO; } return g < 184 ? CT_TRADITIONAL : CT_CITO; } if (r < 201) { if (g < 118) { return r < 141 ? CT_FOUND : CT_EVENT; } if (g < 170) { if (r < 150) { return g < 146 ? CT_FOUND : CT_EARTH; } return r < 192 ? CT_FOUND : CT_EVENT; } return CT_EVENT; } if (g < 183) { return CT_MULTI; } if (r < 239) { return CT_FOUND; } if (g < 210) { return r < 246 ? CT_MULTI : CT_EARTH; } return b < 66 ? CT_FOUND : CT_EARTH; } if (r < 234) { if (r < 86) { if (b < 180) { if (b < 151) { if (r < 55) { return g < 75 ? CT_EVENT : CT_MYSTERY; } return g < 160 ? CT_CITO : CT_OWN; } return g < 92 ? CT_EVENT : CT_MYSTERY; } return CT_WEBCAM; } if (b < 211) { if (r < 164) { if (g < 179) { if (b < 173) { if (r < 98) { return CT_CITO; } if (g < 160) { return CT_EVENT; } return r < 133 ? CT_EARTH : CT_EVENT; } if (b < 185) { if (r < 117) { return CT_MYSTERY; } return g < 154 ? CT_EVENT : CT_CITO; } if (b < 196) { return r < 141 ? CT_MYSTERY : CT_CITO; } return CT_MYSTERY; } if (g < 206) { if (b < 181) { if (g < 189) { return r < 121 ? CT_TRADITIONAL : CT_EARTH; } return b < 155 ? CT_CITO : CT_TRADITIONAL; } if (g < 188) { return b < 204 ? CT_CITO : CT_MYSTERY; } return CT_EARTH; } if (g < 210) { return g < 208 ? CT_OWN : CT_CITO; } if (r < 155) { if (g < 215) { return r < 121 ? CT_OWN : CT_CITO; } return CT_OWN; } return CT_CITO; } if (r < 193) { if (b < 192) { if (g < 175) { return b < 176 ? CT_FOUND : CT_EVENT; } if (b < 171) { return CT_EVENT; } return r < 167 ? CT_EARTH : CT_EVENT; } if (g < 204) { return b < 199 ? CT_EVENT : CT_CITO; } if (g < 226) { if (r < 186) { return CT_TRADITIONAL; } return g < 218 ? CT_EARTH : CT_TRADITIONAL; } return r < 179 ? CT_OWN : CT_CITO; } if (g < 208) { if (g < 180) { return CT_EVENT; } if (r < 198) { return r < 196 ? CT_FOUND : CT_EVENT; } return CT_FOUND; } if (g < 215) { return r < 207 ? CT_EVENT : CT_FOUND; } if (b < 199) { return CT_EVENT; } return r < 218 ? CT_EARTH : CT_EVENT; } if (r < 174) { if (r < 156) { return CT_WEBCAM; } if (g < 201) { return CT_MYSTERY; } if (b < 228) { return CT_EARTH; } if (r < 173) { return CT_WEBCAM; } return g < 221 ? CT_EARTH : CT_WEBCAM; } if (b < 227) { if (g < 222) { if (r < 188) { return b < 214 ? CT_CITO : CT_MYSTERY; } return b < 224 ? CT_CITO : CT_MYSTERY; } if (r < 210) { if (g < 235) { return g < 233 ? CT_TRADITIONAL : CT_CITO; } return CT_OWN; } return r < 216 ? CT_TRADITIONAL : CT_EARTH; } if (r < 208) { if (g < 219) { return CT_MYSTERY; } if (b < 240) { if (r < 190) { return b < 233 ? CT_EARTH : CT_WEBCAM; } return CT_EARTH; } return CT_WEBCAM; } if (g < 233) { if (b < 233) { return r < 210 ? CT_MYSTERY : CT_CITO; } if (r < 221) { return CT_MYSTERY; } return b < 239 ? CT_CITO : CT_MYSTERY; } if (b < 243) { if (g < 241) { if (r < 226) { return CT_EARTH; } if (r < 228) { return CT_CITO; } return r < 229 ? CT_MYSTERY : CT_EARTH; } if (r < 221) { return CT_OWN; } return r < 230 ? CT_CITO : CT_TRADITIONAL; } if (r < 224) { if (b < 244) { return r < 216 ? CT_WEBCAM : CT_EARTH; } return CT_WEBCAM; } return g < 241 ? CT_MYSTERY : CT_EARTH; } if (b < 230) { if (r < 246) { if (b < 206) { if (r < 243) { if (r < 240) { return g < 226 ? CT_EARTH : CT_EVENT; } return CT_EARTH; } return g < 216 ? CT_MULTI : CT_EARTH; } if (b < 219) { if (r < 243) { if (r < 237) { return g < 235 ? CT_EVENT : CT_EARTH; } return CT_EVENT; } return CT_EARTH; } return g < 236 ? CT_FOUND : CT_EVENT; } if (g < 220) { return CT_MULTI; } if (g < 243) { if (r < 249) { return CT_EARTH; } if (r < 251) { return CT_MULTI; } return b < 185 ? CT_EARTH : CT_MULTI; } return CT_EARTH; } if (r < 249) { if (b < 242) { if (r < 246) { if (r < 240) { return CT_TRADITIONAL; } return g < 237 ? CT_EVENT : CT_FOUND; } return CT_EVENT; } if (b < 249) { if (g < 245) { if (b < 245) { return CT_CITO; } if (g < 243) { return CT_MYSTERY; } return b < 247 ? CT_CITO : CT_MYSTERY; } if (b < 248) { if (g < 250) { if (r < 236) { return CT_OWN; } if (r < 246) { if (g < 246) { return CT_EARTH; } if (r < 243) { return CT_TRADITIONAL; } return r < 244 ? CT_EARTH : CT_TRADITIONAL; } return CT_EARTH; } return CT_OWN; } return CT_CITO; } if (g < 249) { return r < 241 ? CT_WEBCAM : CT_MYSTERY; } return CT_WEBCAM; } if (r < 253) { if (b < 252) { if (b < 248) { return CT_EVENT; } return r < 251 ? CT_FOUND : CT_EVENT; } if (b < 254) { if (g < 253) { return r < 252 ? CT_CITO : CT_MYSTERY; } return CT_OWN; } return CT_EARTH; } if (g < 250) { if (g < 249) { return CT_MULTI; } return b < 240 ? CT_EARTH : CT_MULTI; } if (b < 249) { if (b < 243) { return CT_EARTH; } return g < 253 ? CT_MULTI : CT_EARTH; } if (b < 253) { return CT_EVENT; } if (g < 254) { return CT_MYSTERY; } if (b < 255) { return r < 255 ? CT_MULTI : CT_EARTH; } return CT_EARTH; } private static int getCacheTypeFromPixel14(final int r, final int g, final int b) { if (b < 150) { if (r < 118) { if (b < 93) { if (r < 69) { if (b < 74) { return r < 68 ? CT_EARTH : CT_TRADITIONAL; } if (r < 3) { if (b < 78) { return g < 146 ? CT_TRADITIONAL : CT_CITO; } return CT_CITO; } return g < 151 ? CT_TRADITIONAL : CT_CITO; } if (g < 138) { if (r < 100) { return r < 85 ? CT_EARTH : CT_TRADITIONAL; } return CT_FOUND; } if (g < 145) { return r < 94 ? CT_EVENT : CT_TRADITIONAL; } return CT_EVENT; } if (g < 152) { if (b < 122) { if (r < 50) { if (r < 40) { return CT_CITO; } return r < 46 ? CT_EVENT : CT_CITO; } if (g < 133) { return CT_EVENT; } return r < 109 ? CT_EARTH : CT_TRADITIONAL; } if (r < 46) { if (g < 79) { return CT_EVENT; } return b < 133 ? CT_EVENT : CT_MYSTERY; } if (r < 79) { return CT_CITO; } return r < 81 ? CT_EVENT : CT_CITO; } if (g < 175) { if (g < 163) { return r < 81 ? CT_TRADITIONAL : CT_EARTH; } return b < 110 ? CT_CITO : CT_TRADITIONAL; } if (r < 44) { return CT_OWN; } if (g < 184) { return b < 130 ? CT_CITO : CT_TRADITIONAL; } return g < 197 ? CT_CITO : CT_OWN; } if (g < 160) { if (g < 93) { return CT_EVENT; } if (r < 182) { if (r < 132) { if (g < 130) { return CT_FOUND; } return b < 60 ? CT_OWN : CT_TRADITIONAL; } return CT_FOUND; } return b < 80 ? CT_MULTI : CT_EVENT; } if (b < 58) { if (r < 238) { return r < 162 ? CT_OWN : CT_FOUND; } return g < 209 ? CT_EARTH : CT_FOUND; } if (r < 233) { if (g < 191) { if (r < 147) { return b < 139 ? CT_EVENT : CT_EARTH; } return b < 116 ? CT_OWN : CT_TRADITIONAL; } if (r < 176) { return CT_EVENT; } return g < 211 ? CT_OWN : CT_EVENT; } if (g < 204) { if (b < 105) { return g < 192 ? CT_MULTI : CT_EARTH; } return CT_MULTI; } if (r < 246) { if (r < 245) { return CT_EARTH; } return g < 213 ? CT_EARTH : CT_EVENT; } return CT_EARTH; } if (r < 192) { if (b < 197) { if (r < 80) { if (b < 178) { if (g < 95) { return CT_EVENT; } if (r < 58) { return CT_MYSTERY; } return b < 158 ? CT_EVENT : CT_MYSTERY; } return CT_WEBCAM; } if (g < 171) { if (b < 172) { if (r < 149) { if (g < 136) { return r < 96 ? CT_CITO : CT_EVENT; } return CT_CITO; } return CT_FOUND; } if (b < 188) { if (r < 118) { return g < 128 ? CT_EVENT : CT_MYSTERY; } if (r < 142) { return g < 151 ? CT_EVENT : CT_CITO; } return CT_EVENT; } if (b < 190) { return r < 132 ? CT_MYSTERY : CT_CITO; } return CT_MYSTERY; } if (g < 194) { if (r < 142) { if (r < 123) { return g < 179 ? CT_EARTH : CT_TRADITIONAL; } return CT_EARTH; } if (b < 176) { return CT_EARTH; } return r < 165 ? CT_CITO : CT_EVENT; } if (r < 172) { if (g < 206) { if (b < 161) { return r < 138 ? CT_CITO : CT_EVENT; } return CT_TRADITIONAL; } if (r < 149) { if (r < 126) { return CT_OWN; } return r < 140 ? CT_CITO : CT_OWN; } if (g < 216) { return b < 183 ? CT_CITO : CT_TRADITIONAL; } return CT_CITO; } if (b < 179) { return g < 199 ? CT_TRADITIONAL : CT_EVENT; } return CT_EARTH; } if (b < 216) { if (r < 125) { return CT_WEBCAM; } if (g < 212) { if (r < 158) { return g < 191 ? CT_MYSTERY : CT_EARTH; } if (b < 210) { return CT_CITO; } return r < 178 ? CT_MYSTERY : CT_CITO; } if (g < 224) { return CT_TRADITIONAL; } return g < 227 ? CT_CITO : CT_OWN; } if (r < 156) { return CT_WEBCAM; } if (b < 229) { if (r < 175) { if (r < 160) { return g < 214 ? CT_EARTH : CT_WEBCAM; } return CT_EARTH; } return CT_MYSTERY; } if (r < 174) { return CT_WEBCAM; } if (b < 234) { if (r < 176) { return g < 222 ? CT_EARTH : CT_WEBCAM; } return CT_EARTH; } return CT_WEBCAM; } if (b < 212) { if (r < 240) { if (g < 209) { if (r < 215) { if (g < 173) { return CT_EVENT; } if (b < 197) { return CT_FOUND; } return r < 211 ? CT_EVENT : CT_FOUND; } return CT_EVENT; } if (b < 199) { if (b < 163) { return CT_OWN; } if (b < 198) { if (g < 227) { return CT_EVENT; } return b < 189 ? CT_OWN : CT_EVENT; } return CT_OWN; } if (r < 221) { if (r < 201) { return CT_EARTH; } if (r < 216) { return r < 210 ? CT_EVENT : CT_TRADITIONAL; } return CT_FOUND; } return CT_EVENT; } if (g < 224) { if (r < 246) { return b < 171 ? CT_EARTH : CT_EVENT; } return CT_MULTI; } if (g < 235) { return b < 194 ? CT_EARTH : CT_MULTI; } return CT_EARTH; } if (r < 239) { if (b < 235) { if (r < 222) { if (g < 226) { if (b < 225) { return g < 220 ? CT_CITO : CT_EARTH; } if (r < 203) { return CT_MYSTERY; } return b < 233 ? CT_CITO : CT_MYSTERY; } if (g < 236) { if (b < 231) { if (r < 216) { return CT_TRADITIONAL; } return r < 219 ? CT_EARTH : CT_TRADITIONAL; } return CT_CITO; } return g < 241 ? CT_CITO : CT_OWN; } if (g < 234) { if (g < 227) { return CT_FOUND; } return r < 231 ? CT_TRADITIONAL : CT_FOUND; } if (r < 232) { return CT_TRADITIONAL; } return b < 221 ? CT_EVENT : CT_EARTH; } if (r < 215) { if (b < 243) { if (r < 198) { return b < 238 ? CT_EARTH : CT_WEBCAM; } if (r < 201) { return b < 240 ? CT_EARTH : CT_WEBCAM; } return CT_EARTH; } return CT_WEBCAM; } if (b < 247) { if (r < 229) { if (g < 236) { return g < 231 ? CT_MYSTERY : CT_CITO; } if (b < 244) { return CT_EARTH; } return r < 225 ? CT_WEBCAM : CT_EARTH; } if (g < 244) { if (b < 239) { return CT_EARTH; } if (b < 246) { if (g < 239) { return r < 231 ? CT_CITO : CT_MYSTERY; } return CT_CITO; } return CT_MYSTERY; } return r < 233 ? CT_CITO : CT_TRADITIONAL; } if (b < 248) { return r < 230 ? CT_WEBCAM : CT_EARTH; } return CT_WEBCAM; } if (b < 245) { if (r < 251) { if (b < 223) { return g < 238 ? CT_EVENT : CT_EARTH; } if (g < 241) { return r < 242 ? CT_FOUND : CT_EVENT; } if (b < 240) { if (r < 244) { return r < 242 ? CT_OWN : CT_EARTH; } return b < 236 ? CT_EVENT : CT_OWN; } if (r < 248) { return CT_FOUND; } return b < 243 ? CT_EVENT : CT_OWN; } if (g < 246) { if (b < 239) { return r < 254 ? CT_MULTI : CT_EARTH; } return CT_EVENT; } if (b < 243) { return CT_EARTH; } return g < 251 ? CT_MULTI : CT_EARTH; } if (b < 251) { if (r < 250) { if (g < 248) { return b < 247 ? CT_FOUND : CT_MYSTERY; } if (r < 242) { return CT_OWN; } if (g < 250) { return r < 245 ? CT_TRADITIONAL : CT_MYSTERY; } return r < 248 ? CT_CITO : CT_TRADITIONAL; } if (r < 254) { if (g < 249) { return CT_EVENT; } return r < 252 ? CT_FOUND : CT_EVENT; } return CT_MULTI; } if (r < 252) { if (b < 253) { if (r < 249) { return CT_WEBCAM; } return g < 253 ? CT_CITO : CT_OWN; } if (r < 251) { return CT_WEBCAM; } return g < 253 ? CT_MYSTERY : CT_WEBCAM; } if (g < 255) { if (r < 253) { return g < 254 ? CT_MYSTERY : CT_OWN; } if (b < 255) { if (b < 253) { return CT_EVENT; } return r < 255 ? CT_MYSTERY : CT_EVENT; } return CT_MYSTERY; } if (r < 255) { return b < 255 ? CT_OWN : CT_WEBCAM; } return CT_MULTI; } private static int getCacheTypeFromPixel11(final int r, final int g, final int b) { if (r < 182) { if (b < 158) { if (g < 103) { return r < 94 ? CT_MYSTERY : CT_EVENT; } return CT_TRADITIONAL; } if (g < 149) { return CT_MYSTERY; } if (r < 143) { return CT_EARTH; } return g < 218 ? CT_MYSTERY : CT_EARTH; } if (r < 240) { if (b < 174) { return b < 27 ? CT_MULTI : CT_EVENT; } if (b < 221) { return CT_TRADITIONAL; } if (g < 239) { return CT_MYSTERY; } if (b < 241) { return CT_TRADITIONAL; } return r < 238 ? CT_EARTH : CT_MYSTERY; } if (b < 181) { return CT_MULTI; } if (r < 253) { if (b < 235) { return r < 250 ? CT_EVENT : CT_MULTI; } if (b < 247) { return r < 249 ? CT_TRADITIONAL : CT_EVENT; } if (g < 255) { return r < 242 ? CT_EARTH : CT_MYSTERY; } return CT_EARTH; } if (b < 242) { return CT_MULTI; } if (r < 255) { return g < 248 ? CT_EVENT : CT_TRADITIONAL; } if (b < 248) { return CT_MULTI; } return g < 254 ? CT_EVENT : CT_MULTI; } }
package me.dylanburton.blastarreborn; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.View; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import me.dylanburton.blastarreborn.Enemies.Enemy; import me.dylanburton.blastarreborn.Enemies.EnemyType; import me.dylanburton.blastarreborn.Enemies.Fighter; /** * Represents the main screen of play for the game. * */ public class PlayScreen extends Screen { private MainActivity act; private Paint p; //how fast the spaceship moves backwards private final int DECAY_SPEED=5; private final int LEVEL_FIGHTER = 1; // level where different ships are added private final int LEVEL_IMPERIAL = 3; private final int LEVEL_BATTLECRUISER = 4; private final int LEVEL_BATTLESHIP = 5; private final int LEVEL_BERSERKER = 6; static final long ONESEC_NANOS = 1000000000L; private enum State { RUNNING, STARTROUND, ROUNDSUMMARY, STARTGAME, PLAYERDIED, GAMEOVER } private volatile State gamestate = State.STARTGAME; //lists private List<Enemy> enemiesFlying = Collections.synchronizedList(new LinkedList<Enemy>()); // enemies that are still alive private List<ShipExplosion> shipExplosions = new LinkedList<ShipExplosion>(); // ship explosions //width and height of screen private int width = 0; private int height = 0; //bitmap with a rect used for drawing private Bitmap starbackground, spaceship[], spaceshipLaser, fighter, hitFighter, explosion[]; private Rect scaledDst = new Rect(); //main spaceships location and bound, using 1000 for spaceshipy and x because of a weird glitch where the spaceship is drawn at 0,0 for 100 ms private int spaceshipY=0; private int spaceshipX=0; private int currentSpaceshipFrame=0; //frame of spaceship for animation private Rect spaceshipBounds; private boolean spaceshipIsMoving; private int spaceshipLaserX; private int spaceshipLaserY; //used to move the background image, need two pairs of these vars for animation private int mapAnimatorX; private int mapAnimatorY; private int secondaryMapAnimatorX; private int secondaryMapAnimatorY; //time stuff private long hitContactTime = 0; //for if the laser hits the enemy private long enemyFiringTime = 0; //for controlling enemy firing private long spaceshipFrameSwitchTime = 0; //for spaceships fire animation private long frtime = 0; //the global time private long gameStartTime = 0; private int fps = 0; //various game things private int minRoundPass; private int currentLevel; private int score; private int lives; private int highscore=0, highlev=1; private static final String HIGHSCORE_FILE = "highscore.dat"; private static final int START_NUMLIVES = 3; private Map<Integer, String> levelMap = new HashMap<Integer, String>(); //some AI Movement vars, to see how it works, look in Enemy class private boolean startDelayReached = false; private Random rand = new Random(); private float randomlyGeneratedEnemyFiringTimeInSeconds; //variable for enemy firing stuff public PlayScreen(MainActivity act) { p = new Paint(); this.act = act; AssetManager assetManager = act.getAssets(); try { //background InputStream inputStream = assetManager.open("sidescrollingstars.jpg"); starbackground = BitmapFactory.decodeStream(inputStream); inputStream.close(); //your spaceship and laser spaceship = new Bitmap[2]; spaceship[0] = act.getScaledBitmap("spaceship/spaceshiptopview1.png"); spaceship[1] = act.getScaledBitmap("spaceship/spaceshiptopview2.png"); spaceshipLaser = act.getScaledBitmap("spaceshiplaser.png"); //fighter fighter = act.getScaledBitmap("fighter.png"); hitFighter = act.getScaledBitmap("hitfighter.png"); //explosion explosion = new Bitmap[12]; for(int i = 0; i < 12; i++) { explosion[i] = act.getScaledBitmap("explosion/explosion"+(i+1)+".png"); } p.setTypeface(act.getGameFont()); currentLevel = 1; } catch (IOException e) { Log.d(act.LOG_ID, "why tho?", e); } } /** * initialize and start a game */ void initGame() { //used for slight delays on spawning things at the beginning gameStartTime = System.nanoTime(); score = 0; currentLevel = 1; lives = START_NUMLIVES; highscore = 0; if(currentLevel == 1){ enemiesFlying.add(new Fighter(fighter)); enemiesFlying.add(new Fighter(fighter)); } try { BufferedReader f = new BufferedReader(new FileReader(act.getFilesDir() + HIGHSCORE_FILE)); highscore = Integer.parseInt(f.readLine()); highlev = Integer.parseInt(f.readLine()); f.close(); } catch (Exception e) { Log.d(MainActivity.LOG_ID, "ReadHighScore", e); } gamestate = State.STARTGAME; } public void resetGame(){ gamestate = State.STARTROUND; width = 0; height = 0; enemiesFlying.clear(); startDelayReached = false; for(Enemy e: enemiesFlying){ e.setFinishedVelocityChange(false); e.setAIStarted(false); } } /** * init game for current round */ private void initRound() { // how many enemies do we need to kill to progress? if (currentLevel == 1) minRoundPass = 10; else if (currentLevel < 4) minRoundPass = 30; else minRoundPass = 40; gamestate = State.RUNNING; } /** * player lost a life */ private void loseLife() { lives if (lives == 0) { // game over! wrap things up and write high score file gamestate = State.GAMEOVER; try { BufferedWriter f = new BufferedWriter(new FileWriter(act.getFilesDir() + HIGHSCORE_FILE)); f.write(Integer.toString(highscore)+"\n"); f.write(Integer.toString(highlev)+"\n"); f.close(); } catch (Exception e) { // if we can't write the high score file...oh well. Log.d(MainActivity.LOG_ID, "WriteHiScore", e); } } else gamestate = State.PLAYERDIED; } @Override public void update(View v) { long newtime = System.nanoTime(); float elapsedsecs = (float) (newtime - frtime) / ONESEC_NANOS; frtime = newtime; fps = (int) (1 / elapsedsecs); if (gamestate == State.STARTROUND) { initRound(); return; } if (width == 0) { // set variables that rely on screen size width = v.getWidth(); height = v.getHeight(); spaceshipX = width/2; spaceshipY = height*2/3; spaceshipLaserX = spaceshipX+spaceship[0].getWidth()/8; spaceshipLaserY = spaceshipY+spaceship[0].getHeight()/3; mapAnimatorX = width; mapAnimatorY = height; secondaryMapAnimatorX=width; secondaryMapAnimatorY=height; } if (gamestate == State.RUNNING) { } synchronized (enemiesFlying){ Iterator<Enemy> enemiesIterator = enemiesFlying.iterator(); while (enemiesIterator.hasNext()) { Enemy e = enemiesIterator.next(); //delay of 100 ms before enemies spawn if(gameStartTime + (ONESEC_NANOS/10) < frtime){ startDelayReached = true; } /* * Firing AI */ if(enemyFiringTime + randomlyGeneratedEnemyFiringTimeInSeconds < frtime){ enemyFiringTime = System.nanoTime(); randomlyGeneratedEnemyFiringTimeInSeconds = (rand.nextInt(3000))/1000; //todo: make a Shiplaser class and list, then have the Shiplaser object be added to the list here, then make a for each in draw() to drawBitmap the lasers, then in update, update the coordinates of enemy lasers } /* * Movement AI */ //handles collision for multiple enemies for(int i = 0; i<enemiesFlying.size(); i++){ if((e != enemiesFlying.get(i))){ if((e.getX()>= enemiesFlying.get(i).getX()-enemiesFlying.get(i).getBitmap().getWidth() && e.getX()<=enemiesFlying.get(i).getX()+enemiesFlying.get(i).getBitmap().getWidth()) && (e.getY()>=enemiesFlying.get(i).getY()-enemiesFlying.get(i).getBitmap().getHeight() && e.getY() <=enemiesFlying.get(i).getY()+enemiesFlying.get(i).getBitmap().getHeight()) ) { e.setVx(-e.getVx()); e.setVy(-e.getVy()); } } } if(!e.isAIStarted()){ e.setX(rand.nextInt(width*4/5)); e.setY(-height/10); e.setFinishedVelocityChange(true); e.setAIStarted(true); } if(startDelayReached) { e.setX(e.getX() + e.getVx()); e.setY(e.getY() + e.getVy()); } if(e.isFinishedVelocityChange()){ e.setRandomVelocityGeneratorX((rand.nextInt(10000)+1000)/1000); e.setRandomVelocityGeneratorY((rand.nextInt(10000)+1000)/1000); //makes it negative if it is bigger than 5 if(e.getRandomVelocityGeneratorX() > 5){ e.setRandomVelocityGeneratorX(e.getRandomVelocityGeneratorX() - 11); } if(e.getRandomVelocityGeneratorY() > 5){ e.setRandomVelocityGeneratorY(e.getRandomVelocityGeneratorY() - 11); } //makes the ship change direction soon if they are in a naughty area if(e.getY() > height/6){ if(e.getRandomVelocityGeneratorY() > 0){ e.setRandomVelocityGeneratorY(-e.getRandomVelocityGeneratorY()); } }else if(e.getY() < height/12){ if(e.getRandomVelocityGeneratorY() < 0){ e.setRandomVelocityGeneratorY(-e.getRandomVelocityGeneratorY()); } } if(!e.isSlowingDown()){ e.setSpeedingUp(true); } e.setFinishedRandomGeneratorsTime(System.nanoTime()); //just initiating these guys e.setLastSlowedDownVelocityTime(e.getFinishedRandomGeneratorsTime()); e.setLastSpedUpVelocityTime(e.getFinishedRandomGeneratorsTime()); e.setFinishedVelocityChange(false); } if (e.isSlowingDown() && (frtime > e.getLastSlowedDownVelocityTime() + (ONESEC_NANOS/100))) { //obv will never be 0. Half a second for slowing down, then speeding up e.setVx(e.getVx() - (e.getVx()/50)); e.setVy(e.getVy() - (e.getVy()/50)); //borders if(e.getX() < 0 || e.getX() > width*4/5){ //this check disables the ability for ship to get too far and then freeze in place if(e.getX() < 0){ e.setX(0); }else if (e.getX() > width*4/5){ e.setX(width*4/5); } e.setVx(-e.getVx()); e.setRandomVelocityGeneratorX(-e.getRandomVelocityGeneratorX()); } //so we do this if( (e.getVx() > -1 && e.getVx() < 1) && (e.getVy() > -1 && e.getVy() < 1) ){ e.setSlowingDown(false); e.setSpeedingUp(true); } //delays this slowing down process a little e.setLastSlowedDownVelocityTime(System.nanoTime()); }else if(e.isSpeedingUp() && (frtime > e.getLastSpedUpVelocityTime() + (ONESEC_NANOS/100))){ //will not have asymptotes like the last one e.setVx(e.getVx() + (e.getRandomVelocityGeneratorX()/50)); e.setVy(e.getVy() + (e.getRandomVelocityGeneratorY() /50)); //borders for x and y if(e.getX() < 0 || e.getX() > width*4/5){ //this check disables the ability for ship to get too far and then freeze in place if(e.getX() < 0){ e.setX(0); }else if (e.getX() > width*4/5){ e.setX(width*4/5); } e.setVx(-e.getVx()); e.setRandomVelocityGeneratorX(-e.getRandomVelocityGeneratorX()); } //just adding a margin of error regardless though, if the nanoseconds were slightly off it would not work if( (e.getVx() > e.getRandomVelocityGeneratorX()-1 && e.getVx() < e.getRandomVelocityGeneratorX()+1) && (e.getVy() > e.getRandomVelocityGeneratorY() -1 || e.getVy() < e.getRandomVelocityGeneratorY() +1)){ e.setSlowingDown(true); e.setSpeedingUp(false); e.setFinishedVelocityChange(true); } e.setLastSpedUpVelocityTime(System.nanoTime()); } } } //spaceship decay if(spaceshipY<height*9/10 && !spaceshipIsMoving) { spaceshipY += DECAY_SPEED; } //resets spaceship laser spaceshipLaserY -= 20.0f; if(spaceshipLaserY < -height/6){ spaceshipLaserY = spaceshipY+spaceship[0].getHeight()/3; spaceshipLaserX = spaceshipX+spaceship[0].getWidth()/8; } //animator for map background mapAnimatorY+=2.0f; secondaryMapAnimatorY+=2.0f; //this means the stars are off the screen if(mapAnimatorY>=height*2){ mapAnimatorY = height; }else if(secondaryMapAnimatorY>=height*2){ secondaryMapAnimatorY = height; } } @Override public void draw(Canvas c, View v) { try { // actually draw the screen scaledDst.set(mapAnimatorX-width, mapAnimatorY-height, mapAnimatorX, mapAnimatorY); c.drawBitmap(starbackground,null,scaledDst,p); //secondary background for animation. Same as last draw, but instead, these are a height-length higher c.drawBitmap(starbackground,null,new Rect(secondaryMapAnimatorX-width, secondaryMapAnimatorY-(height*2),secondaryMapAnimatorX, secondaryMapAnimatorY-height),p); synchronized (shipExplosions) { for(ShipExplosion se: shipExplosions){ c.drawBitmap(explosion[se.currentFrame],se.x,se.y,p); //semi-clever way of adding a very precise delay (yes, I am scratching my own ass) if(hitContactTime + (ONESEC_NANOS/50) < frtime) { hitContactTime = System.nanoTime(); se.nextFrame(); } if(se.currentFrame == 11){ shipExplosions.remove(se.getExplosionNumber()); } } } synchronized (enemiesFlying) { for(Enemy e: enemiesFlying) { if(startDelayReached) { //puts like a red tinge on the enemy for 100 ms if hes hit if(e.isEnemyHitButNotDead()){ c.drawBitmap(hitFighter, e.getX(), e.getY(), p); if(hitContactTime + (ONESEC_NANOS/10) <frtime){ e.setEnemyIsHitButNotDead(false); } }else { c.drawBitmap(e.getBitmap(), e.getX(), e.getY(), p); } //enemy firing stuff if(enemyFiringTime== 0){ enemyFiringTime = System.nanoTime(); randomlyGeneratedEnemyFiringTimeInSeconds = (rand.nextInt(3000))/1000; } if ((e.hasCollision(spaceshipLaserX, spaceshipLaserY) || e.hasCollision(spaceshipLaserX + spaceship[0].getWidth() * 64 / 100, spaceshipLaserY))) { spaceshipLaserX = 4000; hitContactTime = System.nanoTime(); //subtract a life e.setLives(e.getLives()-1); //fun explosions if(e.getLives() == 0) { shipExplosions.add(new ShipExplosion(e.getX() - e.getBitmap().getWidth() * 3 / 4, e.getY() - e.getBitmap().getHeight() / 2, shipExplosions.size())); enemiesFlying.remove(e); }else{ e.setEnemyIsHitButNotDead(true); } } } } } //main spaceship lasers c.drawBitmap(spaceshipLaser, spaceshipLaserX, spaceshipLaserY, p); c.drawBitmap(spaceshipLaser, spaceshipLaserX + spaceship[0].getWidth() * 64 / 100, spaceshipLaserY, p); //main spaceship for(int i = 0; i<spaceship.length; i++) { if(i == currentSpaceshipFrame && frtime>spaceshipFrameSwitchTime + (ONESEC_NANOS/20)) { if(currentSpaceshipFrame == spaceship.length-1){ currentSpaceshipFrame = 0; }else{ currentSpaceshipFrame++; } c.drawBitmap(spaceship[i], spaceshipX, spaceshipY, p); spaceshipFrameSwitchTime = System.nanoTime(); }else if(i==currentSpaceshipFrame){ c.drawBitmap(spaceship[i], spaceshipX, spaceshipY, p); } } p.setColor(Color.WHITE); p.setTextSize(act.TS_NORMAL); p.setTypeface(act.getGameFont()); if (score >= highscore) { highscore = score; highlev = currentLevel; } if (gamestate == State.ROUNDSUMMARY || gamestate == State.STARTGAME || gamestate == State.PLAYERDIED || gamestate == State.GAMEOVER) { if (gamestate != State.STARTGAME) { // round ended, by completion or player death, display stats if (gamestate == State.ROUNDSUMMARY) { } else if (gamestate == State.PLAYERDIED || gamestate == State.GAMEOVER){ } } if (gamestate != State.PLAYERDIED && gamestate != State.GAMEOVER) { } if (gamestate != State.GAMEOVER) { } } if (gamestate == State.GAMEOVER) { /*p.setTextSize(act.TS_BIG); p.setColor(Color.RED); drawCenteredText(c, "GamE oVeR!", height /2, p, -2); drawCenteredText(c, "Touch to end game", height * 4 /5, p, -2); p.setColor(Color.WHITE); drawCenteredText(c, "GamE oVeR!", height /2, p, 0); drawCenteredText(c, "Touch to end game", height * 4 /5, p, 0);*/ } } catch (Exception e) { Log.e(MainActivity.LOG_ID, "draw", e); e.printStackTrace(); } } //center text private void drawCenteredText(Canvas c, String msg, int height, Paint p, int shift) { c.drawText(msg, (width - p.measureText(msg)) / 2 + shift, height, p); } DisplayMetrics dm = new DisplayMetrics(); @Override public boolean onTouch(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: synchronized (spaceship){ spaceshipBounds = new Rect(spaceshipX,spaceshipY,spaceshipX+spaceship[0].getWidth(),spaceshipY+spaceship[0].getHeight()); if(spaceshipBounds.contains((int) e.getX(),(int) e.getY())){ spaceshipIsMoving = true; spaceshipX = (int) e.getX()-spaceship[0].getWidth()/2; spaceshipY = (int) e.getY()-spaceship[0].getHeight()/2; } } break; case MotionEvent.ACTION_UP: spaceshipIsMoving=false; break; } return true; } //this is for creating multiple ship explosion animations private class ShipExplosion{ float x=0; float y=0; int currentFrame = 0; int explosionNumber = 0; public ShipExplosion(float x, float y, int explosionNumber){ this.x = x; this.y = y; this.explosionNumber = explosionNumber; } public int getCurrentFrame(){ return currentFrame; } public void nextFrame(){ currentFrame++; } public int getExplosionNumber(){ return explosionNumber; } } }
package archimulator.sim.os; import archimulator.model.ContextMapping; import archimulator.service.ServiceManager; import archimulator.sim.analysis.BasicBlock; import archimulator.sim.analysis.ElfAnalyzer; import archimulator.sim.analysis.Function; import archimulator.sim.analysis.Instruction; import archimulator.sim.isa.Memory; import archimulator.sim.isa.PseudoCall; import archimulator.sim.isa.StaticInstruction; import archimulator.sim.isa.dissembler.MipsDisassembler; import archimulator.sim.os.elf.ElfFile; import archimulator.sim.os.elf.ElfSectionHeader; import java.io.File; import java.util.*; /** * * @author Min Cai */ public class BasicProcess extends Process { private Map<Integer, Integer> pcsToMachineInstructions; private Map<Integer, StaticInstruction> machineInstructionsToStaticInstructions; private Map<String, SortedMap<Integer, Instruction>> instructions; private ElfAnalyzer elfAnalyzer; private Map<Integer, String> pcToFunctionNameMappingCache; /** * * @param kernel * @param simulationDirectory * @param contextMapping */ public BasicProcess(Kernel kernel, String simulationDirectory, ContextMapping contextMapping) { super(kernel, simulationDirectory, contextMapping); } /** * * @param kernel * @param simulationDirectory * @param contextMapping */ @Override protected void loadProgram(Kernel kernel, String simulationDirectory, ContextMapping contextMapping) { this.pcsToMachineInstructions = new TreeMap<Integer, Integer>(); this.machineInstructionsToStaticInstructions = new TreeMap<Integer, StaticInstruction>(); this.instructions = new HashMap<String, SortedMap<Integer, Instruction>>(); List<String> commandLineArgumentList = Arrays.asList((contextMapping.getBenchmark().getWorkingDirectory() + File.separator + contextMapping.getBenchmark().getExecutable() + " " + contextMapping.getArguments()).replaceAll(ServiceManager.USER_HOME_TEMPLATE_ARG, System.getProperty("user.home")).split(" ")); String elfFileName = commandLineArgumentList.get(0); ElfFile elfFile = new ElfFile(elfFileName); for (ElfSectionHeader sectionHeader : elfFile.getSectionHeaders()) { if (sectionHeader.getName().equals(".dynamic")) { throw new IllegalArgumentException("dynamic linking is not supported"); } if (sectionHeader.getSh_type() == ElfSectionHeader.SHT_PROGBITS || sectionHeader.getSh_type() == ElfSectionHeader.SHT_NOBITS) { if (sectionHeader.getSh_size() > 0 && (sectionHeader.getSh_flags() & ElfSectionHeader.SHF_ALLOC) != 0) { // this.memory.map((int) sectionHeader.getSh_addr(), (int) sectionHeader.getSh_size())); if (sectionHeader.getSh_type() == ElfSectionHeader.SHT_NOBITS) { this.getMemory().zero((int) sectionHeader.getSh_addr(), (int) sectionHeader.getSh_size()); } else { this.getMemory().writeBlock((int) sectionHeader.getSh_addr(), (int) sectionHeader.getSh_size(), sectionHeader.readContent(elfFile)); if ((sectionHeader.getSh_flags() & ElfSectionHeader.SHF_EXECINSTR) != 0) { this.instructions.put(sectionHeader.getName(), new TreeMap<Integer, Instruction>()); for (int i = 0; i < (int) sectionHeader.getSh_size(); i += 4) { int pc = (int) sectionHeader.getSh_addr() + i; this.predecode(sectionHeader.getName(), this.getMemory(), pc); } } } if (sectionHeader.getSh_addr() >= DATA_BASE) { this.setDataTop((int) Math.max(this.getDataTop(), sectionHeader.getSh_addr() + sectionHeader.getSh_size() - 1)); } } } if (sectionHeader.getName().equals(".text")) { this.setTextSize((int) (sectionHeader.getSh_addr() + sectionHeader.getSh_size() - TEXT_BASE)); } } this.setProgramEntry((int) elfFile.getHeader().getE_entry()); this.setHeapTop(roundUp(this.getDataTop(), Memory.getPageSize())); this.setStackBase(STACK_BASE); // this.stackSize = STACK_SIZE; //TODO this.setStackSize(MAX_ENVIRON); this.setEnvironmentBase(STACK_BASE - MAX_ENVIRON); // this.memory.map(this.stackBase - this.stackSize, this.stackSize); this.getMemory().zero(this.getStackBase() - this.getStackSize(), this.getStackSize()); int stackPointer = this.getEnvironmentBase(); this.getMemory().writeWord(stackPointer, commandLineArgumentList.size()); stackPointer += 4; int argAddress = stackPointer; stackPointer += (commandLineArgumentList.size() + 1) * 4; int environmentAddress = stackPointer; stackPointer += (this.getEnvironments().size() + 1) * 4; for (int i = 0; i < commandLineArgumentList.size(); i++) { this.getMemory().writeWord(argAddress + i * 4, stackPointer); stackPointer += this.getMemory().writeString(stackPointer, commandLineArgumentList.get(i)); } this.getMemory().writeWord(argAddress + commandLineArgumentList.size() * 4, 0); for (int i = 0; i < this.getEnvironments().size(); i++) { this.getMemory().writeWord(environmentAddress + i * 4, stackPointer); stackPointer += this.getMemory().writeString(stackPointer, this.getEnvironments().get(i)); } this.getMemory().writeWord(environmentAddress + this.getEnvironments().size() * 4, 0); if (stackPointer > this.getStackBase()) { throw new IllegalArgumentException("'environ' overflow, increment MAX_ENVIRON"); } this.elfAnalyzer = new ElfAnalyzer(elfFileName, elfFile, this.instructions, this.getProgramEntry()); this.elfAnalyzer.buildControlFlowGraphs(); this.pcToFunctionNameMappingCache = new TreeMap<Integer, String>(); } private void predecode(String sectionName, Memory memory, int pc) { int machineInstruction = memory.readWord(pc); this.pcsToMachineInstructions.put(pc, machineInstruction); if (!this.machineInstructionsToStaticInstructions.containsKey(machineInstruction)) { StaticInstruction staticInstruction = this.decode(machineInstruction); this.machineInstructionsToStaticInstructions.put(machineInstruction, staticInstruction); } this.instructions.get(sectionName).put(pc, new Instruction(this, pc, this.getStaticInstruction(pc))); } /** * * @param process * @param pc * @return */ public static String getDisassemblyInstruction(Process process, int pc) { return MipsDisassembler.disassemble(pc, process.getStaticInstruction(pc)); } /** * * @param pc * @return */ @Override public StaticInstruction getStaticInstruction(int pc) { return this.machineInstructionsToStaticInstructions.get(this.pcsToMachineInstructions.get(pc)); } @Override public String getFunctionNameFromPc(int pc) { if(this.pcToFunctionNameMappingCache.containsKey(pc)) { return this.pcToFunctionNameMappingCache.get(pc); } for(Function function : this.elfAnalyzer.getProgram().getFunctions()) { for (BasicBlock basicBlock : function.getBasicBlocks()) { for (Instruction instruction : basicBlock.getInstructions()) { if (instruction.getPc() == pc) { String functionName = function.getSymbol().getName(); this.pcToFunctionNameMappingCache.put(pc, functionName); return functionName; } } } } return null; } @Override public Function getHotspotFunction() { for (Function function : this.elfAnalyzer.getProgram().getFunctions()) { for (BasicBlock basicBlock : function.getBasicBlocks()) { for (Instruction instruction : basicBlock.getInstructions()) { PseudoCall pseudoCall = StaticInstruction.getPseudoCall(instruction.getStaticInstruction().getMachineInstruction()); if (pseudoCall != null && pseudoCall.getImm() == PseudoCall.PSEUDOCALL_HOTSPOT_FUNCTION_BEGIN) { return function; } } } } return null; } /** * * @return */ @Override public ElfAnalyzer getElfAnalyzer() { return elfAnalyzer; } }
package com.mychess.mychess; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; public class LoginFragment extends Fragment{ EditText usuario; EditText clave; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SharedPreferences preferences = getActivity().getSharedPreferences("usuario",Context.MODE_PRIVATE); if(!(preferences.getString("usuario",null) == null)){ Intent intent = new Intent(getContext(),Juego.class); startActivity(intent); getActivity().finish(); } View view = inflater.inflate(R.layout.login_fragment, container, false); usuario = (EditText) view.findViewById(R.id.loginUsuario); clave = (EditText) view.findViewById(R.id.loginClave); Button entrar = (Button) view.findViewById(R.id.button); entrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (usuario.getText().length() == 0) { Toast.makeText(getContext(), "usuario vacío", Toast.LENGTH_SHORT).show(); } else if (clave.getText().length() == 0) { Toast.makeText(getContext(), "clave vacía", Toast.LENGTH_SHORT).show(); }else { String[] datos = new String[2]; datos[0] = usuario.getText().toString(); datos[1] = clave.getText().toString(); Login login = new Login(); login.execute(datos); } } }); return view; } class Login extends AsyncTask<String,String,Void>{ @Override protected Void doInBackground(String... params) { final String NAMESPACE = "http://servicios/"; final String URL = "http://servermychess.tk:8080/RegistroLogin/RegistroLogin"; final String METHOD_NAME = "login"; final String SOAP_ACTION = "http://Servicios/login"; SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME); request.addProperty("usuario",params[0]); request.addProperty("clave",params[1]); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = false; envelope.setOutputSoapObject(request); HttpTransportSE transportSE = new HttpTransportSE(URL); try{ transportSE.call(SOAP_ACTION,envelope); SoapPrimitive respuesta = (SoapPrimitive) envelope.getResponse(); publishProgress(respuesta.toString()); }catch(Exception ex){ } return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); if(values[0].equals("0")){ SharedPreferences preferences = getActivity().getSharedPreferences("usuario",Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("usuario", usuario.getText().toString()); editor.commit(); Intent intent = new Intent(getContext(),Juego.class); startActivity(intent); getActivity().finish(); } } } }
package cgeo.geocaching.connector.oc; import cgeo.geocaching.Geocache; import cgeo.geocaching.Image; import cgeo.geocaching.LogEntry; import cgeo.geocaching.R; import cgeo.geocaching.Waypoint; import cgeo.geocaching.cgData; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.LogResult; import cgeo.geocaching.connector.gc.GCConnector; import cgeo.geocaching.connector.oc.OCApiConnector.ApiSupport; import cgeo.geocaching.connector.oc.OCApiConnector.OAuthLevel; import cgeo.geocaching.connector.oc.UserInfo.UserInfoStatus; import cgeo.geocaching.enumerations.CacheAttribute; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.network.Network; import cgeo.geocaching.network.OAuth; import cgeo.geocaching.network.Parameters; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.net.Uri; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; final class OkapiClient { private static final char SEPARATOR = '|'; private static final String SEPARATOR_STRING = Character.toString(SEPARATOR); private static final SimpleDateFormat LOG_DATE_FORMAT; static { LOG_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", Locale.US); LOG_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } private static final SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()); private static final String CACHE_ATTRNAMES = "attrnames"; private static final String WPT_LOCATION = "location"; private static final String WPT_DESCRIPTION = "description"; private static final String WPT_TYPE = "type"; private static final String WPT_NAME = "name"; private static final String CACHE_IS_WATCHED = "is_watched"; private static final String CACHE_WPTS = "alt_wpts"; private static final String CACHE_STATUS_ARCHIVED = "Archived"; private static final String CACHE_STATUS_DISABLED = "Temporarily unavailable"; private static final String CACHE_IS_FOUND = "is_found"; private static final String CACHE_SIZE = "size"; private static final String CACHE_VOTES = "rating_votes"; private static final String CACHE_NOTFOUNDS = "notfounds"; private static final String CACHE_FOUNDS = "founds"; private static final String CACHE_HIDDEN = "date_hidden"; private static final String CACHE_LATEST_LOGS = "latest_logs"; private static final String CACHE_IMAGE_URL = "url"; private static final String CACHE_IMAGE_CAPTION = "caption"; private static final String CACHE_IMAGE_IS_SPOILER = "is_spoiler"; private static final String CACHE_IMAGES = "images"; private static final String CACHE_HINT = "hint"; private static final String CACHE_DESCRIPTION = "description"; private static final String CACHE_RECOMMENDATIONS = "recommendations"; private static final String CACHE_RATING = "rating"; private static final String CACHE_TERRAIN = "terrain"; private static final String CACHE_DIFFICULTY = "difficulty"; private static final String CACHE_OWNER = "owner"; private static final String CACHE_STATUS = "status"; private static final String CACHE_TYPE = "type"; private static final String CACHE_LOCATION = "location"; private static final String CACHE_NAME = "name"; private static final String CACHE_CODE = "code"; private static final String CACHE_REQ_PASSWORD = "req_passwd"; private static final String CACHE_MY_NOTES = "my_notes"; private static final String LOG_TYPE = "type"; private static final String LOG_COMMENT = "comment"; private static final String LOG_DATE = "date"; private static final String LOG_USER = "user"; private static final String USER_USERNAME = "username"; private static final String USER_CACHES_FOUND = "caches_found"; private static final String USER_INFO_FIELDS = "username|caches_found"; // the several realms of possible fields for cache retrieval: // Core: for livemap requests (L3 - only with level 3 auth) // Additional: additional fields for full cache (L3 - only for level 3 auth, current - only for connectors with current api) private static final String SERVICE_CACHE_CORE_FIELDS = "code|name|location|type|status|difficulty|terrain|size"; private static final String SERVICE_CACHE_CORE_L3_FIELDS = "is_found"; private static final String SERVICE_CACHE_ADDITIONAL_FIELDS = "owner|founds|notfounds|rating|rating_votes|recommendations|description|hint|images|latest_logs|date_hidden|alt_wpts|attrnames|req_passwd"; private static final String SERVICE_CACHE_ADDITIONAL_CURRENT_FIELDS = "gc_code|attribution_note"; private static final String SERVICE_CACHE_ADDITIONAL_L3_FIELDS = "is_watched|my_notes"; private static final String METHOD_SEARCH_NEAREST = "services/caches/search/nearest"; private static final String METHOD_SEARCH_BBOX = "services/caches/search/bbox"; private static final String METHOD_RETRIEVE_CACHES = "services/caches/geocaches"; public static Geocache getCache(final String geoCode) { final Parameters params = new Parameters("cache_code", geoCode); final IConnector connector = ConnectorFactory.getConnector(geoCode); if (!(connector instanceof OCApiConnector)) { return null; } final OCApiConnector ocapiConn = (OCApiConnector) connector; params.add("fields", getFullFields(ocapiConn)); params.add("attribution_append", "none"); final JSONObject data = request(ocapiConn, OkapiService.SERVICE_CACHE, params); if (data == null) { return null; } return parseCache(data); } public static List<Geocache> getCachesAround(final Geopoint center, final OCApiConnector connector) { final String centerString = GeopointFormatter.format(GeopointFormatter.Format.LAT_DECDEGREE_RAW, center) + SEPARATOR + GeopointFormatter.format(GeopointFormatter.Format.LON_DECDEGREE_RAW, center); final Parameters params = new Parameters("search_method", METHOD_SEARCH_NEAREST); final Map<String, String> valueMap = new LinkedHashMap<String, String>(); valueMap.put("center", centerString); valueMap.put("limit", "20"); valueMap.put("radius", "200"); return requestCaches(connector, params, valueMap); } private static List<Geocache> requestCaches(final OCApiConnector connector, final Parameters params, final Map<String, String> valueMap) { addFilterParams(valueMap, connector); params.add("search_params", new JSONObject(valueMap).toString()); addRetrieveParams(params, connector); final JSONObject data = request(connector, OkapiService.SERVICE_SEARCH_AND_RETRIEVE, params); if (data == null) { return Collections.emptyList(); } return parseCaches(data); } // Assumes level 3 OAuth public static List<Geocache> getCachesBBox(final Viewport viewport, final OCApiConnector connector) { if (viewport.getLatitudeSpan() == 0 || viewport.getLongitudeSpan() == 0) { return Collections.emptyList(); } final String bboxString = GeopointFormatter.format(GeopointFormatter.Format.LAT_DECDEGREE_RAW, viewport.bottomLeft) + SEPARATOR + GeopointFormatter.format(GeopointFormatter.Format.LON_DECDEGREE_RAW, viewport.bottomLeft) + SEPARATOR + GeopointFormatter.format(GeopointFormatter.Format.LAT_DECDEGREE_RAW, viewport.topRight) + SEPARATOR + GeopointFormatter.format(GeopointFormatter.Format.LON_DECDEGREE_RAW, viewport.topRight); final Parameters params = new Parameters("search_method", METHOD_SEARCH_BBOX); final Map<String, String> valueMap = new LinkedHashMap<String, String>(); valueMap.put("bbox", bboxString); return requestCaches(connector, params, valueMap); } public static boolean setWatchState(final Geocache cache, final boolean watched, final OCApiConnector connector) { final Parameters params = new Parameters("cache_code", cache.getGeocode()); params.add("watched", watched ? "true" : "false"); final JSONObject data = request(connector, OkapiService.SERVICE_MARK_CACHE, params); if (data == null) { return false; } cache.setOnWatchlist(watched); return true; } public static LogResult postLog(final Geocache cache, final LogType logType, final Calendar date, final String log, final String logPassword, final OCApiConnector connector) { final Parameters params = new Parameters("cache_code", cache.getGeocode()); params.add("logtype", logType.oc_type); params.add("comment", log); params.add("comment_format", "plaintext"); params.add("when", LOG_DATE_FORMAT.format(date.getTime())); if (logType.equals(LogType.NEEDS_MAINTENANCE)) { params.add("needs_maintenance", "true"); } if (logPassword != null) { params.add("password", logPassword); } final JSONObject data = request(connector, OkapiService.SERVICE_SUBMIT_LOG, params); if (data == null) { return new LogResult(StatusCode.LOG_POST_ERROR, ""); } try { if (data.getBoolean("success")) { return new LogResult(StatusCode.NO_ERROR, data.getString("log_uuid")); } return new LogResult(StatusCode.LOG_POST_ERROR, ""); } catch (final JSONException e) { Log.e("OkapiClient.postLog", e); } return new LogResult(StatusCode.LOG_POST_ERROR, ""); } private static List<Geocache> parseCaches(final JSONObject response) { try { // Check for empty result final String result = response.getString("results"); if (StringUtils.isBlank(result) || StringUtils.equals(result, "[]")) { return Collections.emptyList(); } // Get and iterate result list final JSONObject cachesResponse = response.getJSONObject("results"); if (cachesResponse != null) { final List<Geocache> caches = new ArrayList<Geocache>(cachesResponse.length()); @SuppressWarnings("unchecked") final Iterator<String> keys = cachesResponse.keys(); while (keys.hasNext()) { final String key = keys.next(); final Geocache cache = parseSmallCache(cachesResponse.getJSONObject(key)); caches.add(cache); } return caches; } } catch (final JSONException e) { Log.e("OkapiClient.parseCachesResult", e); } return Collections.emptyList(); } private static Geocache parseSmallCache(final JSONObject response) { final Geocache cache = new Geocache(); cache.setReliableLatLon(true); try { parseCoreCache(response, cache); cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_CACHE)); } catch (final JSONException e) { Log.e("OkapiClient.parseSmallCache", e); } return cache; } private static Geocache parseCache(final JSONObject response) { final Geocache cache = new Geocache(); cache.setReliableLatLon(true); try { parseCoreCache(response, cache); // not used: url final JSONObject owner = response.getJSONObject(CACHE_OWNER); cache.setOwnerDisplayName(parseUser(owner)); cache.getLogCounts().put(LogType.FOUND_IT, response.getInt(CACHE_FOUNDS)); cache.getLogCounts().put(LogType.DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS)); if (!response.isNull(CACHE_RATING)) { cache.setRating((float) response.getDouble(CACHE_RATING)); } cache.setVotes(response.getInt(CACHE_VOTES)); cache.setFavoritePoints(response.getInt(CACHE_RECOMMENDATIONS)); // not used: req_password // Prepend gc-link to description if available final StringBuilder description = new StringBuilder(500); if (!response.isNull("gc_code")) { final String gccode = response.getString("gc_code"); description.append(cgeoapplication.getInstance().getResources() .getString(R.string.cache_listed_on, GCConnector.getInstance().getName())) .append(": <a href=\"http://coord.info/") .append(gccode) .append("\">") .append(gccode) .append("</a><br /><br />"); } description.append(response.getString(CACHE_DESCRIPTION)); cache.setDescription(description.toString()); // currently the hint is delivered as HTML (contrary to OKAPI documentation), so we can store it directly cache.setHint(response.getString(CACHE_HINT)); // not used: hints final JSONArray images = response.getJSONArray(CACHE_IMAGES); if (images != null) { for (int i = 0; i < images.length(); i++) { final JSONObject imageResponse = images.getJSONObject(i); final String title = imageResponse.getString(CACHE_IMAGE_CAPTION); final String url = absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.getGeocode()); cache.addSpoiler(new Image(url, title)); } } cache.setAttributes(parseAttributes(response.getJSONArray(CACHE_ATTRNAMES))); cache.setLogs(parseLogs(response.getJSONArray(CACHE_LATEST_LOGS))); cache.setHidden(parseDate(response.getString(CACHE_HIDDEN))); cache.setWaypoints(parseWaypoints(response.getJSONArray(CACHE_WPTS)), false); if (!response.isNull(CACHE_IS_WATCHED)) { cache.setOnWatchlist(response.getBoolean(CACHE_IS_WATCHED)); } if (!response.isNull(CACHE_MY_NOTES)) { cache.setPersonalNote(response.getString(CACHE_MY_NOTES)); } cache.setLogPasswordRequired(response.getBoolean(CACHE_REQ_PASSWORD)); cache.setDetailedUpdatedNow(); // save full detailed caches cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); } catch (final JSONException e) { Log.e("OkapiClient.parseCache", e); } return cache; } private static void parseCoreCache(final JSONObject response, final Geocache cache) throws JSONException { cache.setGeocode(response.getString(CACHE_CODE)); cache.setName(response.getString(CACHE_NAME)); // not used: names setLocation(cache, response.getString(CACHE_LOCATION)); cache.setType(getCacheType(response.getString(CACHE_TYPE))); final String status = response.getString(CACHE_STATUS); cache.setDisabled(status.equalsIgnoreCase(CACHE_STATUS_DISABLED)); cache.setArchived(status.equalsIgnoreCase(CACHE_STATUS_ARCHIVED)); cache.setSize(getCacheSize(response)); cache.setDifficulty((float) response.getDouble(CACHE_DIFFICULTY)); cache.setTerrain((float) response.getDouble(CACHE_TERRAIN)); if (!response.isNull(CACHE_IS_FOUND)) { cache.setFound(response.getBoolean(CACHE_IS_FOUND)); } } private static String absoluteUrl(final String url, final String geocode) { final Uri uri = Uri.parse(url); if (!uri.isAbsolute()) { final IConnector connector = ConnectorFactory.getConnector(geocode); final String host = connector.getHost(); if (StringUtils.isNotBlank(host)) { return "http://" + host + "/" + url; } } return url; } private static String parseUser(final JSONObject user) throws JSONException { return user.getString(USER_USERNAME); } private static List<LogEntry> parseLogs(final JSONArray logsJSON) { List<LogEntry> result = null; for (int i = 0; i < logsJSON.length(); i++) { try { final JSONObject logResponse = logsJSON.getJSONObject(i); final LogEntry log = new LogEntry( parseUser(logResponse.getJSONObject(LOG_USER)), parseDate(logResponse.getString(LOG_DATE)).getTime(), parseLogType(logResponse.getString(LOG_TYPE)), logResponse.getString(LOG_COMMENT).trim()); if (result == null) { result = new ArrayList<LogEntry>(); } result.add(log); } catch (final JSONException e) { Log.e("OkapiClient.parseLogs", e); } } return result; } private static List<Waypoint> parseWaypoints(final JSONArray wptsJson) { List<Waypoint> result = null; for (int i = 0; i < wptsJson.length(); i++) { try { final JSONObject wptResponse = wptsJson.getJSONObject(i); final Waypoint wpt = new Waypoint(wptResponse.getString(WPT_NAME), parseWptType(wptResponse.getString(WPT_TYPE)), false); wpt.setNote(wptResponse.getString(WPT_DESCRIPTION)); final Geopoint pt = parseCoords(wptResponse.getString(WPT_LOCATION)); if (pt != null) { wpt.setCoords(pt); } if (result == null) { result = new ArrayList<Waypoint>(); } result.add(wpt); } catch (final JSONException e) { Log.e("OkapiClient.parseWaypoints", e); } } return result; } private static LogType parseLogType(final String logType) { if ("Found it".equalsIgnoreCase(logType)) { return LogType.FOUND_IT; } if ("Didn't find it".equalsIgnoreCase(logType)) { return LogType.DIDNT_FIND_IT; } return LogType.NOTE; } private static WaypointType parseWptType(final String wptType) { if ("parking".equalsIgnoreCase(wptType)) { return WaypointType.PARKING; } if ("path".equalsIgnoreCase(wptType)) { return WaypointType.TRAILHEAD; } if ("stage".equalsIgnoreCase(wptType)) { return WaypointType.STAGE; } if ("physical-stage".equalsIgnoreCase(wptType)) { return WaypointType.STAGE; } if ("virtual-stage".equalsIgnoreCase(wptType)) { return WaypointType.PUZZLE; } if ("final".equalsIgnoreCase(wptType)) { return WaypointType.FINAL; } if ("poi".equalsIgnoreCase(wptType)) { return WaypointType.TRAILHEAD; } return WaypointType.WAYPOINT; } private static Date parseDate(final String date) { final String strippedDate = date.replaceAll("\\+0([0-9]){1}\\:00", "+0$100"); try { return ISO8601DATEFORMAT.parse(strippedDate); } catch (final ParseException e) { Log.e("OkapiClient.parseDate", e); } return null; } private static Geopoint parseCoords(final String location) { final String latitude = StringUtils.substringBefore(location, SEPARATOR_STRING); final String longitude = StringUtils.substringAfter(location, SEPARATOR_STRING); if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) { return new Geopoint(latitude, longitude); } return null; } private static List<String> parseAttributes(final JSONArray nameList) { final List<String> result = new ArrayList<String>(); for (int i = 0; i < nameList.length(); i++) { try { final String name = nameList.getString(i); final CacheAttribute attr = CacheAttribute.getByOcId(AttributeParser.getOcDeId(name)); if (attr != null) { result.add(attr.rawName); } } catch (final JSONException e) { Log.e("OkapiClient.parseAttributes", e); } } return result; } private static void setLocation(final Geocache cache, final String location) { final String latitude = StringUtils.substringBefore(location, SEPARATOR_STRING); final String longitude = StringUtils.substringAfter(location, SEPARATOR_STRING); cache.setCoords(new Geopoint(latitude, longitude)); } private static CacheSize getCacheSize(final JSONObject response) { if (response.isNull(CACHE_SIZE)) { return CacheSize.NOT_CHOSEN; } double size = 0; try { size = response.getDouble(CACHE_SIZE); } catch (final JSONException e) { Log.e("OkapiClient.getCacheSize", e); } switch ((int) Math.round(size)) { case 1: return CacheSize.MICRO; case 2: return CacheSize.SMALL; case 3: return CacheSize.REGULAR; case 4: return CacheSize.LARGE; case 5: return CacheSize.LARGE; default: break; } return CacheSize.NOT_CHOSEN; } private static CacheType getCacheType(final String cacheType) { if (cacheType.equalsIgnoreCase("Traditional")) { return CacheType.TRADITIONAL; } if (cacheType.equalsIgnoreCase("Multi")) { return CacheType.MULTI; } if (cacheType.equalsIgnoreCase("Quiz")) { return CacheType.MYSTERY; } if (cacheType.equalsIgnoreCase("Virtual")) { return CacheType.VIRTUAL; } if (cacheType.equalsIgnoreCase("Event")) { return CacheType.EVENT; } if (cacheType.equalsIgnoreCase("Webcam")) { return CacheType.WEBCAM; } if (cacheType.equalsIgnoreCase("Math/Physics")) { return CacheType.MYSTERY; } if (cacheType.equalsIgnoreCase("Drive-In")) { return CacheType.TRADITIONAL; } return CacheType.UNKNOWN; } private static String getCoreFields(final OCApiConnector connector) { if (connector == null) { Log.e("OkapiClient.getCoreFields called with invalid connector"); return StringUtils.EMPTY; } if (connector.getSupportedAuthLevel() == OAuthLevel.Level3) { return SERVICE_CACHE_CORE_FIELDS + SEPARATOR + SERVICE_CACHE_CORE_L3_FIELDS; } return SERVICE_CACHE_CORE_FIELDS; } private static String getFullFields(final OCApiConnector connector) { if (connector == null) { Log.e("OkapiClient.getFullFields called with invalid connector"); return StringUtils.EMPTY; } final StringBuilder res = new StringBuilder(500); res.append(SERVICE_CACHE_CORE_FIELDS); res.append(SEPARATOR).append(SERVICE_CACHE_ADDITIONAL_FIELDS); if (connector.getSupportedAuthLevel() == OAuthLevel.Level3) { res.append(SEPARATOR).append(SERVICE_CACHE_CORE_L3_FIELDS); res.append(SEPARATOR).append(SERVICE_CACHE_ADDITIONAL_L3_FIELDS); } if (connector.getApiSupport() == ApiSupport.current) { res.append(SEPARATOR).append(SERVICE_CACHE_ADDITIONAL_CURRENT_FIELDS); } return res.toString(); } private static JSONObject request(final OCApiConnector connector, final OkapiService service, final Parameters params) { if (connector == null) { return null; } final String host = connector.getHost(); if (StringUtils.isBlank(host)) { return null; } params.add("langpref", getPreferredLanguage()); if (connector.getSupportedAuthLevel() == OAuthLevel.Level3) { ImmutablePair<String, String> tokens = Settings.getTokenPair(connector.getTokenPublicPrefKeyId(), connector.getTokenSecretPrefKeyId()); OAuth.signOAuth(host, service.methodName, "GET", false, params, tokens.left, tokens.right, connector.getCK(), connector.getCS()); } else { connector.addAuthentication(params); } final String uri = "http://" + host + service.methodName; return Network.requestJSON(uri, params); } private static String getPreferredLanguage() { final String code = Locale.getDefault().getCountry(); if (StringUtils.isNotBlank(code)) { return StringUtils.lowerCase(code) + "|en"; } return "en"; } private static void addFilterParams(final Map<String, String> valueMap, final OCApiConnector connector) { if (!Settings.isExcludeDisabledCaches()) { valueMap.put("status", "Available|Temporarily unavailable"); } if (Settings.isExcludeMyCaches() && connector.getSupportedAuthLevel() == OAuthLevel.Level3) { valueMap.put("exclude_my_own", "true"); valueMap.put("found_status", "notfound_only"); } if (Settings.getCacheType() != CacheType.ALL) { valueMap.put("type", getFilterFromType(Settings.getCacheType())); } } private static void addRetrieveParams(final Parameters params, final OCApiConnector connector) { params.add("retr_method", METHOD_RETRIEVE_CACHES); params.add("retr_params", "{\"fields\": \"" + getCoreFields(connector) + "\"}"); params.add("wrap", "true"); } private static String getFilterFromType(final CacheType cacheType) { switch (cacheType) { case EVENT: return "Event"; case MULTI: return "Multi"; case MYSTERY: return "Quiz"; case TRADITIONAL: return "Traditional"; case VIRTUAL: return "Virtual"; case WEBCAM: return "Webcam"; default: return ""; } } public static UserInfo getUserInfo(final OCApiLiveConnector connector) { final Parameters params = new Parameters("fields", USER_INFO_FIELDS); final JSONObject data = request(connector, OkapiService.SERVICE_USER, params); if (data == null) { return new UserInfo(StringUtils.EMPTY, 0, UserInfoStatus.FAILED); } String name = StringUtils.EMPTY; boolean successUserName = false; if (!data.isNull(USER_USERNAME)) { try { name = data.getString(USER_USERNAME); successUserName = true; } catch (final JSONException e) { Log.e("OkapiClient.getUserInfo - name", e); } } int finds = 0; boolean successFinds = false; if (!data.isNull(USER_CACHES_FOUND)) { try { finds = data.getInt(USER_CACHES_FOUND); successFinds = true; } catch (final JSONException e) { Log.e("OkapiClient.getUserInfo - finds", e); } } return new UserInfo(name, finds, successUserName && successFinds ? UserInfoStatus.SUCCESSFUL : UserInfoStatus.FAILED); } }
package me.ydcool.easingandroid.ui; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.Arrays; import me.ydcool.easing.*; import me.ydcool.easingandroid.R; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private static final Class[] EASING_INTERPOLATOR = new Class[]{ EaseInBackInterpolator.class, EaseOutBackInterpolator.class, EaseInOutBackInterpolator.class, EaseInBounceInterpolator.class, EaseOutBounceInterpolator.class, EaseInOutBackInterpolator.class, EaseInCircInterpolator.class, EaseOutCircInterpolator.class, EaseInOutCircInterpolator.class, EaseInCubicInterpolator.class, EaseOutCubicInterpolator.class, EaseInOutCubicInterpolator.class, EaseInElasticInterpolator.class, EaseOutElasticInterpolator.class, EaseInOutElasticInterpolator.class, EaseInExpoInterpolator.class, EaseOutExpoInterpolator.class, EaseInOutExpoInterpolator.class, EaseInQuadInterpolator.class, EaseOutQuadInterpolator.class, EaseInOutQuadInterpolator.class, EaseInQuartInterpolator.class, EaseOutQuartInterpolator.class, EaseInOutQuartInterpolator.class, EaseInQuintInterpolator.class, EaseOutQuintInterpolator.class, EaseInOutQuintInterpolator.class, EaseInSineInterpolator.class, EaseOutSineInterpolator.class, EaseInOutSineInterpolator.class }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.Main_recyclerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); ArrayList<Class> easingInterpolators = new ArrayList<>(); easingInterpolators.addAll(Arrays.asList(EASING_INTERPOLATOR)); mRecyclerView.setAdapter(new DemoAdapter(this, easingInterpolators)); } }
package bdv.viewer; import static bdv.viewer.DisplayMode.FUSED; import static bdv.viewer.DisplayMode.FUSEDGROUP; import static bdv.viewer.DisplayMode.GROUP; import static bdv.viewer.DisplayMode.SINGLE; import static bdv.viewer.VisibilityAndGrouping.Event.CURRENT_GROUP_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.CURRENT_SOURCE_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.DISPLAY_MODE_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.GROUP_ACTIVITY_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.GROUP_NAME_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.SOURCE_ACTVITY_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.SOURCE_TO_GROUP_ASSIGNMENT_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.VISIBILITY_CHANGED; import java.util.Arrays; import java.util.List; import java.util.SortedSet; import java.util.concurrent.CopyOnWriteArrayList; import bdv.viewer.state.SourceGroup; import bdv.viewer.state.SourceState; import bdv.viewer.state.ViewerState; /** * Manage visibility and currentness of sources and groups, as well as grouping * of sources, and display mode. * * @author Tobias Pietzsch &lt;tobias.pietzsch@gmail.com&gt; */ public class VisibilityAndGrouping { public static final class Event { public static final int CURRENT_SOURCE_CHANGED = 0; public static final int CURRENT_GROUP_CHANGED = 1; public static final int SOURCE_ACTVITY_CHANGED = 2; public static final int GROUP_ACTIVITY_CHANGED = 3; public static final int DISPLAY_MODE_CHANGED = 4; public static final int SOURCE_TO_GROUP_ASSIGNMENT_CHANGED = 5; public static final int GROUP_NAME_CHANGED = 6; public static final int VISIBILITY_CHANGED = 7; public static final int NUM_SOURCES_CHANGED = 8; public static final int NUM_GROUPS_CHANGED = 9; public final int id; public final VisibilityAndGrouping visibilityAndGrouping; public Event( final int id, final VisibilityAndGrouping v ) { this.id = id; this.visibilityAndGrouping = v; } } public interface UpdateListener { public void visibilityChanged( Event e ); } protected final CopyOnWriteArrayList< UpdateListener > updateListeners; protected final ViewerState state; public VisibilityAndGrouping( final ViewerState viewerState ) { updateListeners = new CopyOnWriteArrayList<>(); state = viewerState; } public int numSources() { return state.numSources(); } public List< SourceState< ? > > getSources() { return state.getSources(); } public int numGroups() { return state.numSourceGroups(); } public List< SourceGroup > getSourceGroups() { return state.getSourceGroups(); } public synchronized DisplayMode getDisplayMode() { return state.getDisplayMode(); } public synchronized void setDisplayMode( final DisplayMode displayMode ) { state.setDisplayMode( displayMode ); checkVisibilityChange(); update( DISPLAY_MODE_CHANGED ); } public synchronized int getCurrentSource() { return state.getCurrentSource(); } /** * TODO * * @param sourceIndex */ public synchronized void setCurrentSource( final int sourceIndex ) { if ( sourceIndex < 0 || sourceIndex >= numSources() ) return; state.setCurrentSource( sourceIndex ); checkVisibilityChange(); update( CURRENT_SOURCE_CHANGED ); }; public synchronized void setCurrentSource( final Source< ? > source ) { state.setCurrentSource( source ); checkVisibilityChange(); update( CURRENT_SOURCE_CHANGED ); }; public synchronized boolean isSourceActive( final int sourceIndex ) { if ( sourceIndex < 0 || sourceIndex >= numSources() ) return false; return state.getSources().get( sourceIndex ).isActive(); } /** * Set the source active (visible in fused mode) or inactive. * * @param sourceIndex * @param isActive */ public synchronized void setSourceActive( final int sourceIndex, final boolean isActive ) { if ( sourceIndex < 0 || sourceIndex >= numSources() ) return; state.getSources().get( sourceIndex ).setActive( isActive ); update( SOURCE_ACTVITY_CHANGED ); checkVisibilityChange(); } /** * Set the source active (visible in fused mode) or inactive. * * @param source * @param isActive */ public synchronized void setSourceActive( final Source< ? > source, final boolean isActive ) { for ( final SourceState< ? > s : state.getSources() ) { if ( s.getSpimSource().equals( source ) ) s.setActive( isActive ); } update( SOURCE_ACTVITY_CHANGED ); checkVisibilityChange(); } public synchronized int getCurrentGroup() { return state.getCurrentGroup(); } /** * TODO * * @param groupIndex */ public synchronized void setCurrentGroup( final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.setCurrentGroup( groupIndex ); checkVisibilityChange(); update( CURRENT_GROUP_CHANGED ); final SortedSet< Integer > ids = state.getSourceGroups().get( groupIndex ).getSourceIds(); if ( !ids.isEmpty() ) { state.setCurrentSource( ids.first() ); update( CURRENT_SOURCE_CHANGED ); } } public synchronized boolean isGroupActive( final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return false; return state.getSourceGroups().get( groupIndex ).isActive(); } /** * Set the group active (visible in fused mode) or inactive. * * @param groupIndex * @param isActive */ public synchronized void setGroupActive( final int groupIndex, final boolean isActive ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.getSourceGroups().get( groupIndex ).setActive( isActive ); update( GROUP_ACTIVITY_CHANGED ); checkVisibilityChange(); } public synchronized void setGroupName( final int groupIndex, final String name ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.getSourceGroups().get( groupIndex ).setName( name ); update( GROUP_NAME_CHANGED ); } public synchronized void addSourceToGroup( final int sourceIndex, final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.getSourceGroups().get( groupIndex ).addSource( sourceIndex ); update( SOURCE_TO_GROUP_ASSIGNMENT_CHANGED ); checkVisibilityChange(); } public synchronized void removeSourceFromGroup( final int sourceIndex, final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.getSourceGroups().get( groupIndex ).removeSource( sourceIndex ); update( SOURCE_TO_GROUP_ASSIGNMENT_CHANGED ); checkVisibilityChange(); } /** * TODO * @param index */ public synchronized void setCurrentGroupOrSource( final int index ) { if ( isGroupingEnabled() ) setCurrentGroup( index ); else setCurrentSource( index ); } /** * TODO * @param index */ public synchronized void toggleActiveGroupOrSource( final int index ) { if ( isGroupingEnabled() ) setGroupActive( index, !isGroupActive( index ) ); else setSourceActive( index, !isSourceActive( index ) ); } public synchronized boolean isGroupingEnabled() { final DisplayMode mode = state.getDisplayMode(); return ( mode == GROUP ) || ( mode == FUSEDGROUP ); } public synchronized boolean isFusedEnabled() { final DisplayMode mode = state.getDisplayMode(); return ( mode == FUSED ) || ( mode == FUSEDGROUP ); } public synchronized void setGroupingEnabled( final boolean enable ) { setDisplayMode( isFusedEnabled() ? ( enable ? FUSEDGROUP : FUSED ) : ( enable ? GROUP : SINGLE ) ); } public synchronized void setFusedEnabled( final boolean enable ) { setDisplayMode( isGroupingEnabled() ? ( enable ? FUSEDGROUP : GROUP ) : ( enable ? FUSED : SINGLE ) ); } public synchronized boolean isSourceVisible( final int sourceIndex ) { return state.isSourceVisible( sourceIndex ); } protected boolean[] previousVisibleSources = null; protected boolean[] currentVisibleSources = null; protected void checkVisibilityChange() { final boolean[] tmp = previousVisibleSources; previousVisibleSources = currentVisibleSources; currentVisibleSources = tmp; final int n = numSources(); if ( currentVisibleSources == null || currentVisibleSources.length != n ) currentVisibleSources = new boolean[ n ]; Arrays.fill( currentVisibleSources, false ); for ( final int i : state.getVisibleSourceIndices() ) currentVisibleSources[ i ] = true; if ( previousVisibleSources == null || previousVisibleSources.length != n ) { update( VISIBILITY_CHANGED ); return; } for ( int i = 0; i < currentVisibleSources.length; ++i ) if ( currentVisibleSources[ i ] != previousVisibleSources[ i ] ) { update( VISIBILITY_CHANGED ); return; } } protected void update( final int id ) { final Event event = new Event( id, this ); for ( final UpdateListener l : updateListeners ) l.visibilityChanged( event ); } public void addUpdateListener( final UpdateListener l ) { updateListeners.add( l ); } public void removeUpdateListener( final UpdateListener l ) { updateListeners.remove( l ); } }
package com.pxh.richedittext; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
package cgeo.geocaching.connector.ox; import cgeo.geocaching.Geocache; import cgeo.geocaching.files.GPX10Parser; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.NonNull; public class OXGPXParser extends GPX10Parser { private final boolean isDetailed; public OXGPXParser(final int listIdIn, final boolean isDetailed) { super(listIdIn); this.isDetailed = isDetailed; } @Override protected void afterParsing(final Geocache cache) { cache.setUpdated(System.currentTimeMillis()); if (isDetailed) { cache.setDetailedUpdate(cache.getUpdated()); cache.setDetailed(true); } removeTitleFromShortDescription(cache); } /** * The short description of OX caches contains "title by owner, type(T/D/Awesomeness)". That is a lot of * duplication. Additionally a space between type and (T/D/Awesomeness) is introduced. * * @param cache */ private static void removeTitleFromShortDescription(final @NonNull Geocache cache) { cache.setShortDescription(StringUtils.replace(StringUtils.trim(StringUtils.substringAfterLast(cache.getShortDescription(), ",")), "(", " (")); } }
package moe.minori.pgpclipper; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ClipDescription; import android.content.ClipboardManager; import android.content.Intent; import android.os.Build; import android.os.IBinder; import android.util.Log; import java.util.Objects; import androidx.core.app.NotificationCompat; import moe.minori.pgpclipper.activities.PGPClipperResultShowActivity; import moe.minori.pgpclipper.util.PGPBlockDetector; public class PGPClipperService extends Service { private static final String CHANNEL_ID = "PGPCLIPPER_NOTIFICATION"; ClipboardManager clipboardManager; ClipboardManager.OnPrimaryClipChangedListener onPrimaryClipChangedListener; public static final String TRY_DECRYPT = "TRY_DECRYPT"; public static final String DATA = "DATA"; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); startClipboardMonitoring(); } @Override public void onDestroy() { super.onDestroy(); stopClipboardMonitoring(); } private void startClipboardMonitoring() { clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); if (clipboardManager != null) { clipboardManager.addPrimaryClipChangedListener(onPrimaryClipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() { @Override public void onPrimaryClipChanged() { Log.d("PGPClipperService", "Clipboard data change detected!"); // get current clipboard data to string String currentData; if (clipboardManager.hasPrimaryClip() && Objects.requireNonNull(clipboardManager.getPrimaryClipDescription()).hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) { try { currentData = Objects.requireNonNull(clipboardManager.getPrimaryClip()).getItemAt(0).getText().toString(); } catch (NullPointerException e) { // should not happen since clipboard contains text, but returned null. // best effort String parsing try { currentData = clipboardManager.getPrimaryClip().getItemAt(0).coerceToText(PGPClipperService.this).toString(); } catch (Exception e2) { // best attempt failed... return this method return; } } } else { return; } // tidy once currentData = PGPBlockDetector.pgpInputTidy(currentData); // check if this contains ASCII armored PGP data if (PGPBlockDetector.isBlockPresent(currentData)) { // notify user NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Intent intentToLaunchWhenNotificationClicked = new Intent(getApplicationContext(), PGPClipperService.class); intentToLaunchWhenNotificationClicked.putExtra(TRY_DECRYPT, true); intentToLaunchWhenNotificationClicked.putExtra(DATA, currentData); PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intentToLaunchWhenNotificationClicked, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_UPDATE_CURRENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this notificationManager.createNotificationChannel(channel); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID) .setSmallIcon(R.drawable.ic_noti) .setTicker(getString(R.string.NotificationTickerText)) .setContentTitle(getString(R.string.NotificationTitleText)) .setContentText(getString(R.string.NotificationContentText)) .setDefaults(Notification.DEFAULT_LIGHTS) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_MAX) .setWhen(System.currentTimeMillis()) .setAutoCancel(true); notificationManager.notify(8591274, notificationBuilder.build()); } } }); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("PGPClipperService", "onStartCommand called!"); if (intent != null) { if (intent.getBooleanExtra(TRY_DECRYPT, false)) { Log.d("PGPClipperService", "Trying Decryption/Verification"); Intent launchActivity = new Intent(getApplicationContext(), PGPClipperResultShowActivity.class); launchActivity.putExtra(DATA, intent.getStringExtra(DATA)); launchActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(launchActivity); } } return START_STICKY; } private void stopClipboardMonitoring() { if (onPrimaryClipChangedListener != null) { clipboardManager.removePrimaryClipChangedListener(onPrimaryClipChangedListener); } } }
package br.com.caelum.brutal.dao; import static org.hibernate.criterion.Order.desc; import static org.hibernate.criterion.Projections.rowCount; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.gt; import java.util.List; import javax.inject.Inject; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import br.com.caelum.brutal.dao.WithUserPaginatedDAO.OrderType; import br.com.caelum.brutal.dao.WithUserPaginatedDAO.UserRole; import br.com.caelum.brutal.model.News; import br.com.caelum.brutal.model.User; import br.com.caelum.brutal.model.interfaces.RssContent; public class NewsDAO implements PaginatableDAO { private static final long SPAM_BOUNDARY = -5; private WithUserPaginatedDAO<News> withAuthor; private Session session; private QueryFilter invisible; private VisibleNewsFilter visibleFilter; @Deprecated public NewsDAO() { } @Inject public NewsDAO(Session session, ModeratorOrVisibleNewsFilter moderatorOrVisible, VisibleNewsFilter visibleFilter) { this.session = session; this.invisible = moderatorOrVisible; this.visibleFilter = visibleFilter; this.withAuthor = new WithUserPaginatedDAO<News>(session, News.class, UserRole.AUTHOR, moderatorOrVisible); } @SuppressWarnings("unchecked") public List<News> allVisible(Integer initPage, Integer pageSize) { Criteria criteria = defaultPagedCriteria(initPage, pageSize) .createAlias("n.comments.comments", "c", Criteria.LEFT_JOIN); return addModeratorOrApprovedFilter(criteria).list(); } @SuppressWarnings("unchecked") public List<News> allVisibleAndApproved(int size) { return addApprovedFilter(defaultCriteria(size)).list(); } public List<News> postsToPaginateBy(User user, OrderType orderByWhat, Integer page) { return withAuthor.by(user,orderByWhat, page); } @Override public Long countWithAuthor(User author) { return withAuthor.count(author); } @Override public Long numberOfPagesTo(User author) { return withAuthor.numberOfPagesTo(author); } public void save(News news) { session.save(news); } public long numberOfPages(Integer pageSize) { Criteria criteria = session.createCriteria(News.class, "n") .add(and(criterionSpamFilter())) .setProjection(rowCount()) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); Long totalItems = (Long) addModeratorOrApprovedFilter(criteria).list().get(0); return calculatePages(totalItems, pageSize); } @SuppressWarnings("unchecked") public List<RssContent> orderedByCreationDate(int maxResults) { Criteria criteria = session.createCriteria(News.class, "n") .addOrder(desc("n.createdAt")) .setMaxResults(maxResults); return addApprovedFilter(criteria).list(); } @SuppressWarnings("unchecked") public List<News> hotNews() { Query query = session.createQuery("select news from News news " + "where news.approved = true " + "order by news.createdAt desc"); return query.setMaxResults(5).list(); } private Criteria addApprovedFilter(Criteria criteria) { return visibleFilter.addFilter("n", criteria); } private Criterion criterionSpamFilter() { return gt("n.voteCount", SPAM_BOUNDARY); } private int firstResultOf(Integer initPage, Integer pageSize) { return pageSize * (initPage-1); } private Criteria addModeratorOrApprovedFilter(Criteria criteria) { return invisible.addFilter("n", criteria); } private long calculatePages(Long count, Integer pageSize) { long result = count/pageSize.longValue(); if (count % pageSize.longValue() != 0) { result++; } return result; } private Criteria defaultCriteria(Integer maxResults) { Criteria criteria = session.createCriteria(News.class, "n") .createAlias("n.information", "ni") .createAlias("n.author", "na") .createAlias("n.lastTouchedBy", "nl") .add(criterionSpamFilter()) .addOrder(desc("n.lastUpdatedAt")) .setMaxResults(maxResults) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria; } private Criteria defaultPagedCriteria(Integer initPage, Integer pageSize) { return defaultCriteria(pageSize).setFirstResult(firstResultOf(initPage, pageSize)); } }
package info.nightscout.utils; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; public class BolusWizard { // Inputs Profile specificProfile = null; TempTarget tempTarget; public Integer carbs = 0; Double bg = 0d; Double correction; Boolean includeBolusIOB = true; Boolean includeBasalIOB = true; Boolean superBolus = false; Boolean trend = false; // Intermediate public Double sens = 0d; public Double ic = 0d; public GlucoseStatus glucoseStatus; public Double targetBGLow = 0d; public Double targetBGHigh = 0d; public Double bgDiff = 0d; public Double insulinFromBG = 0d; public Double insulinFromCarbs = 0d; public Double insulingFromBolusIOB = 0d; public Double insulingFromBasalsIOB = 0d; public Double insulinFromCorrection = 0d; public Double insulinFromSuperBolus = 0d; public Double insulinFromCOB = 0d; public Double insulinFromTrend = 0d; // Result public Double calculatedTotalInsulin = 0d; public Double totalBeforePercentageAdjustment = 0d; public Double carbsEquivalent = 0d; public Double doCalc(Profile specificProfile, TempTarget tempTarget, Integer carbs, Double cob, Double bg, Double correction, Boolean includeBolusIOB, Boolean includeBasalIOB, Boolean superBolus, Boolean trend) { return doCalc(specificProfile, tempTarget, carbs, cob, bg, correction, 100d, includeBolusIOB, includeBasalIOB, superBolus, trend); } public Double doCalc(Profile specificProfile, TempTarget tempTarget, Integer carbs, Double cob, Double bg, Double correction, double percentageCorrection, Boolean includeBolusIOB, Boolean includeBasalIOB, Boolean superBolus, Boolean trend) { this.specificProfile = specificProfile; this.tempTarget = tempTarget; this.carbs = carbs; this.bg = bg; this.correction = correction; this.includeBolusIOB = includeBolusIOB; this.includeBasalIOB = includeBasalIOB; this.superBolus = superBolus; this.trend = trend; // Insulin from BG sens = specificProfile.getIsf(); targetBGLow = specificProfile.getTargetLow(); targetBGHigh = specificProfile.getTargetHigh(); if (tempTarget != null) { targetBGLow = Profile.fromMgdlToUnits(tempTarget.low, specificProfile.getUnits()); targetBGHigh = Profile.fromMgdlToUnits(tempTarget.high, specificProfile.getUnits()); } if (bg >= targetBGLow && bg <= targetBGHigh) { bgDiff = 0d; } else if (bg <= targetBGLow) { bgDiff = bg - targetBGLow; } else { bgDiff = bg - targetBGHigh; } insulinFromBG = bg != 0d ? bgDiff / sens : 0d; // Insulin from 15 min trend glucoseStatus = GlucoseStatus.getGlucoseStatusData(); if (glucoseStatus != null && trend) { insulinFromTrend = (Profile.fromMgdlToUnits(glucoseStatus.short_avgdelta, specificProfile.getUnits()) * 3) / sens; } // Insuling from carbs ic = specificProfile.getIc(); insulinFromCarbs = carbs / ic; insulinFromCOB = cob / ic; // Insulin from IOB // IOB calculation TreatmentsInterface treatments = MainApp.getConfigBuilder(); treatments.updateTotalIOBTreatments(); IobTotal bolusIob = treatments.getLastCalculationTreatments().round(); treatments.updateTotalIOBTempBasals(); IobTotal basalIob = treatments.getLastCalculationTempBasals().round(); insulingFromBolusIOB = includeBolusIOB ? -bolusIob.iob : 0d; insulingFromBasalsIOB = includeBasalIOB ? -basalIob.basaliob : 0d; // Insulin from correction insulinFromCorrection = correction; // Insulin from superbolus for 2h. Get basal rate now and after 1h if (superBolus) { insulinFromSuperBolus = specificProfile.getBasal(); long timeAfter1h = System.currentTimeMillis(); timeAfter1h += 60L * 60 * 1000; insulinFromSuperBolus += specificProfile.getBasal(timeAfter1h); } // Total calculatedTotalInsulin = insulinFromBG + insulinFromTrend + insulinFromCarbs + insulingFromBolusIOB + insulingFromBasalsIOB + insulinFromCorrection + insulinFromSuperBolus + insulinFromCOB; // Percentage adjustment totalBeforePercentageAdjustment = calculatedTotalInsulin; if (calculatedTotalInsulin > 0) { calculatedTotalInsulin = calculatedTotalInsulin * percentageCorrection / 100d; } if (calculatedTotalInsulin < 0) { carbsEquivalent = -calculatedTotalInsulin * ic; calculatedTotalInsulin = 0d; } double bolusStep = ConfigBuilderPlugin.getActivePump().getPumpDescription().bolusStep; calculatedTotalInsulin = Round.roundTo(calculatedTotalInsulin, bolusStep); return calculatedTotalInsulin; } }
package com.google.refine.importing; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import com.google.refine.Jsonizable; import com.google.refine.ProjectMetadata; import com.google.refine.model.Project; import com.google.refine.util.JSONUtilities; public class ImportingJob implements Jsonizable { final public long id; final public File dir; // Temporary directory where the data about this job is stored private JSONObject config; public Project project; public ProjectMetadata metadata; public long lastTouched; public boolean updating; public boolean canceled; final private Object lock = new Object(); public ImportingJob(long id, File dir) { this.id = id; this.dir = dir; JSONObject cfg = new JSONObject(); JSONUtilities.safePut(cfg, "state", "new"); JSONUtilities.safePut(cfg, "hasData", false); this.config = cfg; dir.mkdirs(); } public JSONObject getOrCreateDefaultConfig() { return config; } public void setState(String state) { synchronized(config) { JSONUtilities.safePut(config, "state", state); } } public void setError(List<Exception> exceptions) { synchronized(config) { JSONUtilities.safePut(config, "errors", DefaultImportingController.convertErrorsToJsonArray(exceptions)); setState("error"); } } public void setProjectID(long projectID) { synchronized (config) { JSONUtilities.safePut(config, "projectID", projectID); } } public void setProgress(int percent, String message) { synchronized (config) { JSONObject progress = JSONUtilities.getObject(config, "progress"); if (progress == null) { progress = new JSONObject(); JSONUtilities.safePut(config, "progress", progress); } JSONUtilities.safePut(progress, "message", message); JSONUtilities.safePut(progress, "percent", percent); JSONUtilities.safePut(progress, "memory", Runtime.getRuntime().totalMemory() / 1000000); JSONUtilities.safePut(progress, "maxmemory", Runtime.getRuntime().maxMemory() / 1000000); } } public void setFileSelection(JSONArray fileSelectionArray) { synchronized (config) { JSONUtilities.safePut(config, "fileSelection", fileSelectionArray); } } public void setRankedFormats(JSONArray rankedFormats) { synchronized (config) { JSONUtilities.safePut(config, "rankedFormats", rankedFormats); } } public JSONObject getRetrievalRecord() { synchronized(config) { return JSONUtilities.getObject(config,"retrievalRecord"); } } public List<JSONObject> getSelectedFileRecords() { List<JSONObject> results = new ArrayList<JSONObject>(); JSONObject retrievalRecord = JSONUtilities.getObject(config,"retrievalRecord"); if (retrievalRecord != null) { JSONArray fileRecordArray = JSONUtilities.getArray(retrievalRecord, "files"); if (fileRecordArray != null) { JSONArray fileSelectionArray = JSONUtilities.getArray(config,"fileSelection"); if (fileSelectionArray != null) { for (int i = 0; i < fileSelectionArray.length(); i++) { int index = JSONUtilities.getIntElement(fileSelectionArray, i, -1); if (index >= 0 && index < fileRecordArray.length()) { results.add(JSONUtilities.getObjectElement(fileRecordArray, index)); } } } } } return results; } public void touch() { lastTouched = System.currentTimeMillis(); } public void prepareNewProject() { if (project != null) { project.dispose(); } project = new Project(); metadata = new ProjectMetadata(); } public void dispose() { if (project != null) { project.dispose(); project = null; } metadata = null; try { FileUtils.deleteDirectory(dir); } catch (IOException e) { } } public File getRawDataDir() { File dir2 = new File(dir, "raw-data"); dir2.mkdirs(); return dir2; } @Override public void write(JSONWriter writer, Properties options) throws JSONException { synchronized(lock) { writer.object(); writer.key("config"); writer.value(config); writer.endObject(); } } }
package nerd.tuxmobil.fahrplan.congress; import android.text.format.Time; public class Lecture { public String title; public String subtitle; public int day; public String room; public int startTime; // minutes since day start public int duration; // minutes public String speakers; public String track; public String lecture_id; public String type; public String lang; public String abstractt; public String description; public int relStartTime; public String links; public String date; public boolean highlight; public boolean has_alarm; public long dateUTC; public int room_index; public String recordingLicense; public boolean recordingOptOut; public static final boolean RECORDING_OPTOUT_ON = true; public static final boolean RECORDING_OPTOUT_OFF = false; public boolean changed_title; public boolean changed_subtitle; public boolean changed_room; public boolean changed_day; public boolean changed_time; public boolean changed_duration; public boolean changed_speakers; public boolean changed_recordingOptOut; public boolean changed_language; public boolean changed_track; public boolean changed_isNew; public boolean changed_isCanceled; public Lecture(String lecture_id) { title = ""; subtitle = ""; day = 0; room = ""; startTime = 0; duration = 0; speakers = ""; track = ""; type = ""; lang = ""; abstractt = ""; description = ""; relStartTime = 0; links = ""; date = ""; this.lecture_id = lecture_id; highlight = false; has_alarm = false; dateUTC = 0; room_index = 0; recordingLicense = ""; recordingOptOut = RECORDING_OPTOUT_OFF; changed_title = false; changed_subtitle = false; changed_room = false; changed_day = false; changed_speakers = false; changed_recordingOptOut = false; changed_language = false; changed_track = false; changed_isNew = false; changed_time = false; changed_duration = false; changed_isCanceled = false; } public static int parseStartTime(String text) { String time[] = text.split(":"); return Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]); } public static int parseDuration(String text) { String time[] = text.split(":"); return Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]); } public Time getTime() { Time t = new Time(); String[] splitDate = date.split("-"); t.setToNow(); t.year = Integer.parseInt(splitDate[0]); t.month = Integer.parseInt(splitDate[1]) - 1; t.monthDay = Integer.parseInt(splitDate[2]); t.hour = relStartTime / 60; t.minute = relStartTime % 60; return t; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Lecture lecture = (Lecture) o; if (day != lecture.day) return false; if (duration != lecture.duration) return false; if (recordingOptOut != lecture.recordingOptOut) return false; if (startTime != lecture.startTime) return false; if (date != null ? !date.equals(lecture.date) : lecture.date != null) return false; if (lang != null ? !lang.equals(lecture.lang) : lecture.lang != null) return false; if (!lecture_id.equals(lecture.lecture_id)) return false; if (recordingLicense != null ? !recordingLicense.equals(lecture.recordingLicense) : lecture.recordingLicense != null) return false; if (room != null ? !room.equals(lecture.room) : lecture.room != null) return false; if (speakers != null ? !speakers.equals(lecture.speakers) : lecture.speakers != null) return false; if (subtitle != null ? !subtitle.equals(lecture.subtitle) : lecture.subtitle != null) return false; if (!title.equals(lecture.title)) return false; if (track != null ? !track.equals(lecture.track) : lecture.track != null) return false; if (type != null ? !type.equals(lecture.type) : lecture.type != null) return false; if (dateUTC != lecture.dateUTC) return false; return true; } @Override public int hashCode() { int result = title.hashCode(); result = 31 * result + (subtitle != null ? subtitle.hashCode() : 0); result = 31 * result + day; result = 31 * result + (room != null ? room.hashCode() : 0); result = 31 * result + startTime; result = 31 * result + duration; result = 31 * result + (speakers != null ? speakers.hashCode() : 0); result = 31 * result + (track != null ? track.hashCode() : 0); result = 31 * result + lecture_id.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); result = 31 * result + (date != null ? date.hashCode() : 0); result = 31 * result + (recordingLicense != null ? recordingLicense.hashCode() : 0); result = 31 * result + (recordingOptOut ? 1 : 0); result = 31 * result + (int) dateUTC; return result; } }
package codechicken.lib.data; import com.google.common.base.Charsets; import io.netty.handler.codec.EncoderException; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTSizeTracker; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public class MCDataUtils { /** * PacketBuffer.readVarIntFromBuffer */ public static int readVarInt(MCDataInput in) { int i = 0; int j = 0; byte b0; do { b0 = in.readByte(); i |= (b0 & 127) << j++ * 7; if (j > 5) { throw new RuntimeException("VarInt too big"); } } while ((b0 & 128) == 128); return i; } public static int readVarShort(MCDataInput in) { int low = in.readUShort(); int high = 0; if ((low & 0x8000) != 0) { low = low & 0x7FFF; high = in.readUByte(); } return ((high & 0xFF) << 15) | low; } public static long readVarLong(MCDataInput in) { long i = 0L; int j = 0; while (true) { byte b0 = in.readByte(); i |= (long) (b0 & 127) << j++ * 7; if (j > 10) { throw new RuntimeException("VarLong too big"); } if ((b0 & 128) != 128) { break; } } return i; } public static String readString(MCDataInput in) { return new String(in.readArray(in.readVarInt()), Charsets.UTF_8); } public static ItemStack readItemStack(MCDataInput in) { ItemStack item = ItemStack.EMPTY; short itemID = in.readShort(); if (itemID >= 0) { int stackSize = in.readVarInt(); short damage = in.readShort(); item = new ItemStack(Item.getItemById(itemID), stackSize, damage); item.setTagCompound(in.readNBTTagCompound()); } return item; } public static FluidStack readFluidStack(MCDataInput in) { FluidStack fluid = null; String fluidName = in.readString(); if (fluidName.length() > 0) { fluid = new FluidStack(FluidRegistry.getFluid(fluidName), in.readVarInt(), in.readNBTTagCompound()); } return fluid; } @Nullable public static NBTTagCompound readNBTTagCompound(MCDataInput input) { byte flag = input.readByte(); if (flag == 0) { return null; } else if (flag == 1) { try { return CompressedStreamTools.read(new DataInputStream(new MCDataInputStream(input)), new NBTSizeTracker(2097152L)); } catch (IOException e) { throw new EncoderException(e); } } else { throw new EncoderException("Invalid flag for readNBTTagCompound. Expected 0 || 1 Got: " + flag + " Possible incorrect read order?"); } } /** * PacketBuffer.writeVarIntToBuffer */ public static void writeVarInt(MCDataOutput out, int i) { while ((i & 0xffffff80) != 0) { out.writeByte(i & 0x7F | 0x80); i >>>= 7; } out.writeByte(i); } /** * ByteBufUtils.readVarShort */ public static void writeVarShort(MCDataOutput out, int s) { int low = s & 0x7FFF; int high = (s & 0x7F8000) >> 15; if (high != 0) { low |= 0x8000; } out.writeShort(low); if (high != 0) { out.writeByte(high); } } public static void writeVarLong(MCDataOutput out, long value) { while ((value & -128L) != 0L) { out.writeByte((int) (value & 127L) | 128); value >>>= 7; } out.writeByte((int) value); } /** * PacketBuffer.writeString */ public static void writeString(MCDataOutput out, String string) { byte[] abyte = string.getBytes(Charsets.UTF_8); if (abyte.length > 32767) { throw new EncoderException("String too big (was " + string.length() + " bytes encoded, max " + 32767 + ")"); } out.writeVarInt(abyte.length); out.writeArray(abyte); } /** * Supports large stacks by writing stackSize as a varInt */ public static void writeItemStack(MCDataOutput out, ItemStack stack) { if (stack.isEmpty()) { out.writeShort(-1); } else { out.writeShort(Item.getIdFromItem(stack.getItem())); out.writeVarInt(stack.getCount()); out.writeShort(stack.getItemDamage()); out.writeNBTTagCompound(stack.getItem().getShareTag() ? stack.getTagCompound() : null); } } public static void writeFluidStack(MCDataOutput out, FluidStack fluid) { if (fluid == null || FluidRegistry.getFluidName(fluid) == null) { out.writeString(""); } else { out.writeString(FluidRegistry.getFluidName(fluid)); out.writeVarInt(fluid.amount); out.writeNBTTagCompound(fluid.tag); } } public static void writeNBTTagCompount(@Nonnull MCDataOutput out, @Nullable NBTTagCompound tag) { if (tag == null) { out.writeByte(0); return; } try { out.writeByte(1); CompressedStreamTools.write(tag, new DataOutputStream(new MCDataOutputStream(out))); } catch (IOException e) { throw new EncoderException(e); } } }
package com.bladecoder.ink.runtime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.Stack; import com.bladecoder.ink.runtime.CallStack.Element; /** * A Story is the core class that represents a complete Ink narrative, and * manages the evaluation and state of it. */ public class Story extends RTObject implements VariablesState.VariableChanged { /** * General purpose delegate definition for bound EXTERNAL function * definitions from ink. Note that this version isn't necessary if you have * a function with three arguments or less - see the overloads of * BindExternalFunction. */ public interface ExternalFunction { Object call(Object[] args) throws Exception; } // Version numbers are for engine itself and story file, rather // than the story state save format (which is um, currently nonexistant) // -- old engine, new format: always fail // -- new engine, old format: possibly cope, based on this number // When incrementing the version number above, the question you // should ask yourself is: // -- Will the engine be able to load an old story file from // before I made these changes to the engine? // If possible, you should support it, though it's not as // critical as loading old save games, since it's an // in-development problem only. /** * Delegate definition for variable observation - see ObserveVariable. */ public interface VariableObserver { void call(String variableName, Object newValue); } /** * The current version of the ink story file format. */ public static final int inkVersionCurrent = 17; /** * The minimum legacy version of ink that can be loaded by the current * version of the code. */ public static final int inkVersionMinimumCompatible = 16; private Container mainContentContainer; private ListDefinitionsOrigin listsDefinitions; /** * An ink file can provide a fallback functions for when when an EXTERNAL * has been left unbound by the client, and the fallback function will be * called instead. Useful when testing a story in playmode, when it's not * possible to write a client-side C# external function, but you don't want * it to fail to run. */ private boolean allowExternalFunctionFallbacks; private HashMap<String, ExternalFunction> externals; private boolean hasValidatedExternals; private StoryState state; private Container temporaryEvaluationContainer; private HashMap<String, List<VariableObserver>> variableObservers; private HashSet<Container> prevContainerSet; // Warning: When creating a Story using this constructor, you need to // call ResetState on it before use. Intended for compiler use only. // For normal use, use the constructor that takes a json string. Story(Container contentContainer, List<ListDefinition> lists) { mainContentContainer = contentContainer; if (lists != null) { listsDefinitions = new ListDefinitionsOrigin(lists); } externals = new HashMap<String, ExternalFunction>(); } Story(Container contentContainer) { this(contentContainer, null); } /** * Construct a Story Object using a JSON String compiled through inklecate. */ public Story(String jsonString) throws Exception { this((Container) null); HashMap<String, Object> rootObject = SimpleJson.textToHashMap(jsonString); Object versionObj = rootObject.get("inkVersion"); if (versionObj == null) throw new Exception("ink version number not found. Are you sure it's a valid .ink.json file?"); int formatFromFile = versionObj instanceof String ? Integer.parseInt((String) versionObj) : (int) versionObj; if (formatFromFile > inkVersionCurrent) { throw new Exception("Version of ink used to build story was newer than the current verison of the engine"); } else if (formatFromFile < inkVersionMinimumCompatible) { throw new Exception( "Version of ink used to build story is too old to be loaded by this version of the engine"); } else if (formatFromFile != inkVersionCurrent) { System.out.println( "WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising."); } Object rootToken = rootObject.get("root"); if (rootToken == null) throw new Exception("Root node for ink not found. Are you sure it's a valid .ink.json file?"); Object listDefsObj = rootObject.get("listDefs"); if (listDefsObj != null) { listsDefinitions = Json.jTokenToListDefinitions(listDefsObj); } mainContentContainer = Json.jTokenToRuntimeObject(rootToken) instanceof Container ? (Container) Json.jTokenToRuntimeObject(rootToken) : null; resetState(); } void addError(String message, boolean useEndLineNumber) throws Exception { DebugMetadata dm = currentDebugMetadata(); if (dm != null) { int lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber; message = String.format("RUNTIME ERROR: '%s' line %d: %s", dm.fileName, lineNum, message); } else if( state.getCurrentPath() != null ) { message = String.format ("RUNTIME ERROR: (%s): %s", state.getCurrentPath().toString(), message); } else { message = "RUNTIME ERROR: " + message; } state.addError(message); // In a broken state don't need to know about any other errors. state.forceEnd(); } void Assert(boolean condition, Object... formatParams) throws Exception { Assert(condition, null, formatParams); } void Assert(boolean condition, String message, Object... formatParams) throws Exception { if (condition == false) { if (message == null) { message = "Story assert"; } if (formatParams != null && formatParams.length > 0) { message = String.format(message, formatParams); } throw new Exception(message + " " + currentDebugMetadata()); } } /** * Most general form of function binding that returns an Object and takes an * array of Object parameters. The only way to bind a function with more * than 3 arguments. * * @param funcName * EXTERNAL ink function name to bind to. * @param func * The Java function to bind. */ public void bindExternalFunction(String funcName, ExternalFunction func) throws Exception { Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound."); externals.put(funcName, func); } @SuppressWarnings("unchecked") public <T> T tryCoerce(Object value, Class<T> type) throws Exception { if (value == null) return null; if (type.isAssignableFrom(value.getClass())) return (T) value; if (value instanceof Float && type == Integer.class) { Integer intVal = (int) Math.round((Float) value); return (T) intVal; } if (value instanceof Integer && type == Float.class) { Float floatVal = Float.valueOf((Integer) value); return (T) floatVal; } if (value instanceof Integer && type == Boolean.class) { int intVal = (Integer) value; return (T) (intVal == 0 ? new Boolean(false) : new Boolean(true)); } if (type == String.class) { return (T) value.toString(); } Assert(false, "Failed to cast " + value.getClass().getCanonicalName() + " to " + type.getCanonicalName()); return null; } /** * Get any global tags associated with the story. These are defined as hash * tags defined at the very top of the story. * * @throws Exception */ public List<String> getGlobalTags() throws Exception { return tagsAtStartOfFlowContainerWithPathString(""); } /** * Gets any tags associated with a particular knot or knot.stitch. These are * defined as hash tags defined at the very top of a knot or stitch. * * @param path * The path of the knot or stitch, in the form "knot" or * "knot.stitch". * @throws Exception */ public List<String> tagsForContentAtPath(String path) throws Exception { return tagsAtStartOfFlowContainerWithPathString(path); } List<String> tagsAtStartOfFlowContainerWithPathString(String pathString) throws Exception { Path path = new Path(pathString); // Expected to be global story, knot or stitch Container flowContainer = null; RTObject c = contentAtPath(path); if (c instanceof Container) flowContainer = (Container) c; while (true) { RTObject firstContent = flowContainer.getContent().get(0); if (firstContent instanceof Container) flowContainer = (Container) firstContent; else break; } // Any initial tag objects count as the "main tags" associated with that // story/knot/stitch List<String> tags = null; for (RTObject c2 : flowContainer.getContent()) { Tag tag = null; if (c2 instanceof Tag) tag = (Tag) c2; if (tag != null) { if (tags == null) tags = new ArrayList<String>(); tags.add(tag.getText()); } else break; } return tags; } /** * Useful when debugging a (very short) story, to visualise the state of the * story. Add this call as a watch and open the extended text. A left-arrow * mark will denote the current point of the story. It's only recommended * that this is used on very short debug stories, since it can end up * generate a large quantity of text otherwise. */ public String buildStringOfHierarchy() { StringBuilder sb = new StringBuilder(); mainContentContainer.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject()); return sb.toString(); } void callExternalFunction(String funcName, int numberOfArguments) throws Exception { Container fallbackFunctionContainer = null; ExternalFunction func = externals.get(funcName); // Try to use fallback function? if (func == null) { if (allowExternalFunctionFallbacks) { RTObject contentAtPath = contentAtPath(new Path(funcName)); fallbackFunctionContainer = contentAtPath instanceof Container ? (Container) contentAtPath : null; Assert(fallbackFunctionContainer != null, "Trying to call EXTERNAL function '" + funcName + "' which has not been bound, and fallback ink function could not be found."); // Divert direct into fallback function and we're done state.getCallStack().push(PushPopType.Function); state.setDivertedTargetObject(fallbackFunctionContainer); return; } else { Assert(false, "Trying to call EXTERNAL function '" + funcName + "' which has not been bound (and ink fallbacks disabled)."); } } // Pop arguments ArrayList<Object> arguments = new ArrayList<Object>(); for (int i = 0; i < numberOfArguments; ++i) { Value<?> poppedObj = (Value<?>) state.popEvaluationStack(); Object valueObj = poppedObj.getValueObject(); arguments.add(valueObj); } // Reverse arguments from the order they were popped, // so they're the right way round again. Collections.reverse(arguments); // Run the function! Object funcResult = func.call(arguments.toArray()); // Convert return value (if any) to the a type that the ink engine can // use RTObject returnObj = null; if (funcResult != null) { returnObj = AbstractValue.create(funcResult); Assert(returnObj != null, "Could not create ink value from returned Object of type " + funcResult.getClass().getCanonicalName()); } else { returnObj = new Void(); } state.pushEvaluationStack(returnObj); } /** * Check whether more content is available if you were to call Continue() - * i.e. are we mid story rather than at a choice point or at the end. * * @return true if it's possible to call Continue() */ public boolean canContinue() { return state.canContinue(); } /** * Chooses the Choice from the currentChoices list with the given index. * Internally, this sets the current content path to that pointed to by the * Choice, ready to continue story evaluation. */ public void chooseChoiceIndex(int choiceIdx) throws Exception { List<Choice> choices = getCurrentChoices(); Assert(choiceIdx >= 0 && choiceIdx < choices.size(), "choice out of range"); // Replace callstack with the one from the thread at the choosing point, // so that we can jump into the right place in the flow. // This is important in case the flow was forked by a new thread, which // can create multiple leading edges for the story, each of // which has its own context. Choice choiceToChoose = choices.get(choiceIdx); state.getCallStack().setCurrentThread(choiceToChoose.getThreadAtGeneration()); choosePath(choiceToChoose.getchoicePoint().getChoiceTarget().getPath()); } void choosePath(Path p) throws Exception { state.setChosenPath(p); // Take a note of newly visited containers for read counts etc visitChangedContainersDueToDivert(); } /** * Change the current position of the story to the given path. From here you * can call Continue() to evaluate the next line. The path String is a * dot-separated path as used ly by the engine. These examples should work: * * myKnot myKnot.myStitch * * Note however that this won't necessarily work: * * myKnot.myStitch.myLabelledChoice * * ...because of the way that content is nested within a weave structure. * * @param path * A dot-separted path string, as specified above. * @param arguments * Optional set of arguments to pass, if path is to a knot that * takes them. */ public void choosePathString(String path, Object[] arguments) throws Exception { state.passArgumentsToEvaluationStack(arguments); choosePath(new Path(path)); } public void choosePathString(String path) throws Exception { choosePathString(path, null); } RTObject contentAtPath(Path path) throws Exception { return mainContentContainer().contentAtPath(path); } /** * Continue the story for one line of content, if possible. If you're not * sure if there's more content available, for example if you want to check * whether you're at a choice point or at the end of the story, you should * call canContinue before calling this function. * * @return The line of text content. */ public String Continue() throws StoryException, Exception { // TODO: Should we leave this to the client, since it could be // slow to iterate through all the content an extra time? if (!hasValidatedExternals) validateExternalBindings(); return continueInternal(); } String continueInternal() throws StoryException, Exception { if (!canContinue()) { throw new StoryException("Can't continue - should check canContinue before calling Continue"); } state.resetOutput(); state.setDidSafeExit(false); state.getVariablesState().setbatchObservingVariableChanges(true); // _previousContainer = null; try { StoryState stateAtLastNewline = null; // The basic algorithm here is: // do { Step() } while( canContinue && !outputStreamEndsInNewline ); // But the complexity comes from: // - Stepping beyond the newline in case it'll be absorbed by glue // later // - Ensuring that non-text content beyond newlines are generated - // i.e. choices, // which are actually built out of text content. // So we have to take a snapshot of the state, continue // prospectively, // and rewind if necessary. // This code is slightly fragile :-/ do { // Run main step function (walks through content) step(); // Run out of content and we have a default invisible choice // that we can follow? if (!canContinue()) { tryFollowDefaultInvisibleChoice(); } // Don't save/rewind during String evaluation, which is e.g. // used for choices if (!getState().inStringEvaluation()) { // We previously found a newline, but were we just double // checking that // it wouldn't immediately be removed by glue? if (stateAtLastNewline != null) { // Cover cases that non-text generated content was // evaluated last step String currText = getCurrentText(); int prevTextLength = stateAtLastNewline.getCurrentText().length(); // Take tags into account too, so that a tag following a // content line: // Content // # tag // ... doesn't cause the tag to be wrongly associated // with the content above. int prevTagCount = stateAtLastNewline.getCurrentTags().size(); // Output has been extended? if (!currText.equals(stateAtLastNewline.getCurrentText()) || prevTagCount != getCurrentTags().size()) { // Original newline still exists? if (currText.length() >= prevTextLength && currText.charAt(prevTextLength - 1) == '\n') { restoreStateSnapshot(stateAtLastNewline); break; } // Newline that previously existed is no longer // valid - e.g. // glue was encounted that caused it to be removed. else { stateAtLastNewline = null; } } } // Current content ends in a newline - approaching end of // our evaluation if (getState().outputStreamEndsInNewline()) { // If we can continue evaluation for a bit: // Create a snapshot in case we need to rewind. // We're going to continue stepping in case we see glue // or some // non-text content such as choices. if (canContinue()) { // Don't bother to record the state beyond the // current newline. // Hello world\n // record state at the end of here // ~ complexCalculation() // don't actually need this unless it generates text if (stateAtLastNewline == null) stateAtLastNewline = stateSnapshot(); } // Can't continue, so we're about to exit - make sure we // don't have an old state hanging around. else { stateAtLastNewline = null; } } } } while (canContinue()); // Need to rewind, due to evaluating further than we should? if (stateAtLastNewline != null) { restoreStateSnapshot(stateAtLastNewline); } // Finished a section of content / reached a choice point? if (!canContinue()) { if (getState().getCallStack().canPopThread()) { error("Thread available to pop, threads should always be flat by the end of evaluation?"); } if (getState().getGeneratedChoices().size() == 0 && !getState().isDidSafeExit() && temporaryEvaluationContainer == null) { if (getState().getCallStack().canPop(PushPopType.Tunnel)) { error("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"); } else if (getState().getCallStack().canPop(PushPopType.Function)) { error("unexpectedly reached end of content. Do you need a '~ return'?"); } else if (!getState().getCallStack().canPop()) { error("ran out of content. Do you need a '-> DONE' or '-> END'?"); } else { error("unexpectedly reached end of content for unknown reason. Please debug compiler!"); } } } } catch (StoryException e) { addError(e.getMessage(), e.useEndLineNumber); } finally { getState().setDidSafeExit(false); state.getVariablesState().setbatchObservingVariableChanges(false); } return getCurrentText(); } /** * Continue the story until the next choice point or until it runs out of * content. This is as opposed to the Continue() method which only evaluates * one line of output at a time. * * @return The resulting text evaluated by the ink engine, concatenated * together. */ public String continueMaximally() throws StoryException, Exception { StringBuilder sb = new StringBuilder(); while (canContinue()) { sb.append(Continue()); } return sb.toString(); } DebugMetadata currentDebugMetadata() { DebugMetadata dm; // Try to get from the current path first RTObject currentContent = state.getCurrentContentObject(); if (currentContent != null) { dm = currentContent.getDebugMetadata(); if (dm != null) { return dm; } } // Move up callstack if possible for (int i = state.getCallStack().getElements().size() - 1; i >= 0; --i) { RTObject currentObj = state.getCallStack().getElements().get(i).currentRTObject; if (currentObj != null && currentObj.getDebugMetadata() != null) { return currentObj.getDebugMetadata(); } } // Current/previous path may not be valid if we've just had an error, // or if we've simply run out of content. // As a last resort, try to grab something from the output stream for (int i = state.getOutputStream().size() - 1; i >= 0; --i) { RTObject outputObj = state.getOutputStream().get(i); dm = outputObj.getDebugMetadata(); if (dm != null) { return dm; } } return null; } int currentLineNumber() throws Exception { DebugMetadata dm = currentDebugMetadata(); if (dm != null) { return dm.startLineNumber; } return 0; } void error(String message) throws Exception { error(message, false); } // Throw an exception that gets caught and causes AddError to be called, // then exits the flow. void error(String message, boolean useEndLineNumber) throws Exception { StoryException e = new StoryException(message); e.useEndLineNumber = useEndLineNumber; throw e; } // Evaluate a "hot compiled" piece of ink content, as used by the REPL-like // CommandLinePlayer. RTObject evaluateExpression(Container exprContainer) throws StoryException, Exception { int startCallStackHeight = state.getCallStack().getElements().size(); state.getCallStack().push(PushPopType.Tunnel); temporaryEvaluationContainer = exprContainer; state.goToStart(); int evalStackHeight = state.getEvaluationStack().size(); Continue(); temporaryEvaluationContainer = null; // Should have fallen off the end of the Container, which should // have auto-popped, but just in case we didn't for some reason, // manually pop to restore the state (including currentPath). if (state.getCallStack().getElements().size() > startCallStackHeight) { state.getCallStack().pop(); } int endStackHeight = state.getEvaluationStack().size(); if (endStackHeight > evalStackHeight) { return state.popEvaluationStack(); } else { return null; } } /** * The list of Choice Objects available at the current point in the Story. * This list will be populated as the Story is stepped through with the * Continue() method. Once canContinue becomes false, this list will be * populated, and is usually (but not always) on the final Continue() step. */ public List<Choice> getCurrentChoices() { // Don't include invisible choices for external usage. List<Choice> choices = new ArrayList<Choice>(); for (Choice c : state.getCurrentChoices()) { if (!c.getchoicePoint().isInvisibleDefault()) { c.setIndex(choices.size()); choices.add(c); } } return choices; } /** * Gets a list of tags as defined with '#' in source that were seen during * the latest Continue() call. */ public List<String> getCurrentTags() { return state.getCurrentTags(); } /** * Any errors generated during evaluation of the Story. */ public List<String> getCurrentErrors() { return state.getCurrentErrors(); } /** * The latest line of text to be generated from a Continue() call. */ public String getCurrentText() { return state.getCurrentText(); } /** * The entire current state of the story including (but not limited to): * * * Global variables * Temporary variables * Read/visit and turn counts * * The callstack and evaluation stacks * The current threads * */ public StoryState getState() { return state; } /** * The VariablesState Object contains all the global variables in the story. * However, note that there's more to the state of a Story than just the * global variables. This is a convenience accessor to the full state * Object. */ public VariablesState getVariablesState() { return state.getVariablesState(); } public ListDefinitionsOrigin getListDefinitions() { return listsDefinitions; } /** * Whether the currentErrors list contains any errors. */ public boolean hasError() { return state.hasError(); } boolean incrementContentPointer() { boolean successfulIncrement = true; Element currEl = state.getCallStack().getCurrentElement(); currEl.currentContentIndex++; // Each time we step off the end, we fall out to the next container, all // the // while we're in indexed rather than named content while (currEl.currentContentIndex >= currEl.currentContainer.getContent().size()) { successfulIncrement = false; Container nextAncestor = currEl.currentContainer.getParent() instanceof Container ? (Container) currEl.currentContainer.getParent() : null; if (nextAncestor == null) { break; } int indexInAncestor = nextAncestor.getContent().indexOf(currEl.currentContainer); if (indexInAncestor == -1) { break; } currEl.currentContainer = nextAncestor; currEl.currentContentIndex = indexInAncestor + 1; successfulIncrement = true; } if (!successfulIncrement) currEl.currentContainer = null; return successfulIncrement; } void incrementVisitCountForContainer(Container container) { String containerPathStr = container.getPath().toString(); Integer count = state.getVisitCounts().get(containerPathStr); if (count == null) count = 0; count++; state.getVisitCounts().put(containerPathStr, count); } // Does the expression result represented by this Object evaluate to true? // e.g. is it a Number that's not equal to 1? boolean isTruthy(RTObject obj) throws Exception { boolean truthy = false; if (obj instanceof Value) { Value<?> val = (Value<?>) obj; if (val instanceof DivertTargetValue) { DivertTargetValue divTarget = (DivertTargetValue) val; error("Shouldn't use a divert target (to " + divTarget.getTargetPath() + ") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"); return false; } return val.isTruthy(); } return truthy; } /** * When the named global variable changes it's value, the observer will be * called to notify it of the change. Note that if the value changes * multiple times within the ink, the observer will only be called once, at * the end of the ink's evaluation. If, during the evaluation, it changes * and then changes back again to its original value, it will still be * called. Note that the observer will also be fired if the value of the * variable is changed externally to the ink, by directly setting a value in * story.variablesState. * * @param variableName * The name of the global variable to observe. * @param observer * A delegate function to call when the variable changes. */ public void observeVariable(String variableName, VariableObserver observer) { if (variableObservers == null) variableObservers = new HashMap<String, List<VariableObserver>>(); if (variableObservers.containsKey(variableName)) { variableObservers.get(variableName).add(observer); } else { List<VariableObserver> l = new ArrayList<VariableObserver>(); l.add(observer); variableObservers.put(variableName, l); } } /** * Convenience function to allow multiple variables to be observed with the * same observer delegate function. See the singular ObserveVariable for * details. The observer will get one call for every variable that has * changed. * * @param variableNames * The set of variables to observe. * @param observer * The delegate function to call when any of the named variables * change. */ public void observeVariables(List<String> variableNames, VariableObserver observer) { for (String varName : variableNames) { observeVariable(varName, observer); } } /** * Removes the variable observer, to stop getting variable change * notifications. If you pass a specific variable name, it will stop * observing that particular one. If you pass null (or leave it blank, since * it's optional), then the observer will be removed from all variables that * it's subscribed to. * * @param observer * The observer to stop observing. * @param specificVariableName * (Optional) Specific variable name to stop observing. */ public void removeVariableObserver(VariableObserver observer, String specificVariableName) { if (variableObservers == null) return; // Remove observer for this specific variable if (specificVariableName != null) { if (variableObservers.containsKey(specificVariableName)) { variableObservers.get(specificVariableName).remove(observer); } } else { // Remove observer for all variables for (List<VariableObserver> obs : variableObservers.values()) { obs.remove(observer); } } } public void removeVariableObserver(VariableObserver observer) { removeVariableObserver(observer, null); } @Override public void variableStateDidChangeEvent(String variableName, RTObject newValueObj) throws Exception { if (variableObservers == null) return; List<VariableObserver> observers = variableObservers.get(variableName); if (observers != null) { if (!(newValueObj instanceof Value)) { throw new Exception("Tried to get the value of a variable that isn't a standard type"); } Value<?> val = (Value<?>) newValueObj; for (VariableObserver o : observers) { o.call(variableName, val.getValueObject()); } } } Container mainContentContainer() { if (temporaryEvaluationContainer != null) { return temporaryEvaluationContainer; } else { return mainContentContainer; } } String BuildStringOfContainer(Container container) { StringBuilder sb = new StringBuilder(); container.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject()); return sb.toString(); } private void nextContent() throws Exception { // Setting previousContentObject is critical for // VisitChangedContainersDueToDivert state.setPreviousContentObject(state.getCurrentContentObject()); // Divert step? if (state.getDivertedTargetObject() != null) { state.setCurrentContentObject(state.getDivertedTargetObject()); state.setDivertedTargetObject(null); // Internally uses state.previousContentObject and // state.currentContentObject visitChangedContainersDueToDivert(); // Diverted location has valid content? if (state.getCurrentContentObject() != null) { return; } // Otherwise, if diverted location doesn't have valid content, // drop down and attempt to increment. // This can happen if the diverted path is intentionally jumping // to the end of a container - e.g. a Conditional that's re-joining } boolean successfulPointerIncrement = incrementContentPointer(); // Ran out of content? Try to auto-exit from a function, // or finish evaluating the content of a thread if (!successfulPointerIncrement) { boolean didPop = false; if (state.getCallStack().canPop(PushPopType.Function)) { // Pop from the call stack state.getCallStack().pop(PushPopType.Function); // This pop was due to dropping off the end of a function that // didn't return anything, // so in this case, we make sure that the evaluator has // something to chomp on if it needs it if (state.getInExpressionEvaluation()) { state.pushEvaluationStack(new Void()); } didPop = true; } else if (state.getCallStack().canPopThread()) { state.getCallStack().popThread(); didPop = true; } else { state.tryExitExternalFunctionEvaluation(); } // Step past the point where we last called out if (didPop && state.getCurrentContentObject() != null) { nextContent(); } } } // Note that this is O(n), since it re-evaluates the shuffle indices // from a consistent seed each time. // TODO: Is this the best algorithm it can be? int nextSequenceShuffleIndex() throws Exception { RTObject popEvaluationStack = state.popEvaluationStack(); IntValue numElementsIntVal = popEvaluationStack instanceof IntValue ? (IntValue) popEvaluationStack : null; if (numElementsIntVal == null) { error("expected number of elements in sequence for shuffle index"); return 0; } Container seqContainer = state.currentContainer(); int numElements = numElementsIntVal.value; IntValue seqCountVal = (IntValue) state.popEvaluationStack(); int seqCount = seqCountVal.value; int loopIndex = seqCount / numElements; int iterationIndex = seqCount % numElements; // Generate the same shuffle based on: // - The hash of this container, to make sure it's consistent // each time the runtime returns to the sequence // - How many times the runtime has looped around this full shuffle String seqPathStr = seqContainer.getPath().toString(); int sequenceHash = 0; for (char c : seqPathStr.toCharArray()) { sequenceHash += c; } int randomSeed = sequenceHash + loopIndex + state.getStorySeed(); Random random = new Random(randomSeed); ArrayList<Integer> unpickedIndices = new ArrayList<Integer>(); for (int i = 0; i < numElements; ++i) { unpickedIndices.add(i); } for (int i = 0; i <= iterationIndex; ++i) { int chosen = random.nextInt(Integer.MAX_VALUE) % unpickedIndices.size(); int chosenIndex = unpickedIndices.get(chosen); unpickedIndices.remove(chosen); if (i == iterationIndex) { return chosenIndex; } } throw new Exception("Should never reach here"); } /** * Checks whether contentObj is a control or flow Object rather than a piece * of content, and performs the required command if necessary. * * @return true if Object was logic or flow control, false if it's normal * content. * @param contentObj * Content Object. */ boolean performLogicAndFlowControl(RTObject contentObj) throws Exception { if (contentObj == null) { return false; } // Divert if (contentObj instanceof Divert) { Divert currentDivert = (Divert) contentObj; if (currentDivert.isConditional()) { RTObject conditionValue = state.popEvaluationStack(); // False conditional? Cancel divert if (!isTruthy(conditionValue)) return true; } if (currentDivert.hasVariableTarget()) { String varName = currentDivert.getVariableDivertName(); RTObject varContents = state.getVariablesState().getVariableWithName(varName); if (!(varContents instanceof DivertTargetValue)) { IntValue intContent = varContents instanceof IntValue ? (IntValue) varContents : null; String errorMessage = "Tried to divert to a target from a variable, but the variable (" + varName + ") didn't contain a divert target, it "; if (intContent != null && intContent.value == 0) { errorMessage += "was empty/null (the value 0)."; } else { errorMessage += "contained '" + varContents + "'."; } error(errorMessage); } DivertTargetValue target = (DivertTargetValue) varContents; state.setDivertedTargetObject(contentAtPath(target.getTargetPath())); } else if (currentDivert.isExternal()) { callExternalFunction(currentDivert.getTargetPathString(), currentDivert.getExternalArgs()); return true; } else { state.setDivertedTargetObject(currentDivert.getTargetContent()); } if (currentDivert.getPushesToStack()) { state.getCallStack().push(currentDivert.getStackPushType()); } if (state.getDivertedTargetObject() == null && !currentDivert.isExternal()) { // Human readable name available - runtime divert is part of a // hard-written divert that to missing content if (currentDivert != null && currentDivert.getDebugMetadata().sourceName != null) { error("Divert target doesn't exist: " + currentDivert.getDebugMetadata().sourceName); } else { error("Divert resolution failed: " + currentDivert); } } return true; } // Start/end an expression evaluation? Or print out the result? else if (contentObj instanceof ControlCommand) { ControlCommand evalCommand = (ControlCommand) contentObj; int choiceCount; switch (evalCommand.getCommandType()) { case EvalStart: Assert(state.getInExpressionEvaluation() == false, "Already in expression evaluation?"); state.setInExpressionEvaluation(true); break; case EvalEnd: Assert(state.getInExpressionEvaluation() == true, "Not in expression evaluation mode"); state.setInExpressionEvaluation(false); break; case EvalOutput: // If the expression turned out to be empty, there may not be // anything on the stack if (state.getEvaluationStack().size() > 0) { RTObject output = state.popEvaluationStack(); // Functions may evaluate to Void, in which case we skip // output if (!(output instanceof Void)) { // TODO: Should we really always blanket convert to // string? // It would be okay to have numbers in the output stream // the // only problem is when exporting text for viewing, it // skips over numbers etc. StringValue text = new StringValue(output.toString()); state.pushToOutputStream(text); } } break; case NoOp: break; case Duplicate: state.pushEvaluationStack(state.peekEvaluationStack()); break; case PopEvaluatedValue: state.popEvaluationStack(); break; case PopFunction: case PopTunnel: PushPopType popType = evalCommand.getCommandType() == ControlCommand.CommandType.PopFunction ? PushPopType.Function : PushPopType.Tunnel; // Tunnel onwards is allowed to specify an optional override // divert to go to immediately after returning: ->-> target DivertTargetValue overrideTunnelReturnTarget = null; if (popType == PushPopType.Tunnel) { RTObject popped = state.popEvaluationStack(); if (popped instanceof DivertTargetValue) { overrideTunnelReturnTarget = (DivertTargetValue) popped; } if (overrideTunnelReturnTarget == null) { Assert(popped instanceof Void, "Expected void if ->-> doesn't override target"); } } if (state.tryExitExternalFunctionEvaluation()) { break; } else if (state.getCallStack().getCurrentElement().type != popType || !state.getCallStack().canPop()) { HashMap<PushPopType, String> names = new HashMap<PushPopType, String>(); names.put(PushPopType.Function, "function return statement (~ return)"); names.put(PushPopType.Tunnel, "tunnel onwards statement (->->)"); String expected = names.get(state.getCallStack().getCurrentElement().type); if (!state.getCallStack().canPop()) { expected = "end of flow (-> END or choice)"; } String errorMsg = String.format("Found %s, when expected %s", names.get(popType), expected); error(errorMsg); } else { state.getCallStack().pop(); // Does tunnel onwards override by diverting to a new ->-> // target? if (overrideTunnelReturnTarget != null) state.setDivertedTargetObject(contentAtPath(overrideTunnelReturnTarget.getTargetPath())); } break; case BeginString: state.pushToOutputStream(evalCommand); Assert(state.getInExpressionEvaluation() == true, "Expected to be in an expression when evaluating a string"); state.setInExpressionEvaluation(false); break; case EndString: // Since we're iterating backward through the content, // build a stack so that when we build the string, // it's in the right order Stack<RTObject> contentStackForString = new Stack<RTObject>(); int outputCountConsumed = 0; for (int i = state.getOutputStream().size() - 1; i >= 0; --i) { RTObject obj = state.getOutputStream().get(i); outputCountConsumed++; ControlCommand command = obj instanceof ControlCommand ? (ControlCommand) obj : null; if (command != null && command.getCommandType() == ControlCommand.CommandType.BeginString) { break; } if (obj instanceof StringValue) contentStackForString.push(obj); } // Consume the content that was produced for this string state.getOutputStream() .subList(state.getOutputStream().size() - outputCountConsumed, state.getOutputStream().size()) .clear(); // Build String out of the content we collected StringBuilder sb = new StringBuilder(); while (contentStackForString.size() > 0) { RTObject c = contentStackForString.pop(); sb.append(c.toString()); } // Return to expression evaluation (from content mode) state.setInExpressionEvaluation(true); state.pushEvaluationStack(new StringValue(sb.toString())); break; case ChoiceCount: choiceCount = state.getGeneratedChoices().size(); state.pushEvaluationStack(new IntValue(choiceCount)); break; case TurnsSince: case ReadCount: RTObject target = state.popEvaluationStack(); if (!(target instanceof DivertTargetValue)) { String extraNote = ""; if (target instanceof IntValue) extraNote = ". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"; error("TURNS_SINCE expected a divert target (knot, stitch, label name), but saw " + target + extraNote); break; } DivertTargetValue divertTarget = target instanceof DivertTargetValue ? (DivertTargetValue) target : null; Container container = contentAtPath(divertTarget.getTargetPath()) instanceof Container ? (Container) contentAtPath(divertTarget.getTargetPath()) : null; int eitherCount; if (evalCommand.getCommandType() == ControlCommand.CommandType.TurnsSince) eitherCount = turnsSinceForContainer(container); else eitherCount = visitCountForContainer(container); state.pushEvaluationStack(new IntValue(eitherCount)); break; case Random: { IntValue maxInt = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) maxInt = (IntValue) o; IntValue minInt = null; o = state.popEvaluationStack(); if (o instanceof IntValue) minInt = (IntValue) o; if (minInt == null) error("Invalid value for minimum parameter of RANDOM(min, max)"); if (maxInt == null) error("Invalid value for maximum parameter of RANDOM(min, max)"); // +1 because it's inclusive of min and max, for e.g. // RANDOM(1,6) for a dice roll. int randomRange = maxInt.value - minInt.value + 1; if (randomRange <= 0) error("RANDOM was called with minimum as " + minInt.value + " and maximum as " + maxInt.value + ". The maximum must be larger"); int resultSeed = state.getStorySeed() + state.getPreviousRandom(); Random random = new Random(resultSeed); int nextRandom = random.nextInt(Integer.MAX_VALUE); int chosenValue = (nextRandom % randomRange) + minInt.value; state.pushEvaluationStack(new IntValue(chosenValue)); // Next random number (rather than keeping the Random object // around) state.setPreviousRandom(state.getPreviousRandom() + 1); break; } case SeedRandom: { IntValue seed = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) seed = (IntValue) o; if (seed == null) error("Invalid value passed to SEED_RANDOM"); // Story seed affects both RANDOM and shuffle behaviour state.setStorySeed(seed.value); state.setPreviousRandom(0); // SEED_RANDOM returns nothing. state.pushEvaluationStack(new Void()); break; } case VisitIndex: int count = visitCountForContainer(state.currentContainer()) - 1; // index // not // count state.pushEvaluationStack(new IntValue(count)); break; case SequenceShuffleIndex: int shuffleIndex = nextSequenceShuffleIndex(); state.pushEvaluationStack(new IntValue(shuffleIndex)); break; case StartThread: // Handled in main step function break; case Done: // We may exist in the context of the initial // act of creating the thread, or in the context of // evaluating the content. if (state.getCallStack().canPopThread()) { state.getCallStack().popThread(); } // In normal flow - allow safe exit without warning else { state.setDidSafeExit(true); // Stop flow in current thread state.setCurrentContentObject(null); } break; // Force flow to end completely case End: state.forceEnd(); break; case ListFromInt: { IntValue intVal = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) intVal = (IntValue) o; StringValue listNameVal = null; o = state.popEvaluationStack(); if (o instanceof StringValue) listNameVal = (StringValue) o; if(intVal == null) { throw new StoryException ("Passed non-integer when creating a list element from a numerical value."); } ListValue generatedListValue = null; ListDefinition foundListDef = listsDefinitions.getDefinition(listNameVal.value); if (foundListDef != null) { InkListItem foundItem; foundItem = foundListDef.getItemWithValue(intVal.value); if (foundItem != null) { generatedListValue = new ListValue(foundItem, intVal.value); } } else { throw new StoryException("Failed to find List called " + listNameVal.value); } if (generatedListValue == null) generatedListValue = new ListValue(); state.pushEvaluationStack(generatedListValue); break; } case ListRange: { RTObject max = state.popEvaluationStack(); RTObject min = state.popEvaluationStack(); RTObject targetRT = state.popEvaluationStack(); ListValue targetList = null; if (targetRT instanceof ListValue) targetList = (ListValue) targetRT; if (targetList == null || min == null || max == null) throw new StoryException("Expected List, minimum and maximum for LIST_RANGE"); int minVal = -1; if (min instanceof ListValue) { minVal = (int) ((ListValue) min).getValue().getMaxItem().getValue(); } else if (min instanceof IntValue) { minVal = (int) ((IntValue) min).getValue(); } int maxVal = -1; if (max instanceof ListValue) { maxVal = (int) ((ListValue) min).getValue().getMaxItem().getValue(); } else if (min instanceof IntValue) { maxVal = (int) ((IntValue) min).getValue(); } if (minVal == -1) throw new StoryException("Invalid min range bound passed to LIST_RANGE(): " + min); if (maxVal == -1) throw new StoryException("Invalid max range bound passed to LIST_RANGE(): " + max); // Extract the range of items from the origin set ListValue result = new ListValue(); List<ListDefinition> origins = targetList.value.origins; if (origins != null) { for (ListDefinition origin : origins) { ListValue rangeFromOrigin = origin.listRange(minVal, maxVal); for (Entry<InkListItem, Integer> kv : rangeFromOrigin.getValue().entrySet()) { result.value.put(kv.getKey(), kv.getValue()); } } } state.pushEvaluationStack(result); break; } default: error("unhandled ControlCommand: " + evalCommand); break; } return true; } // Variable assignment else if (contentObj instanceof VariableAssignment) { VariableAssignment varAss = (VariableAssignment) contentObj; RTObject assignedVal = state.popEvaluationStack(); // When in temporary evaluation, don't create new variables purely // within // the temporary context, but attempt to create them globally // var prioritiseHigherInCallStack = _temporaryEvaluationContainer // != null; state.getVariablesState().assign(varAss, assignedVal); return true; } // Variable reference else if (contentObj instanceof VariableReference) { VariableReference varRef = (VariableReference) contentObj; RTObject foundValue = null; // Explicit read count value if (varRef.getPathForCount() != null) { Container container = varRef.getContainerForCount(); int count = visitCountForContainer(container); foundValue = new IntValue(count); } // Normal variable reference else { foundValue = state.getVariablesState().getVariableWithName(varRef.getName()); if (foundValue == null) { error("Uninitialised variable: " + varRef.getName()); foundValue = new IntValue(0); } } state.pushEvaluationStack(foundValue); return true; } // Native function call else if (contentObj instanceof NativeFunctionCall) { NativeFunctionCall func = (NativeFunctionCall) contentObj; List<RTObject> funcParams = state.popEvaluationStack(func.getNumberOfParameters()); RTObject result = func.call(funcParams); state.pushEvaluationStack(result); return true; } // No control content, must be ordinary content return false; } Choice processChoice(ChoicePoint choicePoint) throws Exception { boolean showChoice = true; // Don't create choice if choice point doesn't pass conditional if (choicePoint.hasCondition()) { RTObject conditionValue = state.popEvaluationStack(); if (!isTruthy(conditionValue)) { showChoice = false; } } String startText = ""; String choiceOnlyText = ""; if (choicePoint.hasChoiceOnlyContent()) { StringValue choiceOnlyStrVal = (StringValue) state.popEvaluationStack(); choiceOnlyText = choiceOnlyStrVal.value; } if (choicePoint.hasStartContent()) { StringValue startStrVal = (StringValue) state.popEvaluationStack(); startText = startStrVal.value; } // Don't create choice if player has already read this content if (choicePoint.isOnceOnly()) { int visitCount = visitCountForContainer(choicePoint.getChoiceTarget()); if (visitCount > 0) { showChoice = false; } } Choice choice = new Choice(choicePoint); choice.setThreadAtGeneration(state.getCallStack().getcurrentThread().copy()); // We go through the full process of creating the choice above so // that we consume the content for it, since otherwise it'll // be shown on the output stream. if (!showChoice) { return null; } // Set final text for the choice choice.setText(startText + choiceOnlyText); return choice; } void recordTurnIndexVisitToContainer(Container container) { String containerPathStr = container.getPath().toString(); state.getTurnIndices().put(containerPathStr, state.getCurrentTurnIndex()); } /** * Unwinds the callstack. Useful to reset the Story's evaluation without * actually changing any meaningful state, for example if you want to exit a * section of story prematurely and tell it to go elsewhere with a call to * ChoosePathString(...). Doing so without calling ResetCallstack() could * cause unexpected issues if, for example, the Story was in a tunnel * already. */ public void resetCallstack() throws Exception { state.forceEnd(); } /** * Reset the runtime error list within the state. */ public void resetErrors() { state.resetErrors(); } void resetGlobals() throws Exception { if (mainContentContainer.getNamedContent().containsKey("global decl")) { Path originalPath = getState().getCurrentPath(); choosePathString("global decl"); // Continue, but without validating external bindings, // since we may be doing this reset at initialisation time. continueInternal(); getState().setCurrentPath(originalPath); } } /** * Reset the Story back to its initial state as it was when it was first * constructed. */ public void resetState() throws Exception { state = new StoryState(this); state.getVariablesState().setVariableChangedEvent(this); resetGlobals(); } void restoreStateSnapshot(StoryState state) { this.state = state; } StoryState stateSnapshot() throws Exception { return state.copy(); } void step() throws Exception { boolean shouldAddToStream = true; // Get current content RTObject currentContentObj = state.getCurrentContentObject(); if (currentContentObj == null) { return; } // Step directly to the first element of content in a container (if // necessary) Container currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null; while (currentContainer != null) { // Mark container as being entered visitContainer(currentContainer, true); // No content? the most we can do is step past it if (currentContainer.getContent().size() == 0) break; currentContentObj = currentContainer.getContent().get(0); state.getCallStack().getCurrentElement().currentContentIndex = 0; state.getCallStack().getCurrentElement().currentContainer = currentContainer; currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null; } currentContainer = state.getCallStack().getCurrentElement().currentContainer; // Is the current content Object: // - Normal content // - Or a logic/flow statement - if so, do it // Stop flow if we hit a stack pop when we're unable to pop (e.g. // return/done statement in knot // that was diverted to rather than called as a function) boolean isLogicOrFlowControl = performLogicAndFlowControl(currentContentObj); // Has flow been forced to end by flow control above? if (state.getCurrentContentObject() == null) { return; } if (isLogicOrFlowControl) { shouldAddToStream = false; } // Choice with condition? ChoicePoint choicePoint = currentContentObj instanceof ChoicePoint ? (ChoicePoint) currentContentObj : null; if (choicePoint != null) { Choice choice = processChoice(choicePoint); if (choice != null) { state.getGeneratedChoices().add(choice); } currentContentObj = null; shouldAddToStream = false; } // If the container has no content, then it will be // the "content" itself, but we skip over it. if (currentContentObj instanceof Container) { shouldAddToStream = false; } // Content to add to evaluation stack or the output stream if (shouldAddToStream) { // If we're pushing a variable pointer onto the evaluation stack, // ensure that it's specific // to our current (possibly temporary) context index. And make a // copy of the pointer // so that we're not editing the original runtime Object. VariablePointerValue varPointer = currentContentObj instanceof VariablePointerValue ? (VariablePointerValue) currentContentObj : null; if (varPointer != null && varPointer.getContextIndex() == -1) { // Create new Object so we're not overwriting the story's own // data int contextIdx = state.getCallStack().contextForVariableNamed(varPointer.getVariableName()); currentContentObj = new VariablePointerValue(varPointer.getVariableName(), contextIdx); } // Expression evaluation content if (state.getInExpressionEvaluation()) { state.pushEvaluationStack(currentContentObj); } // Output stream content (i.e. not expression evaluation) else { state.pushToOutputStream(currentContentObj); } } // Increment the content pointer, following diverts if necessary nextContent(); // Starting a thread should be done after the increment to the content // pointer, // so that when returning from the thread, it returns to the content // after this instruction. ControlCommand controlCmd = currentContentObj instanceof ControlCommand ? (ControlCommand) currentContentObj : null; if (controlCmd != null && controlCmd.getCommandType() == ControlCommand.CommandType.StartThread) { state.getCallStack().pushThread(); } } /** * The Story itself in JSON representation. */ public String toJsonString() throws Exception { List<?> rootContainerJsonList = (List<?>) Json.runtimeObjectToJToken(mainContentContainer); HashMap<String, Object> rootObject = new HashMap<String, Object>(); rootObject.put("inkVersion", inkVersionCurrent); rootObject.put("root", rootContainerJsonList); return SimpleJson.HashMapToText(rootObject); } boolean tryFollowDefaultInvisibleChoice() throws Exception { List<Choice> allChoices = state.getCurrentChoices(); // Is a default invisible choice the ONLY choice? // var invisibleChoices = allChoices.Where (c => // c.choicePoint.isInvisibleDefault).ToList(); ArrayList<Choice> invisibleChoices = new ArrayList<Choice>(); for (Choice c : allChoices) { if (c.getchoicePoint().isInvisibleDefault()) { invisibleChoices.add(c); } } if (invisibleChoices.size() == 0 || allChoices.size() > invisibleChoices.size()) return false; Choice choice = invisibleChoices.get(0); choosePath(choice.getchoicePoint().getChoiceTarget().getPath()); return true; } int turnsSinceForContainer(Container container) throws Exception { if (!container.getTurnIndexShouldBeCounted()) { error("TURNS_SINCE() for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown. The story may need to be compiled with countAllVisits flag (-c)."); } String containerPathStr = container.getPath().toString(); Integer index = state.getTurnIndices().get(containerPathStr); if (index != null) { return state.getCurrentTurnIndex() - index; } else { return -1; } } /** * Remove a binding for a named EXTERNAL ink function. */ public void unbindExternalFunction(String funcName) throws Exception { Assert(externals.containsKey(funcName), "Function '" + funcName + "' has not been bound."); externals.remove(funcName); } /** * Check that all EXTERNAL ink functions have a valid bound C# function. * Note that this is automatically called on the first call to Continue(). */ public void validateExternalBindings() throws Exception { HashSet<String> missingExternals = new HashSet<String>(); validateExternalBindings(mainContentContainer, missingExternals); hasValidatedExternals = true; // No problem! Validation complete if (missingExternals.size() == 0) { hasValidatedExternals = true; } else { // Error for all missing externals StringBuilder join = new StringBuilder(); boolean first = true; for (String item : missingExternals) { if (first) first = false; else join.append(", "); join.append(item); } String message = String.format("ERROR: Missing function binding for external%s: '%s' %s", missingExternals.size() > 1 ? "s" : "", join.toString(), allowExternalFunctionFallbacks ? ", and no fallback ink function found." : " (ink fallbacks disabled)"); error(message); } } void validateExternalBindings(Container c, HashSet<String> missingExternals) throws Exception { for (RTObject innerContent : c.getContent()) { Container container = innerContent instanceof Container ? (Container) innerContent : null; if (container == null || !container.hasValidName()) validateExternalBindings(innerContent, missingExternals); } for (INamedContent innerKeyValue : c.getNamedContent().values()) { validateExternalBindings(innerKeyValue instanceof RTObject ? (RTObject) innerKeyValue : (RTObject) null, missingExternals); } } void validateExternalBindings(RTObject o, HashSet<String> missingExternals) throws Exception { Container container = o instanceof Container ? (Container) o : null; if (container != null) { validateExternalBindings(container, missingExternals); return; } Divert divert = o instanceof Divert ? (Divert) o : null; if (divert != null && divert.isExternal()) { String name = divert.getTargetPathString(); if (!externals.containsKey(name)) { if (allowExternalFunctionFallbacks) { boolean fallbackFound = mainContentContainer.getNamedContent().containsKey(name); if (!fallbackFound) { missingExternals.add(name); } } else { missingExternals.add(name); } } } } void visitChangedContainersDueToDivert() { RTObject previousContentObject = state.getPreviousContentObject(); RTObject newContentObject = state.getCurrentContentObject(); if (newContentObject == null) return; // First, find the previously open set of containers if (prevContainerSet == null) prevContainerSet = new HashSet<Container>(); prevContainerSet.clear(); if (previousContentObject != null) { Container prevAncestor = null; if (previousContentObject instanceof Container) { prevAncestor = (Container) previousContentObject; } else if (previousContentObject.getParent() instanceof Container) { prevAncestor = (Container) previousContentObject.getParent(); } while (prevAncestor != null) { prevContainerSet.add(prevAncestor); prevAncestor = prevAncestor.getParent() instanceof Container ? (Container) prevAncestor.getParent() : null; } } // If the new Object is a container itself, it will be visited // automatically at the next actual // content step. However, we need to walk up the new ancestry to see if // there are more new containers RTObject currentChildOfContainer = newContentObject; Container currentContainerAncestor = currentChildOfContainer.getParent() instanceof Container ? (Container) currentChildOfContainer.getParent() : null; while (currentContainerAncestor != null && !prevContainerSet.contains(currentContainerAncestor)) { // Check whether this ancestor container is being entered at the // start, // by checking whether the child Object is the first. boolean enteringAtStart = currentContainerAncestor.getContent().size() > 0 && currentChildOfContainer == currentContainerAncestor.getContent().get(0); // Mark a visit to this container visitContainer(currentContainerAncestor, enteringAtStart); currentChildOfContainer = currentContainerAncestor; currentContainerAncestor = currentContainerAncestor.getParent() instanceof Container ? (Container) currentContainerAncestor.getParent() : null; } } // Mark a container as having been visited void visitContainer(Container container, boolean atStart) { if (!container.getCountingAtStartOnly() || atStart) { if (container.getVisitsShouldBeCounted()) incrementVisitCountForContainer(container); if (container.getTurnIndexShouldBeCounted()) recordTurnIndexVisitToContainer(container); } } int visitCountForContainer(Container container) throws Exception { if (!container.getVisitsShouldBeCounted()) { error("Read count for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown. The story may need to be compiled with countAllVisits flag (-c)."); return 0; } String containerPathStr = container.getPath().toString(); Integer count = state.getVisitCounts().get(containerPathStr); return count == null ? 0 : count; } public boolean allowExternalFunctionFallbacks() { return allowExternalFunctionFallbacks; } public void setAllowExternalFunctionFallbacks(boolean allowExternalFunctionFallbacks) { this.allowExternalFunctionFallbacks = allowExternalFunctionFallbacks; } /** * Evaluates a function defined in ink. * * @param functionName * The name of the function as declared in ink. * @param arguments * The arguments that the ink function takes, if any. Note that * we don't (can't) do any validation on the number of arguments * right now, so make sure you get it right! * @return The return value as returned from the ink function with `~ return * myValue`, or null if nothing is returned. * @throws Exception */ public Object evaluateFunction(String functionName, Object[] arguments) throws Exception { return evaluateFunction(functionName, null, arguments); } public Object evaluateFunction(String functionName) throws Exception { return evaluateFunction(functionName, null, null); } /** * Checks if a function exists. * * @return True if the function exists, else false. * @param functionName * The name of the function as declared in ink. */ public boolean hasFunction(String functionName) { try { return contentAtPath(new Path(functionName)) instanceof Container; } catch (Exception e) { return false; } } /** * Evaluates a function defined in ink, and gathers the possibly multi-line * text as generated by the function. * * @param arguments * The arguments that the ink function takes, if any. Note that * we don't (can't) do any validation on the number of arguments * right now, so make sure you get it right! * @param functionName * The name of the function as declared in ink. * @param textOutput * This text output is any text written as normal content within * the function, as opposed to the return value, as returned with * `~ return`. * @return The return value as returned from the ink function with `~ return * myValue`, or null if nothing is returned. * @throws Exception */ public Object evaluateFunction(String functionName, StringBuffer textOutput, Object[] arguments) throws Exception { // Get the content that we need to run Container funcContainer = null; if (functionName == null) { throw new Exception("Function is null"); } else if (functionName.trim().isEmpty()) { throw new Exception("Function is empty or white space."); } try { RTObject contentAtPath = contentAtPath(new Path(functionName)); if (contentAtPath instanceof Container) funcContainer = (Container) contentAtPath; } catch (StoryException e) { if (e.getMessage().contains("not found")) throw new Exception("Function doesn't exist: '" + functionName + "'"); else throw e; } // State will temporarily replace the callstack in order to evaluate state.startExternalFunctionEvaluation(funcContainer, arguments); // Evaluate the function, and collect the string output while (canContinue()) { String text = Continue(); if (textOutput != null) textOutput.append(text); } // Finish evaluation, and see whether anything was produced Object result = state.completeExternalFunctionEvaluation(); return result; } }
package com.couchbase.cblite; import android.util.Log; import com.couchbase.cblite.internal.CBLRevisionInternal; import java.util.EnumSet; import java.util.List; import java.util.Map; /** * A CouchbaseLite document (as opposed to any specific revision of it.) */ public class CBLDocument { /** * The document's owning database. */ private CBLDatabase database; /** * The document's ID. */ private String documentId; /** * The current/latest revision. This object is cached. */ private CBLRevision currentRevision; /** * Application-defined model object representing this document */ private Object model; /** * Constructor * * @param database The document's owning database * @param documentId The document's ID */ public CBLDocument(CBLDatabase database, String documentId) { this.database = database; this.documentId = documentId; } /** * Get the document's owning database. */ public CBLDatabase getDatabase() { return database; } /** * Get the document's ID */ public String getId() { return documentId; } /** * Get the document's abbreviated ID */ public String getAbbreviatedId() { // TODO: implement throw new RuntimeException("Not Implemented"); } /** * Is this document deleted? (That is, does its current revision have the '_deleted' property?) * @return boolean to indicate whether deleted or not */ public boolean isDeleted() { return currentRevision.isDeleted(); } /** * Deletes this document by adding a deletion revision. * This will be replicated to other databases. * * @return boolean to indicate whether deleted or not * @throws CBLiteException */ public boolean delete() throws CBLiteException { return currentRevision.deleteDocument() != null; } /** * Purges this document from the database; this is more than deletion, it forgets entirely about it. * The purge will NOT be replicated to other databases. * * @return boolean to indicate whether purged or not * @throws CBLiteException */ public boolean purge() throws CBLiteException { // TODO: implement throw new RuntimeException("Not Implemented"); } /** * The revision with the specified ID. * * @param revisionID the revision ID * @return the CBLRevision object */ public CBLRevision getRevision(String revisionID) { if (revisionID.equals(currentRevision.getId())) { return currentRevision; } EnumSet<CBLDatabase.TDContentOptions> contentOptions = EnumSet.noneOf(CBLDatabase.TDContentOptions.class); CBLRevisionInternal revisionInternal = database.getDocumentWithIDAndRev(getId(), revisionID, contentOptions); CBLRevision revision = null; revision = getRevisionFromRev(revisionInternal); return revision; } /** * Get the current revision * * @return */ public CBLRevision getCurrentRevision() { return currentRevision; } /** * Get the ID of the current revision * * @return */ public String getCurrentRevisionId() { return currentRevision.getId(); } /** * Returns the document's history as an array of CBLRevisions. (See CBLRevision's method.) * * @return document's history * @throws CBLiteException */ public List<CBLRevision> getRevisionHistory() throws CBLiteException { if (currentRevision == null) { Log.w(CBLDatabase.TAG, "getRevisionHistory() called but no currentRevision"); return null; } return currentRevision.getRevisionHistory(); } /** * Returns all the current conflicting revisions of the document. If the document is not * in conflict, only the single current revision will be returned. * * @return all current conflicting revisions of the document * @throws CBLiteException */ public List<String> getConflictingRevisions() throws CBLiteException { return database.getConflictingRevisionIDsOfDocID(documentId); } /** * Returns all the leaf revisions in the document's revision tree, * including deleted revisions (i.e. previously-resolved conflicts.) * * @return all the leaf revisions in the document's revision tree * @throws CBLiteException */ public List<CBLRevision> getLeafRevisions() throws CBLiteException { // TODO: implement throw new RuntimeException("Not Implemented"); } /** * Creates an unsaved new revision whose parent is the currentRevision, * or which will be the first revision if the document doesn't exist yet. * You can modify this revision's properties and attachments, then save it. * No change is made to the database until/unless you save the new revision. * * @return the newly created revision */ public CBLNewRevision newRevision() { return new CBLNewRevision(this, currentRevision); } /** * Shorthand for getProperties().get(key) */ public Object propertyForKey(String key) { return currentRevision.getProperties().get(key); } /** * The contents of the current revision of the document. * This is shorthand for self.currentRevision.properties. * Any keys in the dictionary that begin with "_", such as "_id" and "_rev", contain CouchbaseLite metadata. * * @return contents of the current revision of the document. */ public Map<String,Object> getProperties() { return currentRevision.getProperties(); } /** * The user-defined properties, without the ones reserved by CouchDB. * This is based on -properties, with every key whose name starts with "_" removed. * * @return user-defined properties, without the ones reserved by CouchDB. */ public Map<String,Object> getUserProperties() { return currentRevision.getUserProperties(); } /** * Saves a new revision. The properties dictionary must have a "_rev" property * whose ID matches the current revision's (as it will if it's a modified * copy of this document's .properties property.) * * @param properties the contents to be saved in the new revision * @return a new CBLRevision */ public CBLRevision putProperties(Map<String,Object> properties) throws CBLiteException { String prevID = (String) properties.get("_rev"); return putProperties(properties, prevID); } CBLRevision putProperties(Map<String,Object> properties, String prevID) throws CBLiteException { String newId = (String) properties.get("_id"); if (newId != null && !newId.equalsIgnoreCase(getId())) { Log.w(CBLDatabase.TAG, String.format("Trying to put wrong _id to this: %s properties: %s", this, properties)); } // Process _attachments dict, converting CBLAttachments to dicts: Map<String, Object> attachments = (Map<String, Object>) properties.get("_attachments"); if (attachments != null && attachments.size() > 0) { Map<String, Object> updatedAttachments = CBLAttachment.installAttachmentBodies(attachments, database); properties.put("_attachments", updatedAttachments); } boolean deleted = (properties == null) || ((Boolean)properties.get("_deleted")).booleanValue(); CBLRevisionInternal rev = new CBLRevisionInternal(documentId, null, deleted, database); if (properties != null) { rev.setProperties(properties); } CBLRevisionInternal newRev = database.putRevision(rev, prevID, false); if (newRev == null) { return null; } return new CBLRevision(this, newRev); } /** * Saves a new revision by letting the caller update the existing properties. * This method handles conflicts by retrying (calling the block again). * The CBLRevisionUpdater implementation should modify the properties of the new revision and return YES to save or * NO to cancel. Be careful: the block can be called multiple times if there is a conflict! * * @param updater the callback CBLRevisionUpdater implementation. Will be called on each * attempt to save. Should update the given revision's properties and then * return YES, or just return NO to cancel. * @return The new saved revision, or null on error or cancellation. * @throws CBLiteException */ public CBLRevision update(CBLRevisionUpdater updater) throws CBLiteException { // TODO: implement throw new RuntimeException("Not Implemented"); } CBLRevision getRevisionFromRev(CBLRevisionInternal internalRevision) { if (internalRevision == null) { return null; } else if (internalRevision.getRevId().equals(currentRevision.getId())) { return currentRevision; } else { return new CBLRevision(this, internalRevision); } } public Object getModel() { return model; } public void setModel(Object model) { this.model = model; } public static interface CBLRevisionUpdater { public boolean updateRevision(CBLNewRevision newRevision); } }
package com.groupbyinc.api.model; import com.groupbyinc.api.request.Request; import com.groupbyinc.common.jackson.Mappers; import com.groupbyinc.common.jackson.annotation.JsonIgnore; import com.groupbyinc.common.jackson.annotation.JsonProperty; import com.groupbyinc.common.jackson.core.JsonProcessingException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * <code> * The results object contains a reference to all the objects that come back from the search service. * </code> * * @author will */ public class Results { private long totalRecordCount; protected String id; protected String area; protected String biasingProfile; protected String redirect; protected String errors; protected String query; private String originalQuery; private String correctedQuery; protected Template template; private PageInfo pageInfo = new PageInfo(); protected MatchStrategy matchStrategy; protected List<String> warnings; private List<Navigation> availableNavigation = new ArrayList<Navigation>(); private List<Navigation> selectedNavigation = new ArrayList<Navigation>(); protected List<Record> records = new ArrayList<Record>(); private List<String> didYouMean = new ArrayList<String>(); private List<Metadata> siteParams = new ArrayList<Metadata>(); @JsonProperty DebugInfo debugInfo; private Request originalRequest; private List<String> relatedQueries = new ArrayList<String>(); private List<String> rewrites = new ArrayList<String>(); /** * @return An id that uniquely identifies this Results object. */ public String getId() { return id; } /** * @param id * Set the unique identifier for this Results object. * * @return */ public Results setId(String id) { this.id = id; return this; } /** * @return The area that the query was run against. */ public String getArea() { return area; } /** * @param area * Set the area to run the query against * * @return */ public Results setArea(String area) { this.area = area; return this; } /** * @return A list of spell corrections based on the search term. */ public List<String> getDidYouMean() { return didYouMean; } /** * @param didYouMean * Set the list * * @return */ public Results setDidYouMean(List<String> didYouMean) { this.didYouMean = didYouMean; return this; } /** * @return A Related Query object containing a list of related queries for a * given search term e.g. searchTerm :- pizza, relatedQueries :- * pepperoni, cheese, vegetables, stuff crust */ public List<String> getRelatedQueries() { return relatedQueries; } /** * @param relatedQueries * Set the related queries for a search term * * @return */ public Results setRelatedQueries(List<String> relatedQueries) { this.relatedQueries = relatedQueries; return this; } /** * @return A list of the records for this search and navigation state. */ public List<Record> getRecords() { return records; } /** * @param records * Set the records. * * @return */ public Results setRecords(List<Record> records) { this.records = records; return this; } /** * @return If a rule has fired a template will be returned specified in the * rule. */ public Template getTemplate() { return template; } /** * @param template * Set the template * * @return */ public Results setTemplate(Template template) { this.template = template; return this; } /** * @return Information about the results page. */ public PageInfo getPageInfo() { return pageInfo; } /** * @param pageInfo * Set the page info * * @return */ public Results setPageInfo(PageInfo pageInfo) { this.pageInfo = pageInfo; return this; } /** * @return A list of all the ways in which you can filter the current result * set. */ public List<Navigation> getAvailableNavigation() { return availableNavigation; } /** * @param availableNavigation * Set the available navigation. * * @return */ public Results setAvailableNavigation(List<Navigation> availableNavigation) { this.availableNavigation = availableNavigation; return this; } /** * @return A list of the currently selected refinements. Also known as breadcrumbs. */ public List<Navigation> getSelectedNavigation() { return selectedNavigation; } /** * @param selectedNavigation * Set the selected refinements * * @return */ public Results setSelectedNavigation(List<Navigation> selectedNavigation) { this.selectedNavigation = selectedNavigation; return this; } /** * @return A JSON-formatted string representing the selected refinements. */ @JsonIgnore public String getSelectedNavigationJson() { if (selectedNavigation != null) { try { return Mappers.JSON.writeValueAsString(selectedNavigation); } catch (JsonProcessingException e) { // Ignore } } return "[]"; } /** * <code> * Note, if a redirect is triggered the engine does not send back records. * </code> * * @return A URL to redirect to based on this search term. */ public String getRedirect() { return redirect; } /** * @param redirect * Set the redirect * * @return */ public Results setRedirect(String redirect) { this.redirect = redirect; return this; } /** * @return String representation of any errors encountered. */ public String getErrors() { return errors; } /** * @param errors * Set errors. * * @return */ public Results setErrors(String errors) { this.errors = errors; return this; } /** * @return A count of the total number of records in this search and * navigation state. */ public long getTotalRecordCount() { return totalRecordCount; } /** * @param totalRecordCount * Set the total record count. * * @return */ public Results setTotalRecordCount(long totalRecordCount) { this.totalRecordCount = totalRecordCount; return this; } /** * @return A list of metadata as set in the area management section of the * command center. */ public List<Metadata> getSiteParams() { return siteParams; } /** * @param siteParams * Set the site metadata * * @return */ public Results setSiteParams(List<Metadata> siteParams) { this.siteParams = siteParams; return this; } /** * @return The original query sent to the search service */ public String getOriginalQuery() { return originalQuery; } /** * @param originalQuery * Sets the original query sent to the search service * * @return */ public Results setOriginalQuery(String originalQuery) { this.originalQuery = originalQuery; return this; } /** * @return The corrected query sent to the engine, if auto-correction is enabled */ public String getCorrectedQuery() { return correctedQuery; } /** * @param correctedQuery * Sets the corrected query sent to the engine, if auto-correction is enabled * * @return */ public Results setCorrectedQuery(String correctedQuery) { this.correctedQuery = correctedQuery; return this; } /** * @return The query sent to the engine, after query rewrites are applied */ public String getQuery() { return query; } /** * @param query * Sets the query sent to the engine, after query rewrites are applied * * @return */ public Results setQuery(String query) { this.query = query; return this; } /** * @return A list of rewrites (spellings, synonyms, etc...) that occurred. */ public List<String> getRewrites() { return rewrites; } /** * @param rewrites * Set the rewrites that occurred * * @return */ public Results setRewrites(List<String> rewrites) { this.rewrites = rewrites; return this; } /** * @return The biasing profile in effect. */ public String getBiasingProfile() { return biasingProfile; } /** * @param biasingProfile * Set the biasing profile in effect * * @return */ public Results setBiasingProfile(String biasingProfile) { this.biasingProfile = biasingProfile; return this; } /** * @return A list of warnings encountered. */ public List<String> getWarnings() { return warnings; } /** * @param warnings * Set warnings. * * @return */ public Results setWarnings(List<String> warnings) { this.warnings = warnings; return this; } /** * @param warnings * The warnings to add * @return */ public Results addWarnings(Collection<String> warnings) { if (warnings != null) { for (String warning : warnings) { addWarning(warning); } } return this; } /** * @param warning * The warning to add * @return */ public Results addWarning(String warning) { if (warnings == null) { warnings = new ArrayList<String>(); } this.warnings.add(warning); return this; } /** * @return The match strategy. */ public MatchStrategy getMatchStrategy() { return matchStrategy; } /** * @param matchStrategy * Set the match strategy in effect * * @return */ public Results setMatchStrategy(MatchStrategy matchStrategy) { this.matchStrategy = matchStrategy; return this; } /** * @return The original request received. */ public Request getOriginalRequest() { return originalRequest; } /** * @param originalRequest * Set the original request * * @return */ public Results setOriginalRequest(Request originalRequest) { this.originalRequest = originalRequest; return this; } }
package com.j256.ormlite.field; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.SQLException; import java.util.Collection; import java.util.Map; import com.j256.ormlite.dao.BaseDaoImpl; import com.j256.ormlite.dao.BaseForeignCollection; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.dao.EagerForeignCollection; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.dao.LazyForeignCollection; import com.j256.ormlite.dao.ObjectCache; import com.j256.ormlite.db.DatabaseType; import com.j256.ormlite.field.types.VoidType; import com.j256.ormlite.misc.BaseDaoEnabled; import com.j256.ormlite.misc.SqlExceptionUtil; import com.j256.ormlite.stmt.mapped.MappedQueryForId; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.support.DatabaseConnection; import com.j256.ormlite.support.DatabaseResults; import com.j256.ormlite.table.DatabaseTableConfig; import com.j256.ormlite.table.TableInfo; /** * Per field information configured from the {@link DatabaseField} annotation and the associated {@link Field} in the * class. Use the {@link #createFieldType} static method to instantiate the class. * * @author graywatson */ public class FieldType { /** default suffix added to fields that are id fields of foreign objects */ public static final String FOREIGN_ID_FIELD_SUFFIX = "_id"; /* * Default values. * * NOTE: These don't get any values so the compiler assigns them to the default values for the type. Ahhhh. Smart. */ private static boolean DEFAULT_VALUE_BOOLEAN; private static byte DEFAULT_VALUE_BYTE; private static char DEFAULT_VALUE_CHAR; private static short DEFAULT_VALUE_SHORT; private static int DEFAULT_VALUE_INT; private static long DEFAULT_VALUE_LONG; private static float DEFAULT_VALUE_FLOAT; private static double DEFAULT_VALUE_DOUBLE; private final ConnectionSource connectionSource; private final Field field; private final String dbColumnName; private final DatabaseFieldConfig fieldConfig; private final boolean isId; private final boolean isGeneratedId; private final String generatedIdSequence; private final Method fieldGetMethod; private final Method fieldSetMethod; private DataPersister dataPersister; private Object defaultValue; private Object dataTypeConfigObj; private FieldConverter fieldConverter; private FieldType foreignIdField; private Constructor<?> foreignConstructor; private FieldType foreignFieldType; private Dao<?, ?> foreignDao; private MappedQueryForId<Object, Object> mappedQueryForId; private static final ThreadLocal<LevelCounters> threadLevelCounters = new ThreadLocal<LevelCounters>(); /** * You should use {@link FieldType#createFieldType} to instantiate one of these field if you have a {@link Field}. */ public FieldType(ConnectionSource connectionSource, String tableName, Field field, DatabaseFieldConfig fieldConfig, Class<?> parentClass) throws SQLException { this.connectionSource = connectionSource; DatabaseType databaseType = connectionSource.getDatabaseType(); this.field = field; Class<?> clazz = field.getType(); DataPersister dataPersister; if (fieldConfig.getDataPersister() == null) { Class<? extends DataPersister> persisterClass = fieldConfig.getPersisterClass(); if (persisterClass == null || persisterClass == VoidType.class) { dataPersister = DataPersisterManager.lookupForField(field); } else { Method method; try { method = persisterClass.getDeclaredMethod("getSingleton"); } catch (Exception e) { throw SqlExceptionUtil.create("Could not find getSingleton static method on class " + persisterClass, e); } Object result; try { result = method.invoke(null); } catch (InvocationTargetException e) { throw SqlExceptionUtil.create("Could not run getSingleton method on class " + persisterClass, e.getTargetException()); } catch (Exception e) { throw SqlExceptionUtil.create("Could not run getSingleton method on class " + persisterClass, e); } if (result == null) { throw new SQLException("Static getSingleton method should not return null on class " + persisterClass); } try { dataPersister = (DataPersister) result; } catch (Exception e) { throw SqlExceptionUtil.create( "Could not cast result of static getSingleton method to DataPersister from class " + persisterClass, e); } } } else { dataPersister = fieldConfig.getDataPersister(); if (!dataPersister.isValidForField(field)) { throw new IllegalArgumentException("Field class " + clazz + " for field " + this + " is not valid for data persister " + dataPersister); } } String defaultFieldName = field.getName(); if (fieldConfig.isForeign() || fieldConfig.isForeignAutoRefresh()) { if (dataPersister != null && dataPersister.isPrimitive()) { throw new IllegalArgumentException("Field " + this + " is a primitive class " + clazz + " but marked as foreign"); } defaultFieldName = defaultFieldName + FOREIGN_ID_FIELD_SUFFIX; } else if (fieldConfig.isForeignCollection()) { if (clazz != Collection.class && !ForeignCollection.class.isAssignableFrom(clazz)) { throw new SQLException("Field class for '" + field.getName() + "' must be of class " + ForeignCollection.class.getSimpleName() + " or Collection."); } Type type = field.getGenericType(); if (!(type instanceof ParameterizedType)) { throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection."); } Type[] genericArguments = ((ParameterizedType) type).getActualTypeArguments(); if (genericArguments.length == 0) { // i doubt this will ever be reached throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection with at least 1 type."); } } else if (dataPersister == null && (!fieldConfig.isForeignCollection())) { if (byte[].class.isAssignableFrom(clazz)) { throw new SQLException("ORMLite can't store unknown class " + clazz + " for field '" + field.getName() + "'. byte[] fields must specify dataType=DataType.BYTE_ARRAY or SERIALIZABLE"); } else if (Serializable.class.isAssignableFrom(clazz)) { throw new SQLException("ORMLite can't store unknown class " + clazz + " for field '" + field.getName() + "'. Serializable fields must specify dataType=DataType.SERIALIZABLE"); } else { throw new IllegalArgumentException("ORMLite does not know how to store field class " + clazz + " for field " + this); } } if (fieldConfig.getColumnName() == null) { this.dbColumnName = defaultFieldName; } else { this.dbColumnName = fieldConfig.getColumnName(); } this.fieldConfig = fieldConfig; if (fieldConfig.isId()) { if (fieldConfig.isGeneratedId() || fieldConfig.getGeneratedIdSequence() != null) { throw new IllegalArgumentException("Must specify one of id, generatedId, and generatedIdSequence with " + field.getName()); } this.isId = true; this.isGeneratedId = false; this.generatedIdSequence = null; } else if (fieldConfig.isGeneratedId()) { if (fieldConfig.getGeneratedIdSequence() != null) { throw new IllegalArgumentException("Must specify one of id, generatedId, and generatedIdSequence with " + field.getName()); } this.isId = true; this.isGeneratedId = true; if (databaseType.isIdSequenceNeeded()) { this.generatedIdSequence = databaseType.generateIdSequenceName(tableName, this); } else { this.generatedIdSequence = null; } } else if (fieldConfig.getGeneratedIdSequence() != null) { this.isId = true; this.isGeneratedId = true; String seqName = fieldConfig.getGeneratedIdSequence(); if (databaseType.isEntityNamesMustBeUpCase()) { seqName = seqName.toUpperCase(); } this.generatedIdSequence = seqName; } else { this.isId = false; this.isGeneratedId = false; this.generatedIdSequence = null; } if (this.isId && (fieldConfig.isForeign() || fieldConfig.isForeignAutoRefresh())) { throw new IllegalArgumentException("Id field " + field.getName() + " cannot also be a foreign object"); } if (fieldConfig.isUseGetSet()) { this.fieldGetMethod = DatabaseFieldConfig.findGetMethod(field, true); this.fieldSetMethod = DatabaseFieldConfig.findSetMethod(field, true); } else { if (!field.isAccessible()) { try { this.field.setAccessible(true); } catch (SecurityException e) { throw new IllegalArgumentException("Could not open access to field " + field.getName() + ". You may have to set useGetSet=true to fix."); } } this.fieldGetMethod = null; this.fieldSetMethod = null; } if (fieldConfig.isAllowGeneratedIdInsert() && !fieldConfig.isGeneratedId()) { throw new IllegalArgumentException("Field " + field.getName() + " must be a generated-id if allowGeneratedIdInsert = true"); } assignDataType(databaseType, dataPersister); } /** * Because we go recursive in a lot of situations if we construct DAOs inside of the FieldType constructor, we have * to do this 2nd pass initialization so we can better use the DAO caches. * * @see BaseDaoImpl#initialize() */ public void configDaoInformation(ConnectionSource connectionSource, Class<?> parentClass) throws SQLException { Class<?> clazz = field.getType(); DatabaseType databaseType = connectionSource.getDatabaseType(); TableInfo<?, ?> foreignTableInfo; final FieldType foreignIdField; final Constructor<?> foreignConstructor; final FieldType foreignFieldType; final Dao<?, ?> foreignDao; final MappedQueryForId<Object, Object> mappedQueryForId; if (fieldConfig.isForeignAutoRefresh()) { DatabaseTableConfig<?> tableConfig = fieldConfig.getForeignTableConfig(); if (tableConfig == null) { // NOTE: the cast is necessary for maven foreignDao = (BaseDaoImpl<?, ?>) DaoManager.createDao(connectionSource, clazz); foreignTableInfo = ((BaseDaoImpl<?, ?>) foreignDao).getTableInfo(); } else { tableConfig.extractFieldTypes(connectionSource); // NOTE: the cast is necessary for maven foreignDao = (BaseDaoImpl<?, ?>) DaoManager.createDao(connectionSource, tableConfig); foreignTableInfo = ((BaseDaoImpl<?, ?>) foreignDao).getTableInfo(); } foreignIdField = foreignTableInfo.getIdField(); if (foreignIdField == null) { throw new IllegalArgumentException("Foreign field " + clazz + " does not have id field"); } @SuppressWarnings("unchecked") MappedQueryForId<Object, Object> castMappedQueryForId = (MappedQueryForId<Object, Object>) MappedQueryForId.build(databaseType, foreignTableInfo); mappedQueryForId = castMappedQueryForId; foreignConstructor = foreignTableInfo.getConstructor(); foreignFieldType = null; } else if (fieldConfig.isForeign()) { /* * If we are a foreign-field or if the foreign-auto-refresh was in too deep then we configure this as a * foreign field. This is <= instead of < because we go one more level than the foreign auto-refresh. */ if (this.dataPersister != null && this.dataPersister.isPrimitive()) { throw new IllegalArgumentException("Field " + this + " is a primitive class " + clazz + " but marked as foreign"); } DatabaseTableConfig<?> tableConfig = fieldConfig.getForeignTableConfig(); if (tableConfig != null) { tableConfig.extractFieldTypes(connectionSource); // NOTE: the cast is necessary for maven foreignDao = (BaseDaoImpl<?, ?>) DaoManager.createDao(connectionSource, tableConfig); foreignTableInfo = ((BaseDaoImpl<?, ?>) foreignDao).getTableInfo(); foreignIdField = foreignTableInfo.getIdField(); foreignConstructor = foreignTableInfo.getConstructor(); } else if (BaseDaoEnabled.class.isAssignableFrom(clazz)) { // NOTE: the cast is necessary for maven foreignDao = (BaseDaoImpl<?, ?>) DaoManager.createDao(connectionSource, clazz); foreignTableInfo = ((BaseDaoImpl<?, ?>) foreignDao).getTableInfo(); foreignIdField = foreignTableInfo.getIdField(); foreignConstructor = foreignTableInfo.getConstructor(); } else { foreignDao = null; foreignIdField = DatabaseTableConfig.extractIdFieldType(connectionSource, clazz, DatabaseTableConfig.extractTableName(clazz)); foreignConstructor = DatabaseTableConfig.findNoArgConstructor(clazz); } if (foreignIdField == null) { throw new IllegalArgumentException("Foreign field " + clazz + " does not have id field"); } foreignFieldType = null; mappedQueryForId = null; } else if (fieldConfig.isForeignCollection()) { if (clazz != Collection.class && !ForeignCollection.class.isAssignableFrom(clazz)) { throw new SQLException("Field class for '" + field.getName() + "' must be of class " + ForeignCollection.class.getSimpleName() + " or Collection."); } Type type = field.getGenericType(); if (!(type instanceof ParameterizedType)) { throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection."); } Type[] genericArguments = ((ParameterizedType) type).getActualTypeArguments(); if (genericArguments.length == 0) { // i doubt this will ever be reached throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection with at least 1 type."); } clazz = (Class<?>) genericArguments[0]; DatabaseTableConfig<?> tableConfig = fieldConfig.getForeignTableConfig(); Dao<Object, Object> foundDao; if (tableConfig == null) { @SuppressWarnings("unchecked") Dao<Object, Object> castDao = (Dao<Object, Object>) DaoManager.createDao(connectionSource, clazz); foundDao = castDao; } else { @SuppressWarnings("unchecked") Dao<Object, Object> castDao = (Dao<Object, Object>) DaoManager.createDao(connectionSource, tableConfig); foundDao = castDao; } FieldType findForeignFieldType = null; for (FieldType fieldType : ((BaseDaoImpl<?, ?>) foundDao).getTableInfo().getFieldTypes()) { if (fieldType.getFieldType() == parentClass) { findForeignFieldType = fieldType; break; } } if (findForeignFieldType == null) { throw new SQLException("Foreign collection object " + clazz + " for field '" + field.getName() + "' does not contain a foreign field of class " + parentClass); } if (!findForeignFieldType.fieldConfig.isForeign() && !findForeignFieldType.fieldConfig.isForeignAutoRefresh()) { // this may never be reached throw new SQLException("Foreign collection object " + clazz + " for field '" + field.getName() + "' contains a field of class " + parentClass + " but it's not foreign"); } foreignDao = foundDao; foreignFieldType = findForeignFieldType; foreignIdField = null; foreignConstructor = null; mappedQueryForId = null; } else { foreignConstructor = null; foreignIdField = null; foreignFieldType = null; foreignDao = null; mappedQueryForId = null; } this.mappedQueryForId = mappedQueryForId; this.foreignConstructor = foreignConstructor; this.foreignFieldType = foreignFieldType; this.foreignDao = foreignDao; this.foreignIdField = foreignIdField; if (foreignIdField != null) { assignDataType(databaseType, foreignIdField.getDataPersister()); } } public Field getField() { return field; } public String getFieldName() { return field.getName(); } /** * Return the class of the field associated with this field type. */ public Class<?> getFieldType() { return field.getType(); } public String getDbColumnName() { return dbColumnName; } public DataPersister getDataPersister() { return dataPersister; } public Object getDataTypeConfigObj() { return dataTypeConfigObj; } public SqlType getSqlType() { return fieldConverter.getSqlType(); } /** * Return the default value as parsed from the {@link DatabaseFieldConfig#getDefaultValue()}. */ public Object getDefaultValue() { return defaultValue; } public int getWidth() { return fieldConfig.getWidth(); } public boolean isCanBeNull() { return fieldConfig.isCanBeNull(); } /** * Return whether the field is an id field. It is an id if {@link DatabaseField#id}, * {@link DatabaseField#generatedId}, OR {@link DatabaseField#generatedIdSequence} are enabled. */ public boolean isId() { return isId; } /** * Return whether the field is a generated-id field. This is true if {@link DatabaseField#generatedId} OR * {@link DatabaseField#generatedIdSequence} are enabled. */ public boolean isGeneratedId() { return isGeneratedId; } /** * Return whether the field is a generated-id-sequence field. This is true if * {@link DatabaseField#generatedIdSequence} is specified OR if {@link DatabaseField#generatedId} is enabled and the * {@link DatabaseType#isIdSequenceNeeded} is enabled. If the latter is true then the sequence name will be * auto-generated. */ public boolean isGeneratedIdSequence() { return generatedIdSequence != null; } /** * Return the generated-id-sequence associated with the field or null if {@link #isGeneratedIdSequence} is false. */ public String getGeneratedIdSequence() { return generatedIdSequence; } public boolean isForeign() { return fieldConfig.isForeign(); } public FieldType getForeignFieldType() { return foreignFieldType; } /** * Assign to the data object the val corresponding to the fieldType. */ public void assignField(Object data, Object val, boolean parentObject, ObjectCache objectCache) throws SQLException { // if this is a foreign object then val is the foreign object's id val if (foreignIdField != null && val != null) { // get the current field value which is the foreign-id Object foreignId = extractJavaFieldValue(data); /* * See if we don't need to create a new foreign object. If we are refreshing and the id field has not * changed then there is no need to create a new foreign object and maybe lose previously refreshed field * information. */ if (foreignId != null && foreignId.equals(val)) { return; } if (!parentObject) { Object foreignObject; /* * If we don't have a mappedQueryForId or if we have recursed the proper number of times, just return a * shell with the id set. */ LevelCounters levelCounters = getLevelCounters(); if (mappedQueryForId == null || levelCounters.autoRefreshlevel >= fieldConfig.getMaxForeignAutoRefreshLevel()) { // create a shell and assign its id field foreignObject = TableInfo.createObject(foreignConstructor, foreignDao); foreignIdField.assignField(foreignObject, val, false, objectCache); } else { levelCounters.autoRefreshlevel++; try { DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(); try { foreignObject = mappedQueryForId.execute(databaseConnection, val, objectCache); } finally { connectionSource.releaseConnection(databaseConnection); } } finally { levelCounters.autoRefreshlevel } } // the value we are to assign to our field is now the foreign object itself val = foreignObject; } } if (fieldSetMethod == null) { try { field.set(data, val); } catch (IllegalArgumentException e) { throw SqlExceptionUtil.create("Could not assign object '" + val + "' to field " + this, e); } catch (IllegalAccessException e) { throw SqlExceptionUtil.create("Could not assign object '" + val + "' to field " + this, e); } } else { try { fieldSetMethod.invoke(data, val); } catch (Exception e) { throw SqlExceptionUtil.create("Could not call " + fieldSetMethod + " on object with '" + val + "' for " + this, e); } } } /** * Assign an ID value to this field. */ public Object assignIdValue(Object data, Number val, ObjectCache objectCache) throws SQLException { Object idVal = dataPersister.convertIdNumber(val); if (idVal == null) { throw new SQLException("Invalid class " + dataPersister + " for sequence-id " + this); } else { assignField(data, idVal, false, objectCache); return idVal; } } /** * Return the value from the field in the object that is defined by this FieldType. */ public <FV> FV extractJavaFieldValue(Object object) throws SQLException { Object val; if (fieldGetMethod == null) { try { // field object may not be a T yet val = field.get(object); } catch (Exception e) { throw SqlExceptionUtil.create("Could not get field value for " + this, e); } } else { try { val = fieldGetMethod.invoke(object); } catch (Exception e) { throw SqlExceptionUtil.create("Could not call " + fieldGetMethod + " for " + this, e); } } if (val == null) { return null; } // if this is a foreign object then we want its id field if (foreignIdField != null) { val = foreignIdField.extractJavaFieldValue(val); } @SuppressWarnings("unchecked") FV converted = (FV) val; return converted; } /** * Extract a field from an object and convert to something suitable to be passed to SQL as an argument. */ public Object extractJavaFieldToSqlArgValue(Object object) throws SQLException { return convertJavaFieldToSqlArgValue(extractJavaFieldValue(object)); } /** * Convert a field value to something suitable to be stored in the database. */ public <FV> FV convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException { if (fieldVal == null) { return null; } else { fieldVal = fieldConverter.javaToSqlArg(this, fieldVal); @SuppressWarnings("unchecked") FV converted = (FV) fieldVal; return converted; } } /** * Return the id field associated with the foreign object or null if none. */ public FieldType getForeignIdField() throws SQLException { return foreignIdField; } /** * Call through to {@link DataPersister#isEscapedValue()} */ public boolean isEscapedValue() { return dataPersister.isEscapedValue(); } public Enum<?> getUnknownEnumVal() { return fieldConfig.getUnknownEnumValue(); } /** * Return the format of the field. */ public String getFormat() { return fieldConfig.getFormat(); } public boolean isUnique() { return fieldConfig.isUnique(); } public boolean isUniqueCombo() { return fieldConfig.isUniqueCombo(); } public String getIndexName() { return fieldConfig.getIndexName(); } public String getUniqueIndexName() { return fieldConfig.getUniqueIndexName(); } /** * Call through to {@link DataPersister#isEscapedDefaultValue()} */ public boolean isEscapedDefaultValue() { return dataPersister.isEscapedDefaultValue(); } /** * Call through to {@link DataPersister#isComparable()} */ public boolean isComparable() { return dataPersister.isComparable(); } /** * Call through to {@link DataPersister#isSelectArgRequired()} */ public boolean isArgumentHolderRequired() { return dataPersister.isSelectArgRequired(); } /** * Call through to {@link DatabaseFieldConfig#isForeignCollection()} */ public boolean isForeignCollection() { return fieldConfig.isForeignCollection(); } /** * Build and return a foreign collection based on the field settings that matches the id argument. This can return * null in certain circumstances. * * @param parent * The parent object that we will set on each item in the collection. * @param id * The id of the foreign object we will look for. This can be null if we are creating an empty * collection. * @param forceEager * Set to true to force this to be an eager collection. */ public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(FT parent, Object id, boolean forceEager) throws SQLException { // this can happen if we have a foreign-auto-refresh scenario if (foreignFieldType == null) { return null; } @SuppressWarnings("unchecked") Dao<FT, FID> castDao = (Dao<FT, FID>) foreignDao; if (!fieldConfig.isForeignCollectionEager() && !forceEager) { // we know this won't go recursive so no need for the counters return new LazyForeignCollection<FT, FID>(castDao, foreignFieldType.dbColumnName, id, fieldConfig.getForeignCollectionOrderColumn(), parent); } LevelCounters levelCounters = getLevelCounters(); // are we over our level limit? if (levelCounters.foreignCollectionLevel >= fieldConfig.getMaxEagerForeignCollectionLevel()) { // then return a lazy collection instead return new LazyForeignCollection<FT, FID>(castDao, foreignFieldType.dbColumnName, id, fieldConfig.getForeignCollectionOrderColumn(), parent); } levelCounters.foreignCollectionLevel++; try { return new EagerForeignCollection<FT, FID>(castDao, parent, foreignFieldType, id, fieldConfig.getForeignCollectionOrderColumn()); } finally { levelCounters.foreignCollectionLevel } } /** * Get the result object from the results. A call through to {@link FieldConverter#resultToJava}. */ public <T> T resultToJava(DatabaseResults results, Map<String, Integer> columnPositions) throws SQLException { Integer dbColumnPos = columnPositions.get(dbColumnName); if (dbColumnPos == null) { dbColumnPos = results.findColumn(dbColumnName); columnPositions.put(dbColumnName, dbColumnPos); } @SuppressWarnings("unchecked") T converted = (T) fieldConverter.resultToJava(this, results, dbColumnPos); if (dataPersister.isPrimitive()) { if (fieldConfig.isThrowIfNull() && results.wasNull(dbColumnPos)) { throw new SQLException("Results value for primitive field '" + field.getName() + "' was an invalid null value"); } } else if (!fieldConverter.isStreamType() && results.wasNull(dbColumnPos)) { // we can't check if we have a null if this is a stream type return null; } return converted; } /** * Call through to {@link DataPersister#isSelfGeneratedId()} */ public boolean isSelfGeneratedId() { return dataPersister.isSelfGeneratedId(); } /** * Call through to {@link DatabaseFieldConfig#isAllowGeneratedIdInsert()} */ public boolean isAllowGeneratedIdInsert() { return fieldConfig.isAllowGeneratedIdInsert(); } /** * Call through to {@link DatabaseFieldConfig#getColumnDefinition()} */ public String getColumnDefinition() { return fieldConfig.getColumnDefinition(); } /** * Call through to {@link DataPersister#generateId()} */ public Object generateId() { return dataPersister.generateId(); } /** * Return the value of field in the data argument if it is not the default value for the class. If it is the default * then null is returned. */ public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException { @SuppressWarnings("unchecked") FV fieldValue = (FV) extractJavaFieldValue(object); if (isFieldValueDefault(fieldValue)) { return null; } else { return fieldValue; } } /** * Return whether or not the data object has a default value passed for this field of this type. */ public boolean isObjectsFieldValueDefault(Object object) throws SQLException { Object fieldValue = extractJavaFieldValue(object); return isFieldValueDefault(fieldValue); } /** * Return whether or not the field value passed in is the default value for the type of the field. Null will return * true. */ public boolean isFieldValueDefault(Object fieldValue) { if (fieldValue == null) { return true; } if (field.getType() == boolean.class) { return fieldValue.equals(DEFAULT_VALUE_BOOLEAN); } else if (field.getType() == byte.class || field.getType() == Byte.class) { return fieldValue.equals(DEFAULT_VALUE_BYTE); } else if (field.getType() == char.class || field.getType() == Character.class) { return fieldValue.equals(DEFAULT_VALUE_CHAR); } else if (field.getType() == short.class || field.getType() == Short.class) { return fieldValue.equals(DEFAULT_VALUE_SHORT); } else if (field.getType() == int.class || field.getType() == Integer.class) { return fieldValue.equals(DEFAULT_VALUE_INT); } else if (field.getType() == long.class || field.getType() == Long.class) { return fieldValue.equals(DEFAULT_VALUE_LONG); } else if (field.getType() == float.class || field.getType() == Float.class) { return fieldValue.equals(DEFAULT_VALUE_FLOAT); } else if (field.getType() == double.class || field.getType() == Double.class) { return fieldValue.equals(DEFAULT_VALUE_DOUBLE); } else { return false; } } /** * Return An instantiated {@link FieldType} or null if the field does not have a {@link DatabaseField} annotation. */ public static FieldType createFieldType(ConnectionSource connectionSource, String tableName, Field field, Class<?> parentClass) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); DatabaseFieldConfig fieldConfig = DatabaseFieldConfig.fromField(databaseType, tableName, field); if (fieldConfig == null) { return null; } else { return new FieldType(connectionSource, tableName, field, fieldConfig, parentClass); } } @Override public boolean equals(Object arg) { if (arg == null || arg.getClass() != this.getClass()) { return false; } FieldType other = (FieldType) arg; return field.equals(other.field); } @Override public int hashCode() { return field.hashCode(); } @Override public String toString() { return getClass().getSimpleName() + ":name=" + field.getName() + ",class=" + field.getDeclaringClass().getSimpleName(); } /** * Configure our data persister and any dependent fields. We have to do this here because both the constructor and * {@link #configDaoInformation} method can set the data-type. */ private void assignDataType(DatabaseType databaseType, DataPersister dataPersister) throws SQLException { this.dataPersister = dataPersister; if (dataPersister == null) { return; } this.fieldConverter = databaseType.getFieldConverter(dataPersister); if (this.isGeneratedId && !dataPersister.isValidGeneratedType()) { StringBuilder sb = new StringBuilder(); sb.append("Generated-id field '").append(field.getName()); sb.append("' in ").append(field.getDeclaringClass().getSimpleName()); sb.append(" can't be type ").append(this.dataPersister.getSqlType()); sb.append(". Must be one of: "); for (DataType dataType : DataType.values()) { DataPersister persister = dataType.getDataPersister(); if (persister != null && persister.isValidGeneratedType()) { sb.append(dataType).append(' '); } } throw new IllegalArgumentException(sb.toString()); } if (fieldConfig.isThrowIfNull() && !dataPersister.isPrimitive()) { throw new SQLException("Field " + field.getName() + " must be a primitive if set with throwIfNull"); } if (this.isId && !dataPersister.isAppropriateId()) { throw new SQLException("Field '" + field.getName() + "' is of data type " + dataPersister + " which cannot be the ID field"); } this.dataTypeConfigObj = dataPersister.makeConfigObject(this); String defaultStr = fieldConfig.getDefaultValue(); if (defaultStr == null || defaultStr.equals("")) { this.defaultValue = null; } else if (this.isGeneratedId) { throw new SQLException("Field '" + field.getName() + "' cannot be a generatedId and have a default value '" + defaultStr + "'"); } else { this.defaultValue = this.fieldConverter.parseDefaultString(this, defaultStr); } } private LevelCounters getLevelCounters() { LevelCounters levelCounters = threadLevelCounters.get(); if (levelCounters == null) { levelCounters = new LevelCounters(); threadLevelCounters.set(levelCounters); } return levelCounters; } private static class LevelCounters { int autoRefreshlevel; int foreignCollectionLevel; } }
package com.j256.simplemagic; import java.util.HashMap; import java.util.Map; /** * Enumerated type of the content if it is known by SimpleMagic matched from the mime-type. This information is _not_ * processed from the magic files. * * @author graywatson */ public enum ContentType { /** AIFF audio format */ AIFF("audio/x-aiff", "aiff", "aif", "aiff", "aifc"), /** Apple Quicktime image */ APPLE_QUICKTIME_IMAGE("image/x-quicktime", null), /** Apple Quicktime movie */ APPLE_QUICKTIME_MOVIE("video/quicktime", "quicktime", "qt", "mov"), /** ARC archive data */ ARC("application/x-arc", "arc", "arc"), /** MPEG audio file */ AUDIO_MPEG("audio/mpeg", "mpeg", "mpeg", "mpg", "mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"), /** Microsoft AVI video file */ AVI("video/x-msvideo", "avi", "avi"), /** Unix AWK command script */ AWK("text/x-awk", "awk", "awk"), /** Macintosh BinHex file */ BINHEX("application/mac-binhex40", "binhex", "hqx"), /** Bittorrent file */ BITTORRENT("application/x-bittorrent", "bittorrent", "torrent"), /** Microsoft PC bitmap image */ BMP("image/x-ms-bmp", "bmp", "bmp"), /** Bzip2 compressed file */ BZIP2("application/x-bzip2", "bzip2", "bz2", "boz"), /** Unix compress file */ COMPRESS("application/x-compress", "compress", "Z"), /** Corel Draw image file */ COREL_DRAW("image/x-coreldraw", "corel-draw"), /** Unix core dump output */ CORE_DUMP("application/x-coredump", "core-dump"), /** Unix CPIO archive data */ CPIO("application/x-cpio", "cpio"), /** Berkeley database file */ DBM("application/x-dbm", "dbm"), /** Debian installation package */ DEBIAN_PACKAGE("application/x-debian-package", "debian-pkg", "pkg", "deb", "udeb"), /** Unix diff output */ DIFF("text/x-diff", "diff"), /** TeX DVI output file */ DVI("application/x-dvi", "dvi", "dvi"), /** Macromedia Flash data */ FLASH("application/x-shockwave-flash", "flash"), /** Macromedia Flash movie file */ FLASH_VIDEO("video/x-flv", "flash-video", "flv"), /** FORTRAN program */ FORTRAN("text/x-fortran", "fortran", "f", "for", "f77", "f90"), /** FrameMaker document */ FRAMEMAKER("application/x-mif", "framemaker", "fm", "frame", "maker", "book"), /** GNU awk script */ GAWK("text/x-gawk", "gawk"), /** GNU database file */ GDBM("application/x-gdbm", "gdbm"), /** GIF image file */ GIF("image/gif", "gif", "gif"), /** GNU Numeric file */ GNUMERIC("application/x-gnumeric", "gnumeric"), /** GPG keyring file */ GNUPG_KEYRING("application/x-gnupg-keyring", "gnupg-keyring"), /** GNU Info file */ GNU_INFO("text/x-info", "gnu-info", "info"), /** Gzip compressed data */ GZIP("application/x-gzip", "gzip", "gz"), /** H264 video encoded file */ H264("video/h264", "h264", "h264"), /** HTML document */ HTML("text/html", "html", "html", "htm"), /** MS Windows icon resource */ ICO("image/x-ico", "ico", "ico"), /** ISO 9660 CD-ROM filesystem data */ ISO_9660("application/x-iso9660-image", "iso9660"), /** Java applet */ JAVA_APPLET("application/x-java-applet", "applet"), /** Java keystore file */ JAVA_KEYSTORE("application/x-java-keystore", "java-keystore"), /** JPEG image */ JPEG("image/jpeg", "jpeg", "jpeg", "jpg", "jpe"), /** JPEG 2000 image */ JPEG_2000("image/jp2", "jp2", "jp2"), /** LHA archive data */ LHA("application/x-lha", "lha", "lha", "lzh"), /** Lisp program */ LISP("text/x-lisp", "lisp"), /** Lotus 123 spreadsheet */ LOTUS_123("application/x-123", "lotus-123", "123"), /** Microsoft access database */ MICROSOFT_ACCESS("application/x-msaccess", "access"), /** Microsoft excel spreadsheet */ MICROSOFT_EXCEL("application/vnd.ms-excel", "excel", "xls", "xlm", "xla", "xlc", "xlt", "xlw"), /** Microsoft word document */ MICROSOFT_WORD("application/msword", "word", "doc", "dot"), /** MIDI audio */ MIDI("audio/midi", "midi", "mid", "midi", "kar", "rmi"), /** MNG video */ MNG("video/x-mng", "mng", "mng"), /** MP4 encoded video */ MP4A("video/mp4", "mp4a", "mp4", "mp4a"), /** MP4V encoded video */ MP4V("video/mp4v-es", "mp4v", "mp4v"), /** New Awk script */ NAWK("text/x-nawk", "nawk"), /** Network news message */ NEWS("message/news", "news"), /** OGG file container */ OGG("application/ogg", "ogg", "ogg", "oga", "spx"), /** PBM image */ PBM("image/x-portable-bitmap", "pbm", "pbm"), /** PDF document */ PDF("application/pdf", "pdf", "pbm"), /** Perl script */ PERL("text/x-perl", "perl", "pl"), /** PGM image */ PGM("image/x-portable-greymap", "pgm", "pgm"), /** PGP encrypted message */ PGP("application/pgp-encrypted", "pgp", "pgp"), /** PGP keyring */ PGP_KEYRING("application/x-pgp-keyring", "pgp-keyring"), /** PGP signature */ PGP_SIGNATURE("application/pgp-signature", "pgp-signature"), /** Photoshop image */ PHOTOSHOP("image/vnd.adobe.photoshop", "photoshop"), /** PHP script */ PHP("text/x-php", "php", "php"), /** PNG image */ PNG("image/png", "png", "png"), /** Postscript file */ POSTSCRIPT("application/postscript", "postscript", "ps", "eps"), /** PPM image */ PPM("image/x-portable-pixmap", "ppm", "ppm"), /** RAR archive data */ RAR("application/x-rar", "rar", "rar"), /** Real-audio file */ REAL_AUDIO("audio/x-pn-realaudio", "real-audio", "ram", "ra"), /** Real-media file */ REAL_MEDIA("application/vnd.rn-realmedia", "real-media"), /** RFC822 news message */ RFC822("message/rfc822", "rfc822"), /** RedHat package file */ RPM("application/x-rpm", "rpm", "rpm"), /** Rich text format document */ RTF("text/rtf", "rtf", "rtf"), /** Shared library file */ SHARED_LIBRARY("application/x-sharedlib", "shared-lib"), /** Unix shell script */ SHELL_SCRIPT("text/x-shellscript", "shell-script", "sh"), /** Mac Stuffit archive data */ STUFFIT("application/x-stuffit", "stuffit"), /** SVG image */ SVG("image/svg+xml", "svg", "svg", "svgz"), /** TAR archive data */ TAR("application/x-tar", "tar", "tar"), /** TeX document */ TEX("text/x-tex", "tex", "tex"), /** TeXinfo document */ TEXINFO("text/x-texinfo", "texinfo", "texinfo", "texi"), /** TIFF image */ TIFF("image/tiff", "tiff", "tiff", "tif"), /** Troff document */ TROFF("text/troff", "troff", "t", "tr", "roff", "man", "me", "ms"), /** vCard visiting card */ VCARD("text/x-vcard", "vcard"), /** Mpeg video */ VIDEO_MPEG("video/mpeg", "mpeg", "mpeg", "mpg", "mpe", "m1v", "m2v"), /** VRML modeling file */ VRML("model/vrml", "vrml", "wrl", "vrml"), /** WAV audio */ WAV("audio/x-wav", "wav", "wav"), /** X3D modeling file */ X3D("model/x3d", "x3d", "x3d"), /** XML document */ XML("application/xml", "xml", "xml", "xsl"), /** Zip archive data */ ZIP("application/zip", "zip", "zip"), /** Zoo archive data */ ZOO("application/x-zoo", "zoo", "zoo"), ANDREW_INSERT("application/andrew-inset", "andrew-insert", "ez"), APPLIXWARE("application/applixware", "applixware", "aw", "aw"), ATOM("application/atom+xml", "atom", "atom"), CU_SEEME("application/cu-seeme", "cu-seeme", "cu"), DOCBOOK("application/docbook+xml", "docbook", "dbk"), DSSC("application/dssc+der", "dssc", "dssc"), ECMA_SCRIPT("application/ecmascript", "ecma", "ecma"), EMMA("application/emma+xml", "emma", "emma"), EPUB("application/epub+zip", "epub", "epub"), EXI("application/exi", "exi", "exi"), FONT_TDPFR("application/font-tdpfr", "pfr", "pfr"), GML("application/gml+xml", "gml", "gml"), GPX("application/gpx+xml", "gpx", "gpx"), GXF("application/gxf", "gxf", "gxf"), HYPER_STUDIO("application/hyperstudio", "hyper-studio", "stk"), INKML("application/inkml+xml", "inkml", "ink", "inkml"), IPFIX("application/ipfix", "ipfix", "ipfix"), JAVA_ARCHIVE("application/java-archive", "java-archive", "jar"), JAVA_SERIALIZED("application/java-serialized-object", "java-serialized", "ser"), JAVA_CLASS("application/java-vm", "java-class", "class"), JAVASCRIPT("application/javascript", "javascript", "js"), JSON("application/json", "json", "json"), JSON_ML("application/jsonml+json", "jsonml", "jsonml"), LOST_XML("application/lost+xml", "lostxml", "lostxml"), COMPACT_PRO("application/mac-compactpro", "compact-pro", "cpt"), MADS("application/mads+xml", "mads", "mads"), MARC("application/marc", "marc", "mrc"), MARC_XML("application/marcxml+xml", "marc-xml", "mrcx"), MATHEMATICA("application/mathematica", "mathematica", "ma", "nb", "mb"), MATH_ML("application/mathml+xml", "mathml", "mathml"), MBOX("application/mbox", "mbox", "mbox"), META4("application/metalink4+xml", "meta4", "meta4"), METS("application/mets+xml", "mets", "mets"), MODS("application/mods+xml", "mods", "mods"), MP21("application/mp21", "mp21", "m21", "mp21"), MXF("application/mxf", "mxf", "mxf"), ODA("application/oda", "oda", "oda"), OEBPS_PACKAGE("application/oebps-package+xml", "oebps-package", "opf"), OMDOC("application/omdoc+xml", "omdoc", "omdoc"), ONE_NOTE("application/onenote", "one-note", "onetoc", "onetoc2", "onetmp", "onepkg"), OXPS("application/oxps", "oxps", "oxps"), PICS_RULES("application/pics-rules", "pics-rules", "prf"), PKCS10("application/pkcs10", "pkcs10", "p10"), PKCS7_MIME("application/pkcs7-mime", "pkcs7-mime", "p7m", "p7c"), PKCS7_SIGNATURE("application/pkcs7-signature", "pkcs7-signature", "p7s"), PKCS8("application/pkcs8", "pkcs8", "p8"), PKIX_ATTR_CERT("application/pkix-attr-cert", "ac", "ac"), PKIX_CERT("application/pkix-cert", "pkix-cert", "cer"), PKIX_CRL("application/pkix-crl", "pkix-crl", "crl"), PKIX_PKIPATH("application/pkix-pkipath", "pkix-pkipath", "pkipath"), PKIXCMP("application/pkixcmp", "pkixcmp", "pki"), PLS("application/pls+xml", "pls-xml", "pls"), PRS_CWW("application/prs.cww", "prs-cww", "cww"), PSKC("application/pskc+xml", "pskc", "pskcxml"), RDF("application/rdf+xml", "rdf", "rdf"), REGINFO("application/reginfo+xml", "reginfo", "rif"), RELAX_NG_COMPACT("application/relax-ng-compact-syntax", "relax-ng-compact", "rnc"), RESOURCE_LISTS("application/resource-lists+xml", "resource-lists", "rl"), RESOURCE_LISTS_DIFF("application/resource-lists-diff+xml", "resource-lists-diff", "rld"), RLS_SERVICES("application/rls-services+xml", "rls-services", "rs"), RPKI_GHOSTBUSTERS("application/rpki-ghostbusters", "rpki-ghostbusters", "gbr"), RPKI_MANIFEST("application/rpki-manifest", "rpki-manifest", "mft"), RPKI_ROA("application/rpki-roa", "rpki-roa", "roa"), RSD("application/rsd+xml", "rsd", "rsd"), RSS("application/rss+xml", "rss", "rss"), SBML("application/sbml+xml", "sbml", "sbml"), SCVP_CV_REQUEST("application/scvp-cv-request", "scvp-cv-request", "scq"), SCVP_CV_RESPONSE("application/scvp-cv-response", "scvp-cv-response", "scs"), SCVP_VP_REQUEST("application/scvp-vp-request", "scvp-vp-request", "spq"), SCVP_VP_RESPONSE("application/scvp-vp-response", "scvp-vp-response", "spp"), SDP("application/sdp", "sdp", "sdp"), SHF("application/shf+xml", "shf", "shf"), SMIL("application/smil+xml", "smil", "smi", "smil"), SPARQL_QUERY("application/sparql-query", "sparql-query", "rq"), SPARQL_RESULTS("application/sparql-results+xml", "sparql-results", "srx"), SRGS("application/srgs", "srgs", "gram"), SRGS_XML("application/srgs+xml", "srgs-xml", "grxml"), SRU("application/sru+xml", "sru", "sru"), SSDL("application/ssdl+xml", "ssdl", "ssdl"), SSML("application/ssml+xml", "ssml", "ssml"), TEI("application/tei+xml", "tei", "tei"), TFI("application/thraud+xml", "tfi", "tfi"), TIMESTAMPED_DATA("application/timestamped-data", "timestamped-data", "tsd"), PLB("application/vnd.3gpp.pic-bw-large", "plb", "plb"), PSB("application/vnd.3gpp.pic-bw-small", "psb", "psb"), PVB("application/vnd.3gpp.pic-bw-var", "pvb", "pvb"), TCAP("application/vnd.3gpp2.tcap", "tcap", "tcap"), PWN("application/vnd.3m.post-it-notes", "pwn", "pwn"), ASO("application/vnd.accpac.simply.aso", "aso", "aso"), IMP("application/vnd.accpac.simply.imp", "imp", "imp"), ACU("application/vnd.acucobol", "acu", "acu"), ACU_CORP("application/vnd.acucorp", "acu-corp", "atc", "acutc"), AIR("application/vnd.adobe.air-application-installer-package+zip", "air", "air"), FCDT("application/vnd.adobe.formscentral.fcdt", "fcdt", "fcdt"), ADOBE_FXP("application/vnd.adobe.fxp", "adobe-fxp", "fxp", "fxpl"), XDP("application/vnd.adobe.xdp+xml", "xdp", "xdp"), XFDF("application/vnd.adobe.xfdf", "xfdf", "xfdf"), AHEAD("application/vnd.ahead.space", "ahead", "ahead"), AZF("application/vnd.airzip.filesecure.azf", "azf", "azf"), AZS("application/vnd.airzip.filesecure.azs", "azs", "azs"), AZW("application/vnd.amazon.ebook", "azw", "azw"), ACC("application/vnd.americandynamics.acc", "acc", "acc"), AMI("application/vnd.amiga.ami", "ami", "ami"), APK("application/vnd.android.package-archive", "apk", "apk"), CII("application/vnd.anser-web-certificate-issue-initiation", "cii", "cii"), FTI("application/vnd.anser-web-funds-transfer-initiation", "fti", "fti"), ATX("application/vnd.antix.game-component", "atx", "atx"), MPKG("application/vnd.apple.installer+xml", "mpkg", "mpkg"), M3U8("application/vnd.apple.mpegurl", "m3u8", "m3u8"), SWI("application/vnd.aristanetworks.swi", "swi", "swi"), IOTA("application/vnd.astraea-software.iota", "iota", "iota"), AEP("application/vnd.audiograph", "aep", "aep"), MPM("application/vnd.blueice.multipass", "mpm", "mpm"), BMI("application/vnd.bmi", "bmi", "bmi"), REP("application/vnd.businessobjects", "rep", "rep"), CDXML("application/vnd.chemdraw+xml", "cdxml", "cdxml"), MMD("application/vnd.chipnuts.karaoke-mmd", "mmd", "mmd"), CDY("application/vnd.cinderella", "cdy", "cdy"), CLA("application/vnd.claymore", "cla", "cla"), RP9("application/vnd.cloanto.rp9", "rp9", "rp9"), CLONK_C4GROUP("application/vnd.clonk.c4group", "clonk-c4group", "c4g", "c4d", "c4f", "c4p", "c4u"), C11AMC("application/vnd.cluetrust.cartomobile-config", "c11amc", "c11amc"), C11AMZ("application/vnd.cluetrust.cartomobile-config-pkg", "c11amz", "c11amz"), CSP("application/vnd.commonspace", "csp", "csp"), CDBCMSG("application/vnd.contact.cmsg", "cdbcmsg", "cdbcmsg"), CMC("application/vnd.cosmocaller", "cmc", "cmc"), CLKX("application/vnd.crick.clicker", "clkx", "clkx"), CLKK("application/vnd.crick.clicker.keyboard", "clkk", "clkk"), CLKP("application/vnd.crick.clicker.palette", "clkp", "clkp"), CLKT("application/vnd.crick.clicker.template", "clkt", "clkt"), CLKW("application/vnd.crick.clicker.wordbank", "clkw", "clkw"), WBS("application/vnd.criticaltools.wbs+xml", "wbs", "wbs"), PML("application/vnd.ctc-posml", "pml", "pml"), PPD("application/vnd.cups-ppd", "ppd", "ppd"), CAR("application/vnd.curl.car", "car", "car"), PCURL("application/vnd.curl.pcurl", "pcurl", "pcurl"), DART("application/vnd.dart", "dart", "dart"), RDZ("application/vnd.data-vision.rdz", "rdz", "rdz"), DECE_DATA("application/vnd.dece.data", "dece-data", "uvf", "uvvf", "uvd", "uvvd"), DECE_TTML("application/vnd.dece.ttml+xml", "dece-ttml", "uvt uvvt"), DECE_UNSPECIFIED("application/vnd.dece.unspecified", "dece-unspecified", "uvx uvvx"), DECE_ZIP("application/vnd.dece.zip", "dece-zip", "uvz", "uvvz"), FE_LAUNCH("application/vnd.denovo.fcselayout-link", "fe_launch", "fe_launch"), DNA("application/vnd.dna", "dna", "dna"), MLP("application/vnd.dolby.mlp", "mlp", "mlp"), DPG("application/vnd.dpgraph", "dpg", "dpg"), DFAC("application/vnd.dreamfactory", "dfac", "dfac"), KPXX("application/vnd.ds-keypoint", "kpxx", "kpxx"), AIT("application/vnd.dvb.ait", "ait", "ait"), SVC("application/vnd.dvb.service", "svc", "svc"), GEO("application/vnd.dynageo", "geo", "geo"), MAG("application/vnd.ecowin.chart", "mag", "mag"), NML("application/vnd.enliven", "nml", "nml"), ESF("application/vnd.epson.esf", "esf", "esf"), MSF("application/vnd.epson.msf", "msf", "msf"), QAM("application/vnd.epson.quickanime", "qam", "qam"), SLT("application/vnd.epson.salt", "slt", "slt"), SSF("application/vnd.epson.ssf", "ssf", "ssf"), ESZIGNO3("application/vnd.eszigno3+xml", "eszigno3", "es3", "et3"), EZ2("application/vnd.ezpix-album", "ez2", "ez2"), EZ3("application/vnd.ezpix-package", "ez3", "ez3"), FDF("application/vnd.fdf", "fdf", "fdf"), MSEED("application/vnd.fdsn.mseed", "mseed", "mseed"), FDSN_SEED("application/vnd.fdsn.seed", "fdns-seed", "seed"), GPH("application/vnd.flographit", "gph", "gph"), FTC("application/vnd.fluxtime.clip", "ftc", "ftc"), FNC("application/vnd.frogans.fnc", "fnc", "fnc"), LTF("application/vnd.frogans.ltf", "ltf", "ltf"), FSC("application/vnd.fsc.weblaunch", "fsc", "fsc"), OAS("application/vnd.fujitsu.oasys", "oas", "oas"), OA2("application/vnd.fujitsu.oasys2", "oa2", "oa2"), OA3("application/vnd.fujitsu.oasys3", "oa3", "oa3"), FG5("application/vnd.fujitsu.oasysgp", "fg5", "fg5"), BH2("application/vnd.fujitsu.oasysprs", "bh2", "bh2"), DDD("application/vnd.fujixerox.ddd", "ddd", "ddd"), XDW("application/vnd.fujixerox.docuworks", "xdw", "xdw"), XBD("application/vnd.fujixerox.docuworks.binder", "xbd", "xbd"), FZS("application/vnd.fuzzysheet", "fzs", "fzs"), TXD("application/vnd.genomatix.tuxedo", "txd", "txd"), GGB("application/vnd.geogebra.file", "ggb", "ggb"), GGT("application/vnd.geogebra.tool", "ggt", "ggt"), GEOMETRY_EXPLORER("application/vnd.geometry-explorer", "geometry-explorer", "gex gre"), GXT("application/vnd.geonext", "gxt", "gxt"), G2W("application/vnd.geoplan", "g2w", "g2w"), G3W("application/vnd.geospace", "g3w", "g3w"), GMX("application/vnd.gmx", "gmx", "gmx"), KML("application/vnd.google-earth.kml+xml", "kml", "kml"), KMZ("application/vnd.google-earth.kmz", "kmz", "kmz"), GRAFEQ("application/vnd.grafeq", "grafeq", "gqf gqs"), GAC("application/vnd.groove-account", "gac", "gac"), GHF("application/vnd.groove-help", "ghf", "ghf"), GIM("application/vnd.groove-identity-message", "gim", "gim"), GRV("application/vnd.groove-injector", "grv", "grv"), GTM("application/vnd.groove-tool-message", "gtm", "gtm"), TPL("application/vnd.groove-tool-template", "tpl", "tpl"), VCG("application/vnd.groove-vcard", "vcg", "vcg"), HAL("application/vnd.hal+xml", "hal", "hal"), ZMM("application/vnd.handheld-entertainment+xml", "zmm", "zmm"), HBCI("application/vnd.hbci", "hbci", "hbci"), LES("application/vnd.hhe.lesson-player", "les", "les"), HPGL("application/vnd.hp-hpgl", "hpgl", "hpgl"), HPID("application/vnd.hp-hpid", "hpid", "hpid"), HPS("application/vnd.hp-hps", "hps", "hps"), JLT("application/vnd.hp-jlyt", "jlt", "jlt"), PCL("application/vnd.hp-pcl", "pcl", "pcl"), PCLXL("application/vnd.hp-pclxl", "pclxl", "pclxl"), HYDROSTATIX_SOF("application/vnd.hydrostatix.sof-data", "hydrostatix-sof", "sfd-hdstx"), MPY("application/vnd.ibm.minipay", "mpy", "mpy"), MODCAP("application/vnd.ibm.modcap", "modcap", "afp", "listafp", "list3820"), IRM("application/vnd.ibm.rights-management", "irm", "irm"), SC("application/vnd.ibm.secure-container", "sc", "sc"), ICC_PROFILE("application/vnd.iccprofile", "icc-profile", "icc", "icm"), IGL("application/vnd.igloader", "igl", "igl"), IVP("application/vnd.immervision-ivp", "ivp", "ivp"), IVU("application/vnd.immervision-ivu", "ivu", "ivu"), IGM("application/vnd.insors.igm", "igm", "igm"), INTERCON("application/vnd.intercon.formnet", "intercon", "xpw", "xpx"), I2G("application/vnd.intergeo", "i2g", "i2g"), QBO("application/vnd.intu.qbo", "qbo", "qbo"), QFX("application/vnd.intu.qfx", "qfx", "qfx"), RCPROFILE("application/vnd.ipunplugged.rcprofile", "rcprofile", "rcprofile"), IRP("application/vnd.irepository.package+xml", "irp", "irp"), XPR("application/vnd.is-xpr", "xpr", "xpr"), FCS("application/vnd.isac.fcs", "fcs", "fcs"), JAM("application/vnd.jam", "jam", "jam"), RMS("application/vnd.jcp.javame.midlet-rms", "rms", "rms"), JISP("application/vnd.jisp", "jisp", "jisp"), JODA("application/vnd.joost.joda-archive", "joda", "joda"), KAHOOTZ("application/vnd.kahootz", "kahootz", "ktz", "ktr"), KARBON("application/vnd.kde.karbon", "karbon", "karbon"), CHRT("application/vnd.kde.kchart", "chrt", "chrt"), KFO("application/vnd.kde.kformula", "kfo", "kfo"), FLW("application/vnd.kde.kivio", "flw", "flw"), KON("application/vnd.kde.kontour", "kon", "kon"), KDE_KPRESENTER("application/vnd.kde.kpresenter", "kde-kpresenter", "kpr", "kpt"), KSP("application/vnd.kde.kspread", "ksp", "ksp"), KDE_WORD("application/vnd.kde.kword", "kde-word", "kwd", "kwt"), HTKE("application/vnd.kenameaapp", "htke", "htke"), KIA("application/vnd.kidspiration", "kia", "kia"), KINAR("application/vnd.kinar", "kinar", "kne", "knp"), KOAN("application/vnd.koan", "koan", "skp skd skt skm"), SSE("application/vnd.kodak-descriptor", "sse", "sse"), LASXML("application/vnd.las.las+xml", "lasxml", "lasxml"), LBD("application/vnd.llamagraphics.life-balance.desktop", "lbd", "lbd"), LBE("application/vnd.llamagraphics.life-balance.exchange+xml", "lbe", "lbe"), APR("application/vnd.lotus-approach", "apr", "apr"), PRE("application/vnd.lotus-freelance", "pre", "pre"), NSF("application/vnd.lotus-notes", "nsf", "nsf"), ORG("application/vnd.lotus-organizer", "org", "org"), SCM("application/vnd.lotus-screencam", "scm", "scm"), LWP("application/vnd.lotus-wordpro", "lwp", "lwp"), PORTPKG("application/vnd.macports.portpkg", "portpkg", "portpkg"), MCD("application/vnd.mcd", "mcd", "mcd"), MC1("application/vnd.medcalcdata", "mc1", "mc1"), CDKEY("application/vnd.mediastation.cdkey", "cdkey", "cdkey"), MWF("application/vnd.mfer", "mwf", "mwf"), MFM("application/vnd.mfmp", "mfm", "mfm"), FLO("application/vnd.micrografx.flo", "flo", "flo"), IGX("application/vnd.micrografx.igx", "igx", "igx"), MIF("application/vnd.mif", "mif", "mif"), DAF("application/vnd.mobius.daf", "daf", "daf"), DIS("application/vnd.mobius.dis", "dis", "dis"), MBK("application/vnd.mobius.mbk", "mbk", "mbk"), MQY("application/vnd.mobius.mqy", "mqy", "mqy"), MSL("application/vnd.mobius.msl", "msl", "msl"), PLC("application/vnd.mobius.plc", "plc", "plc"), TXF("application/vnd.mobius.txf", "txf", "txf"), MPN("application/vnd.mophun.application", "mpn", "mpn"), MPC("application/vnd.mophun.certificate", "mpc", "mpc"), XUL("application/vnd.mozilla.xul+xml", "xul", "xul"), CIL("application/vnd.ms-artgalry", "cil", "cil"), CAB("application/vnd.ms-cab-compressed", "cab", "cab"), FONT_OBJECT("application/vnd.ms-fontobject", "font-object", "eot"), CHM("application/vnd.ms-htmlhelp", "chm", "chm"), IMS("application/vnd.ms-ims", "ims", "ims"), LRM("application/vnd.ms-lrm", "lrm", "lrm"), THMX("application/vnd.ms-officetheme", "thmx", "thmx"), CAT("application/vnd.ms-pki.seccat", "cat", "cat"), STL("application/vnd.ms-pki.stl", "stl", "stl"), MICROSOFT_POWERPOINT("application/vnd.ms-powerpoint", "powerpoint", "ppt", "pps", "pot"), PPAM("application/vnd.ms-powerpoint.addin.macroenabled.12", "ppam", "ppam"), PPTM("application/vnd.ms-powerpoint.presentation.macroenabled.12", "pptm", "pptm"), SLDM("application/vnd.ms-powerpoint.slide.macroenabled.12", "sldm", "sldm"), PPSM("application/vnd.ms-powerpoint.slideshow.macroenabled.12", "ppsm", "ppsm"), POTM("application/vnd.ms-powerpoint.template.macroenabled.12", "potm", "potm"), MICROSOFT_PROJECT("application/vnd.ms-project", "project", "mpp", "mpt"), DOCM("application/vnd.ms-word.document.macroenabled.12", "docm", "docm"), DOTM("application/vnd.ms-word.template.macroenabled.12", "dotm", "dotm"), MICROSOFT_WORKS("application/vnd.ms-works", "works", "wps", "wks", "wcm", "wdb"), WPL("application/vnd.ms-wpl", "wpl", "wpl"), XPS("application/vnd.ms-xpsdocument", "xps", "xps"), MSEQ("application/vnd.mseq", "mseq", "mseq"), MUS("application/vnd.musician", "mus", "mus"), MSTY("application/vnd.muvee.style", "msty", "msty"), TAGLET("application/vnd.mynfc", "taglet", "taglet"), NLU("application/vnd.neurolanguage.nlu", "nlu", "nlu"), NITF("application/vnd.nitf", "nitf", "ntf", "nitf"), NND("application/vnd.noblenet-directory", "nnd", "nnd"), NNS("application/vnd.noblenet-sealer", "nns", "nns"), NNW("application/vnd.noblenet-web", "nnw", "nnw"), NGDAT("application/vnd.nokia.n-gage.data", "ngdat", "ngdat"), N_GAGE("application/vnd.nokia.n-gage.symbian.install", "n-gage", "n-gage"), RPST("application/vnd.nokia.radio-preset", "rpst", "rpst"), RPSS("application/vnd.nokia.radio-presets", "rpss", "rpss"), EDM("application/vnd.novadigm.edm", "edm", "edm"), EDX("application/vnd.novadigm.edx", "edx", "edx"), EXT("application/vnd.novadigm.ext", "ext", "ext"), OPENDOCUMENT_CHART("application/vnd.oasis.opendocument.chart", "odc", "odc"), OPENDOCUMENT_CHART_TEMPLATE("application/vnd.oasis.opendocument.chart-template", "otc", "otc"), OPENDOCUMENT_DATABASE("application/vnd.oasis.opendocument.database", "odb", "odb"), OPENDOCUMENT_FORMULA("application/vnd.oasis.opendocument.formula", "odf", "odf"), OPENDOCUMENT_FORMULA_TEMPLATE("application/vnd.oasis.opendocument.formula-template", "odft", "odft"), OPENDOCUMENT_GRAPHICS("application/vnd.oasis.opendocument.graphics", "odg", "odg"), OPENDOCUMENT_GRAPHICS_TEMPLATE("application/vnd.oasis.opendocument.graphics-template", "otg", "otg"), OPENDOCUMENT_IMAGE("application/vnd.oasis.opendocument.image", "odi", "odi"), OPENDOCUMENT_IMAGE_TEMPLATE("application/vnd.oasis.opendocument.image-template", "oti", "oti"), OPENDOCUMENT_PRESENTATION("application/vnd.oasis.opendocument.presentation", "odp", "odp"), OPENDOCUMENT_PRESENTATION_TEMPLATE("application/vnd.oasis.opendocument.presentation-template", "otp", "otp"), OPENDOCUMENT_SPREADSHEET("application/vnd.oasis.opendocument.spreadsheet", "opendocument-spreadsheet", "ods"), OPENDOCUMENT_SPREADSHEET_TEMPLATE("application/vnd.oasis.opendocument.spreadsheet-template", "ots", "ots"), OPENDOCUMENT_TEXT("application/vnd.oasis.opendocument.text", "opendocument-text", "odt"), OPENDOCUMENT_TEXT_MASTER("application/vnd.oasis.opendocument.text-master", "opendocument-text-master", "odm"), OPENDOCUMENT_TEXT_TEMPLATE("application/vnd.oasis.opendocument.text-template", "opendocument-text-template", "ott"), OTH("application/vnd.oasis.opendocument.text-web", "oth", "oth"), XO("application/vnd.olpc-sugar", "xo", "xo"), DD2("application/vnd.oma.dd2+xml", "dd2", "dd2"), OXT("application/vnd.openofficeorg.extension", "oxt", "oxt"), PPTX("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx", "pptx"), SLDX("application/vnd.openxmlformats-officedocument.presentationml.slide", "sldx", "sldx"), PPSX("application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx", "ppsx"), POTX("application/vnd.openxmlformats-officedocument.presentationml.template", "potx", "potx"), XLSX("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx", "xlsx"), XLTX("application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx", "xltx"), DOCX("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx", "docx"), DOTX("application/vnd.openxmlformats-officedocument.wordprocessingml.template", "dotx", "dotx"), MGP("application/vnd.osgeo.mapguide.package", "mgp", "mgp"), DP("application/vnd.osgi.dp", "dp", "dp"), ESA("application/vnd.osgi.subsystem", "esa", "esa"), PALM("application/vnd.palm", "palm", "pdb", "pqa", "oprc"), PAW("application/vnd.pawaafile", "paw", "paw"), STR("application/vnd.pg.format", "str", "str"), EI6("application/vnd.pg.osasli", "ei6", "ei6"), EFIF("application/vnd.picsel", "efif", "efif"), WG("application/vnd.pmi.widget", "wg", "wg"), PLF("application/vnd.pocketlearn", "plf", "plf"), PBD("application/vnd.powerbuilder6", "pbd", "pbd"), BOX("application/vnd.previewsystems.box", "box", "box"), MGZ("application/vnd.proteus.magazine", "mgz", "mgz"), QPS("application/vnd.publishare-delta-tree", "qps", "qps"), PTID("application/vnd.pvi.ptid1", "ptid", "ptid"), QUARK_XPRESS("application/vnd.quark.quarkxpress", "quark-xpress", "qxd", "qxt", "qwd", "qwt", "qxl", "qxb"), BED("application/vnd.realvnc.bed", "bed", "bed"), MXL("application/vnd.recordare.musicxml", "mxl", "mxl"), MUSICXML("application/vnd.recordare.musicxml+xml", "musicxml", "musicxml"), CRYPTONOTE("application/vnd.rig.cryptonote", "cryptonote", "cryptonote"), COD("application/vnd.rim.cod", "cod", "cod"), RM("application/vnd.rn-realmedia", "rm", "rm"), RMVB("application/vnd.rn-realmedia-vbr", "rmvb", "rmvb"), LINK66("application/vnd.route66.link66+xml", "link66", "link66"), ST("application/vnd.sailingtracker.track", "st", "st"), SEE("application/vnd.seemail", "see", "see"), SEMA("application/vnd.sema", "sema", "sema"), SEMD("application/vnd.semd", "semd", "semd"), SEMF("application/vnd.semf", "semf", "semf"), IFM("application/vnd.shana.informed.formdata", "ifm", "ifm"), ITP("application/vnd.shana.informed.formtemplate", "itp", "itp"), IIF("application/vnd.shana.informed.interchange", "iif", "iif"), IPK("application/vnd.shana.informed.package", "ipk", "ipk"), MIND_MAPPER("application/vnd.simtech-mindmapper", "mind-mapper", "twd", "twds"), MMF("application/vnd.smaf", "mmf", "mmf"), TEACHER("application/vnd.smart.teacher", "teacher", "teacher"), SOLENT("application/vnd.solent.sdkm+xml", "solent", "sdkm", "sdkd"), DXP("application/vnd.spotfire.dxp", "dxp", "dxp"), SFS("application/vnd.spotfire.sfs", "sfs", "sfs"), SDC("application/vnd.stardivision.calc", "sdc", "sdc"), SDA("application/vnd.stardivision.draw", "sda", "sda"), SDD("application/vnd.stardivision.impress", "sdd", "sdd"), SMF("application/vnd.stardivision.math", "smf", "smf"), STARDIVISION_WRITER("application/vnd.stardivision.writer", "stardivision-writer", "sdw", "vor"), STARDIVISION_WRITER_GLOBAL("application/vnd.stardivision.writer-global", "stardivision-writer-global", "sgl"), SMZIP("application/vnd.stepmania.package", "smzip", "smzip"), SM("application/vnd.stepmania.stepchart", "sm", "sm"), SXC("application/vnd.sun.xml.calc", "sxc", "sxc"), STC("application/vnd.sun.xml.calc.template", "stc", "stc"), SXD("application/vnd.sun.xml.draw", "sxd", "sxd"), STD("application/vnd.sun.xml.draw.template", "std", "std"), SXI("application/vnd.sun.xml.impress", "sxi", "sxi"), STI("application/vnd.sun.xml.impress.template", "sti", "sti"), SXM("application/vnd.sun.xml.math", "sxm", "sxm"), SXW("application/vnd.sun.xml.writer", "sxw", "sxw"), SXG("application/vnd.sun.xml.writer.global", "sxg", "sxg"), STW("application/vnd.sun.xml.writer.template", "stw", "stw"), SUS_CALENDAR("application/vnd.sus-calendar", "sus-calendar", "sus", "susp"), SVD("application/vnd.svd", "svd", "svd"), SYMBIAN("application/vnd.symbian.install", "symbian", "sis", "sisx"), XSM("application/vnd.syncml+xml", "xsm", "xsm"), BDM("application/vnd.syncml.dm+wbxml", "bdm", "bdm"), XDM("application/vnd.syncml.dm+xml", "xdm", "xdm"), TAO("application/vnd.tao.intent-module-archive", "tao", "tao"), TCPDUMP("application/vnd.tcpdump.pcap", "tcpdump", "pcap", "cap", "dmp"), TMO("application/vnd.tmobile-livetv", "tmo", "tmo"), TPT("application/vnd.trid.tpt", "tpt", "tpt"), MXS("application/vnd.triscape.mxs", "mxs", "mxs"), TRA("application/vnd.trueapp", "tra", "tra"), UFDL("application/vnd.ufdl", "ufdl", "ufd", "ufdl"), UTZ("application/vnd.uiq.theme", "utz", "utz"), UMJ("application/vnd.umajin", "umj", "umj"), UNITYWEB("application/vnd.unity", "unityweb", "unityweb"), UOML("application/vnd.uoml+xml", "uoml", "uoml"), VCX("application/vnd.vcx", "vcx", "vcx"), VISIO("application/vnd.visio", "visio", "vsd", "vst", "vss", "vsw"), VIS("application/vnd.visionary", "vis", "vis"), VSF("application/vnd.vsf", "vsf", "vsf"), WBXML("application/vnd.wap.wbxml", "wbxml", "wbxml"), WMLC("application/vnd.wap.wmlc", "wmlc", "wmlc"), WMLSC("application/vnd.wap.wmlscriptc", "wmlsc", "wmlsc"), WTB("application/vnd.webturbo", "wtb", "wtb"), NBP("application/vnd.wolfram.player", "nbp", "nbp"), WPD("application/vnd.wordperfect", "wpd", "wpd"), WQD("application/vnd.wqd", "wqd", "wqd"), STF("application/vnd.wt.stf", "stf", "stf"), XAR("application/vnd.xara", "xar", "xar"), XFDL("application/vnd.xfdl", "xfdl", "xfdl"), HVD("application/vnd.yamaha.hv-dic", "hvd", "hvd"), HVS("application/vnd.yamaha.hv-script", "hvs", "hvs"), HVP("application/vnd.yamaha.hv-voice", "hvp", "hvp"), OSF("application/vnd.yamaha.openscoreformat", "osf", "osf"), OSFPVG("application/vnd.yamaha.openscoreformat.osfpvg+xml", "osfpvg", "osfpvg"), SAF("application/vnd.yamaha.smaf-audio", "saf", "saf"), SPF("application/vnd.yamaha.smaf-phrase", "spf", "spf"), CMP("application/vnd.yellowriver-custom-menu", "cmp", "cmp"), ZUL("application/vnd.zul", "zul", "zir", "zirz"), ZAZ("application/vnd.zzazz.deck+xml", "zaz", "zaz"), VXML("application/voicexml+xml", "vxml", "vxml"), WGT("application/widget", "wgt", "wgt"), HLP("application/winhlp", "hlp", "hlp"), WSDL("application/wsdl+xml", "wsdl", "wsdl"), WSPOLICY("application/wspolicy+xml", "wspolicy", "wspolicy"), SEVEN_Z("application/x-7z-compressed", "7z", "7z"), ABW("application/x-abiword", "abw", "abw"), ACE("application/x-ace-compressed", "ace", "ace"), DMG("application/x-apple-diskimage", "dmg", "dmg"), AUTHORWARE("application/x-authorware-bin", "authorware", "aab", "x32", "u32", "vox"), AAM("application/x-authorware-map", "aam", "aam"), AAS("application/x-authorware-seg", "aas", "aas"), BCPIO("application/x-bcpio", "bcpio", "bcpio"), BLORB("application/x-blorb", "blb blorb", "blb blorb"), BZ("application/x-bzip", "bz", "bz"), CBR("application/x-cbr", "cbr", "cbr", "cba", "cbt", "cbz", "cb7"), VCD("application/x-cdlink", "vcd", "vcd"), CFS("application/x-cfs-compressed", "cfs", "cfs"), CHAT("application/x-chat", "chat", "chat"), PGN("application/x-chess-pgn", "pgn", "pgn"), NSC("application/x-conference", "nsc", "nsc"), CSH("application/x-csh", "csh", "csh"), DGC("application/x-dgc-compressed", "dgc", "dgc"), X_DIRCTOR("application/x-director", "x-director", "dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"), WAD("application/x-doom", "wad", "wad"), NCX("application/x-dtbncx+xml", "ncx", "ncx"), DTB("application/x-dtbook+xml", "dtb", "dtb"), RES("application/x-dtbresource+xml", "res", "res"), EVY("application/x-envoy", "evy", "evy"), EVA("application/x-eva", "eva", "eva"), BDF("application/x-font-bdf", "bdf", "bdf"), GSF("application/x-font-ghostscript", "gsf", "gsf"), PSF("application/x-font-linux-psf", "psf", "psf"), OTF("application/x-font-otf", "otf", "otf"), PCF("application/x-font-pcf", "pcf", "pcf"), SNF("application/x-font-snf", "snf", "snf"), FONT_TTF("application/x-font-ttf", "font-ttf", "ttf", "ttc"), FONT_TYPE1("application/x-font-type1", "font-type1", "pfa", "pfb", "pfm", "afm"), WOFF("application/x-font-woff", "woff", "woff"), SPL("application/x-futuresplash", "spl", "spl"), GCA("application/x-gca-compressed", "gca", "gca"), ULX("application/x-glulx", "ulx", "ulx"), GRAMPS("application/x-gramps-xml", "gramps", "gramps"), GTAR("application/x-gtar", "gtar", "gtar"), HDF("application/x-hdf", "hdf", "hdf"), INSTALL("application/x-install-instructions", "install", "install"), ISO("application/x-iso9660-image", "iso", "iso"), JNLP("application/x-java-jnlp-file", "jnlp", "jnlp"), LATEX("application/x-latex", "latex", "latex"), MIE("application/x-mie", "mie", "mie"), MOBIPOCKET_EBOOK("application/x-mobipocket-ebook", "mobipocket-ebook", "prc", "mobi"), APPLICATION("application/x-ms-application", "application", "application"), LNK("application/x-ms-shortcut", "lnk", "lnk"), WMD("application/x-ms-wmd", "wmd", "wmd"), WMZ("application/x-ms-wmz", "wmz", "wmz"), XBAP("application/x-ms-xbap", "xbap", "xbap"), MDB("application/x-msaccess", "mdb", "mdb"), OBD("application/x-msbinder", "obd", "obd"), CRD("application/x-mscardfile", "crd", "crd"), CLP("application/x-msclip", "clp", "clp"), MICROSOFT_MONEY("application/x-msmoney", "money", "mny"), PUB("application/x-mspublisher", "pub", "pub"), SCD("application/x-msschedule", "scd", "scd"), TRM("application/x-msterminal", "trm", "trm"), MICROSOFT_WRITE("application/x-mswrite", "write", "wri"), NETCDF("application/x-netcdf", "netcdf", "nc", "cdf"), NZB("application/x-nzb", "nzb", "nzb"), PKCS12("application/x-pkcs12", "pkcs12", "p12", "pfx"), PKCS7_CERTIFICATES("application/x-pkcs7-certificates", "pkcs7-certificates", "p7b", "spc"), P7R("application/x-pkcs7-certreqresp", "p7r", "p7r"), RIS("application/x-research-info-systems", "ris", "ris"), SH("application/x-sh", "sh", "sh"), SHAR("application/x-shar", "shar", "shar"), SWF("application/x-shockwave-flash", "swf", "swf"), XAP("application/x-silverlight-app", "xap", "xap"), SQL("application/x-sql", "sql", "sql"), SIT("application/x-stuffit", "sit", "sit"), SITX("application/x-stuffitx", "sitx", "sitx"), SRT("application/x-subrip", "srt", "srt"), SV4CPIO("application/x-sv4cpio", "sv4cpio", "sv4cpio"), SV4CRC("application/x-sv4crc", "sv4crc", "sv4crc"), T3("application/x-t3vm-image", "t3", "t3"), GAM("application/x-tads", "gam", "gam"), TCL("application/x-tcl", "tcl", "tcl"), TFM("application/x-tex-tfm", "tfm", "tfm"), OBJ("application/x-tgif", "obj", "obj"), USTAR("application/x-ustar", "ustar", "ustar"), SRC("application/x-wais-source", "src", "src"), X509_CA_CERT("application/x-x509-ca-cert", "x509-ca-cert", "der", "crt"), XFIG("application/x-xfig", "xfig", "fig"), XLIFF("application/x-xliff+xml", "xliff", "xlf"), XP_INSTALL("application/x-xpinstall", "xp-install", "xpi"), XZ("application/x-xz", "xz", "xz"), ZMACHINE("application/x-zmachine", "zmachine", "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"), XAML("application/xaml+xml", "xaml", "xaml"), XDF("application/xcap-diff+xml", "xdf", "xdf"), XENC("application/xenc+xml", "xenc", "xenc"), XHTML("application/xhtml+xml", "xhtml", "xhtml", "xht"), DTD("application/xml-dtd", "dtd", "dtd"), XOP("application/xop+xml", "xop", "xop"), XPL("application/xproc+xml", "xpl", "xpl"), XSLT("application/xslt+xml", "xslt", "xslt"), XSPF("application/xspf+xml", "xspf", "xspf"), XV("application/xv+xml", "xv", "mxml", "xhvml", "xvml", "xvm"), YANG("application/yang", "yang", "yang"), YIN("application/yin+xml", "yin", "yin"), ADP("audio/adpcm", "adp", "adp"), SND("audio/basic", "audio-basic", "au", "snd"), S3M("audio/s3m", "s3m", "s3m"), SIL("audio/silk", "silk", "sil"), DECE_AUDIO("audio/vnd.dece.audio", "dece-audio", "uva", "uvva"), EOL("audio/vnd.digital-winds", "eol", "eol"), DRA("audio/vnd.dra", "dra", "dra"), DTS("audio/vnd.dts", "dts", "dts"), DTSHD("audio/vnd.dts.hd", "dtshd", "dtshd"), LVP("audio/vnd.lucent.voice", "lvp", "lvp"), PYA("audio/vnd.ms-playready.media.pya", "pya", "pya"), ECELP4800("audio/vnd.nuera.ecelp4800", "ecelp4800", "ecelp4800"), ECELP7470("audio/vnd.nuera.ecelp7470", "ecelp7470", "ecelp7470"), ECELP9600("audio/vnd.nuera.ecelp9600", "ecelp9600", "ecelp9600"), RIP("audio/vnd.rip", "rip", "rip"), WEBA("audio/webm", "weba", "weba"), AAC("audio/x-aac", "aac", "aac"), CAF("audio/x-caf", "caf", "caf"), FLAC("audio/x-flac", "flac", "flac"), MKA("audio/x-matroska", "mka", "mka"), M3U("audio/x-mpegurl", "m3u", "m3u"), WAX("audio/x-ms-wax", "wax", "wax"), WMA("audio/x-ms-wma", "wma", "wma"), RMP("audio/x-pn-realaudio-plugin", "rmp", "rmp"), XM("audio/xm", "xm", "xm"), CDX("chemical/x-cdx", "cdx", "cdx"), CIF("chemical/x-cif", "cif", "cif"), CMDF("chemical/x-cmdf", "cmdf", "cmdf"), CML("chemical/x-cml", "cml", "cml"), CSML("chemical/x-csml", "csml", "csml"), XYZ("chemical/x-xyz", "xyz", "xyz"), CGM("image/cgm", "cgm", "cgm"), G3("image/g3fax", "g3", "g3"), IEF("image/ief", "ief", "ief"), KTX("image/ktx", "ktx", "ktx"), BTIF("image/prs.btif", "btif", "btif"), SGI("image/sgi", "sgi", "sgi"), PSD("image/vnd.adobe.photoshop", "psd", "psd"), DECE_GRAPHIC("image/vnd.dece.graphic", "dece-graphic", "uvi", "uvvi", "uvg", "uvvg"), SUB("image/vnd.dvb.subtitle", "sub", "sub"), DJVU("image/vnd.djvu", "djvu", "djvu", "djv"), DWG("image/vnd.dwg", "dwg", "dwg"), DXF("image/vnd.dxf", "dxf", "dxf"), FBS("image/vnd.fastbidsheet", "fbs", "fbs"), FPX("image/vnd.fpx", "fpx", "fpx"), FST("image/vnd.fst", "fst", "fst"), MMR("image/vnd.fujixerox.edmics-mmr", "mmr", "mmr"), RLC("image/vnd.fujixerox.edmics-rlc", "rlc", "rlc"), MDI("image/vnd.ms-modi", "mdi", "mdi"), WDP("image/vnd.ms-photo", "wdp", "wdp"), NPX("image/vnd.net-fpx", "npx", "npx"), WBMP("image/vnd.wap.wbmp", "wbmp", "wbmp"), XIF("image/vnd.xiff", "xif", "xif"), WEBP("image/webp", "webp", "webp"), RAS("image/x-cmu-raster", "ras", "ras"), CMX("image/x-cmx", "cmx", "cmx"), FREEHAND("image/x-freehand", "freehand", "fh", "fhc", "fh4", "fh5", "fh7"), SID("image/x-mrsid-image", "sid", "sid"), PCX("image/x-pcx", "pcx", "pcx"), PICT("image/x-pict", "pict", "pic", "pct"), PNM("image/x-portable-anymap", "pnm", "pnm"), RGB("image/x-rgb", "rgb", "rgb"), TGA("image/x-tga", "tga", "tga"), XBM("image/x-xbitmap", "xbm", "xbm"), XPM("image/x-xpixmap", "xpm", "xpm"), XWD("image/x-xwindowdump", "xwd", "xwd"), MIME("message/rfc822", "mime", "eml", "mime"), IGES("model/iges", "iges", "igs", "iges"), MESH("model/mesh", "mesh", "msh", "mesh", "silo"), DAE("model/vnd.collada+xml", "dae", "dae"), DWF("model/vnd.dwf", "dwf", "dwf"), GDL("model/vnd.gdl", "gdl", "gdl"), GTW("model/vnd.gtw", "gtw", "gtw"), MTS("model/vnd.mts", "mts", "mts"), VTU("model/vnd.vtu", "vtu", "vtu"), X3D_BINARY("model/x3d+binary", "x3d-binary", "x3db", "x3dbz"), X3D_VRML("model/x3d+vrml", "x3d-vrml", "x3dv", "x3dvz"), X3D_XML("model/x3d+xml", "x3d-xml", "x3d", "x3dz"), CALENDAR("text/calendar", "calendar", "ics", "ifb"), CSS("text/css", "css", "css"), CSV("text/csv", "csv", "csv"), N3("text/n3", "n3", "n3"), TEXT("text/plain", "text", "txt", "text"), DSC("text/prs.lines.tag", "dsc", "dsc"), RTX("text/richtext", "rtx", "rtx"), SGML("text/sgml", "sgml", "sgml", "sgm"), TSV("text/tab-separated-values", "tsv", "tsv"), TTL("text/turtle", "ttl", "ttl"), CURL("text/vnd.curl", "curl", "curl"), DCURL("text/vnd.curl.dcurl", "dcurl", "dcurl"), SCURL("text/vnd.curl.scurl", "scurl", "scurl"), MCURL("text/vnd.curl.mcurl", "mcurl", "mcurl"), DVB_SUBTITLE("text/vnd.dvb.subtitle", "dvb-subtitle", "sub"), FLY("text/vnd.fly", "fly", "fly"), FLX("text/vnd.fmi.flexstor", "flx", "flx"), GV("text/vnd.graphviz", "gv", "gv"), SPOT("text/vnd.in3d.spot", "spot", "spot"), JAD("text/vnd.sun.j2me.app-descriptor", "jad", "jad"), WML("text/vnd.wap.wml", "wml", "wml"), WMLS("text/vnd.wap.wmlscript", "wmls", "wmls"), ASSEMBLY("text/x-asm", "assembly", "s asm"), C_SOURCE("text/x-c", "c-source", "c", "cc", "cxx", "cpp", "h", "hh", "dic"), JAVA("text/x-java-source", "java", "java"), OPML("text/x-opml", "opml", "opml"), PASCAL("text/x-pascal", "pascal", "p", "pas"), NFO("text/x-nfo", "nfo", "nfo"), ETX("text/x-setext", "etx", "etx"), SFV("text/x-sfv", "sfv", "sfv"), UU("text/x-uuencode", "uu", "uu"), VCS("text/x-vcalendar", "vcs", "vcs"), VCF("text/x-vcard", "vcf", "vcf"), THREE_GP("video/3gpp", "3gp", "3gp"), THREE_G2("video/3gpp2", "3g2", "3g2"), H261("video/h261", "h261", "h261"), H263("video/h263", "h263", "h263"), JPGV("video/jpeg", "jpgv", "jpgv"), JPM("video/jpm", "jpm", "jpm", "jpgm"), MJ2("video/mj2", "mj2", "mj2", "mjp2"), MP4("video/mp4", "mp4 mp4v mpg4", "mp4", "mp4v", "mpg4"), OGV("video/ogg", "ogv", "ogv"), DECE_HD("video/vnd.dece.hd", "dece-hd", "uvh", "uvvh"), DECE_MOBILE("video/vnd.dece.mobile", "dece-mobile", "uvm", "uvvm"), DECE_PD("video/vnd.dece.pd", "dece-pd", "uvp", "uvvp"), DECE_SD("video/vnd.dece.sd", "dece-sd", "uvs", "uvvs"), DECE_VIDEO("video/vnd.dece.video", "dece-video", "uvv", "uvvv"), DVB("video/vnd.dvb.file", "dvb", "dvb"), FVT("video/vnd.fvt", "fvt", "fvt"), MPEG_URL("video/vnd.mpegurl", "mpeg-url", "mxu", "m4u"), PYV("video/vnd.ms-playready.media.pyv", "pyv", "pyv"), UVVU_MP4("video/vnd.uvvu.mp4", "uvvu-mp4", "uvu", "uvvu"), VIV("video/vnd.vivo", "viv", "viv"), WEBM("video/webm", "webm", "webm"), F4V("video/x-f4v", "f4v", "f4v"), FLI("video/x-fli", "fli", "fli"), FLV("video/x-flv", "flv", "flv"), M4V("video/x-m4v", "m4v", "m4v"), MATROSKA("video/x-matroska", "matroska", "mkv", "mk3d", "mks"), MICROSOFT_ASF("video/x-ms-asf", "asf", "asf", "asx"), VOB("video/x-ms-vob", "vob", "vob"), WM("video/x-ms-wm", "wm", "wm"), WMV("video/x-ms-wmv", "wmv", "wmv"), WMX("video/x-ms-wmx", "wmx", "wmx"), WVX("video/x-ms-wvx", "wvx", "wvx"), MOVIE("video/x-sgi-movie", "movie", "movie"), SMV("video/x-smv", "smv", "smv"), ICE("x-conference/x-cooltalk", "ice", "ice"), /** default if no specific match to the mime-type */ OTHER("application/octet-stream", "other"), // end ; private final static Map<String, ContentType> mimeTypeMap = new HashMap<String, ContentType>(); private final static Map<String, ContentType> fileExtensionMap = new HashMap<String, ContentType>(); static { for (ContentType type : values()) { if (type.mimeType != null) { mimeTypeMap.put(type.mimeType.toLowerCase(), type); } if (type.fileExtensions != null) { for (String fileExtension : type.fileExtensions) { fileExtensionMap.put(fileExtension, type); } } } } private final String mimeType; private final String simpleName; private final String[] fileExtensions; private ContentType(String mimeType, String simpleName, String... fileExtensions) { this.mimeType = mimeType; this.simpleName = simpleName; this.fileExtensions = fileExtensions; } /** * Get simple name of the type. */ public String getSimpleName() { return simpleName; } /** * Return the type associated with the mime-type string or {@link #OTHER} if not found. */ public static ContentType fromMimeType(String mimeType) { // NOTE: mimeType can be null if (mimeType != null) { mimeType = mimeType.toLowerCase(); } ContentType type = mimeTypeMap.get(mimeType); if (type == null) { return OTHER; } else { return type; } } /** * Return the type associated with the file-extension string or {@link #OTHER} if not found. */ public static ContentType fromFileExtension(String fileExtension) { // NOTE: mimeType can be null ContentType type = fileExtensionMap.get(fileExtension.toLowerCase()); if (type == null) { return OTHER; } else { return type; } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaDocumentService; import com.kaltura.client.services.KalturaEdgeServerService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaServerService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaXInternalService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaSystemPartnerService; import com.kaltura.client.services.KalturaEntryAdminService; import com.kaltura.client.services.KalturaUiConfAdminService; import com.kaltura.client.services.KalturaReportAdminService; import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:15-10-26"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaDocumentService documentService; public KalturaDocumentService getDocumentService() { if(this.documentService == null) this.documentService = new KalturaDocumentService(this); return this.documentService; } protected KalturaEdgeServerService edgeServerService; public KalturaEdgeServerService getEdgeServerService() { if(this.edgeServerService == null) this.edgeServerService = new KalturaEdgeServerService(this); return this.edgeServerService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaServerService mediaServerService; public KalturaMediaServerService getMediaServerService() { if(this.mediaServerService == null) this.mediaServerService = new KalturaMediaServerService(this); return this.mediaServerService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaXInternalService xInternalService; public KalturaXInternalService getXInternalService() { if(this.xInternalService == null) this.xInternalService = new KalturaXInternalService(this); return this.xInternalService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaSystemPartnerService systemPartnerService; public KalturaSystemPartnerService getSystemPartnerService() { if(this.systemPartnerService == null) this.systemPartnerService = new KalturaSystemPartnerService(this); return this.systemPartnerService; } protected KalturaEntryAdminService entryAdminService; public KalturaEntryAdminService getEntryAdminService() { if(this.entryAdminService == null) this.entryAdminService = new KalturaEntryAdminService(this); return this.entryAdminService; } protected KalturaUiConfAdminService uiConfAdminService; public KalturaUiConfAdminService getUiConfAdminService() { if(this.uiConfAdminService == null) this.uiConfAdminService = new KalturaUiConfAdminService(this); return this.uiConfAdminService; } protected KalturaReportAdminService reportAdminService; public KalturaReportAdminService getReportAdminService() { if(this.reportAdminService == null) this.reportAdminService = new KalturaReportAdminService(this); return this.reportAdminService; } protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService; public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() { if(this.kalturaInternalToolsSystemHelperService == null) this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this); return this.kalturaInternalToolsSystemHelperService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-08-30"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package io.branch.referral; import android.content.Context; import io.branch.referral.Defines.PreinstallKey; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; class BranchPreinstall { private String SYSTEM_PROPERTIES_CLASS_KEY = "android.os.SystemProperties"; private String BRANCH_PREINSTALL_PROP_KEY = "io.branch.preinstall.apps.path"; public void getPreinstallSystemData(Context context) { // check if the SystemProperties has the branch file path added String branchFilePath = checkForBranchPreinstallInSystem(); if (branchFilePath != null) { // after getting the file path get the file contents JSONObject branchFileContentJson = null; branchFileContentJson = readBranchFile(branchFilePath); if (branchFileContentJson != null) { // check if the current app package exists in the json Iterator<String> keys = branchFileContentJson.keys(); while (keys.hasNext()) { String key = keys.next(); try { if (key.equals("apps") && branchFileContentJson .get(key) instanceof JSONObject) { if (branchFileContentJson.getJSONObject(key) .get(SystemObserver.getPackageName(context)) != null) { JSONObject branchPreinstallData = branchFileContentJson .getJSONObject(key) .getJSONObject(SystemObserver.getPackageName(context)); // find the preinstalls keys and any custom data Iterator<String> preinstallDataKeys = branchPreinstallData.keys(); while (preinstallDataKeys.hasNext()) { String datakey = preinstallDataKeys.next(); if (datakey.equals(PreinstallKey.campaign.getKey())) { Branch.getInstance() .setPreinstallCampaign( branchPreinstallData.get(datakey) .toString()); } else if (datakey.equals(PreinstallKey.partner.getKey())) { Branch.getInstance() .setPreinstallPartner( branchPreinstallData.get(datakey) .toString()); } else { Branch.getInstance().setRequestMetadata(datakey, branchPreinstallData.get(datakey).toString()); } } } } } catch (JSONException e) { e.printStackTrace(); } } } } } private String checkForBranchPreinstallInSystem() { String path = null; try { path = (String) Class.forName(SYSTEM_PROPERTIES_CLASS_KEY) .getMethod("get", String.class).invoke(null, BRANCH_PREINSTALL_PROP_KEY); } catch (Exception e) { e.printStackTrace(); } return path; } private JSONObject readBranchFile(String branchFilePath) { JSONObject branchFileContentJson = null; File yourFile = new File(branchFilePath); StringBuilder branchFileContent = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(yourFile)); String line; while ((line = br.readLine()) != null) { branchFileContent.append(line); } br.close(); } catch (IOException ignore) { // the file does not exists } try { branchFileContentJson = new JSONObject(branchFileContent.toString().trim()); } catch (JSONException e) { e.printStackTrace(); } return branchFileContentJson; } }
package com.pyramidacceptors.pub; import com.pyramidacceptors.ptalk.api.PyramidAcceptor; import com.pyramidacceptors.ptalk.api.PyramidDeviceException; import com.pyramidacceptors.ptalk.api.PyramidPort; import com.pyramidacceptors.ptalk.api.event.*; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Point; import java.awt.Toolkit; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JComboBox; import javax.swing.JList; /** * * @author Cory Todd <cory@pyramidacceptors.com> */ public class TestGUI extends javax.swing.JFrame implements PTalkEventListener { private final String REV = "1.2.0"; private PyramidAcceptor acceptor; private static DefaultListModel data; private final JList rawList; private JComboBox portList; private final ButtonGroup bg; /** * Creates new form TestGUI */ public TestGUI() { initComponents(); // Title the application this.setTitle("PTalk Test Harness - Rev: " + REV); this.setVisible(true); // Center the JFrame Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int x = getWidth() / 2; int y = getHeight() / 2; Point pt = new Point((int) (dim.getWidth() / 2 - x), (int) (dim.getHeight() / 2 - y)); this.setLocation(pt); // Register a listener for data received from the target device // Create a new list for data rx and bind it to a new jList data = new DefaultListModel(); rawList = new JList(data); GridBagConstraints gbc = new GridBagConstraints(); this.listPanel.add(rawList, gbc); // Add the radio buttons to the radio button group bg = new ButtonGroup(); bg.add(this.rdoAccepting); bg.add(this.rdoIdle); bg.add(this.rdoEscrowed); bg.add(this.rdoStacking); // Finally, get all available ports getPorts(); } private void getPorts() { // If we don't have a combobox, create one if(portList == null) { portList = new JComboBox(); this.portPanel.add(portList); } // Clear the list and add all accessible ports this.portList.removeAllItems(); for(String s : PyramidPort.getPortList()) { this.portList.addItem(s); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); btnConnect = new javax.swing.JButton(); btnDisconnect = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); lblStatus = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); btnExit = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); listPanel = new javax.swing.JPanel(); portPanel = new javax.swing.JPanel(); btnRescan = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); rdoIdle = new javax.swing.JRadioButton(); rdoAccepting = new javax.swing.JRadioButton(); rdoEscrowed = new javax.swing.JRadioButton(); rdoStacking = new javax.swing.JRadioButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jLabel1.setText("Port"); jLabel2.setText("Raw Data"); btnConnect.setText("Connect"); btnConnect.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnConnectMouseClicked(evt); } }); btnDisconnect.setText("Disconnect"); btnDisconnect.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnDisconnectMouseClicked(evt); } }); jLabel3.setText("Status"); btnExit.setText("Exit"); btnExit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnExitMouseClicked(evt); } }); listPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); listPanel.setAutoscrolls(true); listPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jScrollPane1.setViewportView(listPanel); btnRescan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reload_alt_18x21.png"))); // NOI18N btnRescan.setToolTipText("Rescan Ports"); btnRescan.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnRescanMouseClicked(evt); } }); rdoIdle.setText("Idle"); rdoAccepting.setText("Accepting"); rdoEscrowed.setText("Escrowed"); rdoStacking.setText("Stacking"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rdoIdle) .addComponent(rdoAccepting) .addComponent(rdoEscrowed) .addComponent(rdoStacking)) .addContainerGap(21, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(rdoIdle) .addGap(18, 18, 18) .addComponent(rdoAccepting) .addGap(18, 18, 18) .addComponent(rdoEscrowed) .addGap(18, 18, 18) .addComponent(rdoStacking) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lblStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(portPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(btnRescan))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnConnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnDisconnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(portPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnRescan) .addComponent(btnConnect) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnDisconnect) .addComponent(lblStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addGap(5, 5, 5) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnExit) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnConnectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnConnectMouseClicked String newPortName = this.portList.getSelectedItem().toString(); if(acceptor != null && acceptor.getPortName().equals(newPortName) && acceptor.isConnected()) { lblStatus.setText( String.format("Device is connected port %s", acceptor.getPortName())); } else if(acceptor != null && !acceptor.isConnected()) { acceptor.connect(); lblStatus.setText( String.format("Device is connected port %s", acceptor.getPortName())); }else { try { // Instantiate a new acceptor with this port acceptor = PyramidAcceptor.valueOfRS232(newPortName); acceptor.connect(); if(acceptor.isConnected()) { lblStatus.setText( String.format("Connected on port %s", acceptor.getPortName())); acceptor.addChangeListener(this); } else { lblStatus.setText( String.format("Failed to connect port %s", acceptor.getPortName())); } } catch (PyramidDeviceException ex) { Logger.getLogger(TestGUI.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_btnConnectMouseClicked private void btnExitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnExitMouseClicked try { if(acceptor != null && acceptor.isConnected()) acceptor.disconnect(); } catch(Exception ex){ lblStatus.setText("Error"); } finally { this.dispose(); } }//GEN-LAST:event_btnExitMouseClicked private void btnDisconnectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnDisconnectMouseClicked if(acceptor != null && acceptor.isConnected()) { acceptor.disconnect(); String name = acceptor.getPortName(); lblStatus.setText(String.format("Disconnected device from port %s", name)); } else { lblStatus.setText("Not connected to a device"); boolean n = false; } }//GEN-LAST:event_btnDisconnectMouseClicked private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing btnExitMouseClicked(null); }//GEN-LAST:event_formWindowClosing private void btnRescanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRescanMouseClicked this.getPorts(); }//GEN-LAST:event_btnRescanMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnConnect; private javax.swing.JButton btnDisconnect; private javax.swing.JButton btnExit; private javax.swing.JButton btnRescan; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JLabel lblStatus; private javax.swing.JPanel listPanel; private javax.swing.JPanel portPanel; private javax.swing.JRadioButton rdoAccepting; private javax.swing.JRadioButton rdoEscrowed; private javax.swing.JRadioButton rdoIdle; private javax.swing.JRadioButton rdoStacking; // End of variables declaration//GEN-END:variables @Override public void changeEventReceived(PTalkEvent evt) { // There can only be one state at a time if(evt instanceof IdlingEvent) this.rdoIdle.setSelected(true); else if (evt instanceof AcceptingEvent) this.rdoAccepting.setSelected(true); else if (evt instanceof EscrowedEvent) this.rdoEscrowed.setSelected(true); else if (evt instanceof StackingEvent) this.rdoStacking.setSelected(true); else if (evt instanceof CreditEvent) addToList(evt.getFriendlyString()); // Log them all the things String resp = getEventString(evt); Logger.getLogger(TestGUI.class.getName()).log(Level.INFO, String.format("Event: %s", resp)); addToList(resp); } private String lastMessage = ""; void addToList(String message) { // Only add non-empty, non-repeat messages if(message instanceof String && !message.equals("") && !lastMessage.equals(message)) data.addElement(message); int sz = data.size(); rawList.ensureIndexIsVisible(sz-1); lastMessage = message; } /** * Returns the string name of the event. Due to localization issues * we handle this in the client code and not the core API. * @param evt * @return */ private String getEventString(PTalkEvent evt) { if(evt instanceof CasseteMissingEvent) return "Cashbox Removed"; if(evt instanceof BillJammedEvent) return "Bill Jam"; if(evt instanceof ReturnedEvent) return "Bill Returned"; if(evt instanceof BillRejectedEvent) return "Bill Rejected"; if(evt instanceof FailureEvent) return "Device Failure"; if(evt instanceof PowerUpEvent) return "Powered Up"; if(evt instanceof StackedEvent) return "Bill Stacked"; if(evt instanceof StackerFullEvent) return "Stacker Full"; if(evt instanceof InvalidMessageEvent) return "Invalid Message"; if(evt instanceof CheatedEvent) return "Cheat Detected"; if(evt instanceof IdlingEvent) return "Idling"; if (evt instanceof AcceptingEvent) return "Accepting"; if (evt instanceof EscrowedEvent) return "Escrowed"; if (evt instanceof StackingEvent) return "Stacking"; if (evt instanceof CreditEvent) return "Credited"; return ""; } }
package com.schedule.demo.jobs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import com.schedule.demo.dao.ScheduleLogDao; import com.schedule.demo.vo.ScheduleLog; public class SimpleJob implements org.quartz.Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String appUrl = jobDataMap.getString("appUrl"); Long jobId = jobDataMap.getLong("jobId"); boolean appCallStatus = false; String resCode = ""; String successfulCode = jobDataMap.getString("successfulCode"); ScheduleLogDao scheduleLogDao = (ScheduleLogDao) jobDataMap.get("scheduleLogDao"); try { resCode = submitGetRequest(successfulCode, appUrl); if (successfulCode != null && successfulCode.equals(resCode)) { appCallStatus = true; } else { appCallStatus = false; } } catch (Exception e) { appCallStatus = false; e.printStackTrace(); } finally { //add schedule log try{ ScheduleLog scheduleLog=new ScheduleLog(); scheduleLog.setJobId(jobId); scheduleLog.setCallStatus(appCallStatus); scheduleLogDao.insert(scheduleLog); }catch(Exception e){ e.printStackTrace(); } // all db to update job running status System.out.println("Job running:" + appCallStatus); } } private String submitGetRequest(String expectedResponse, String appUrl) throws Exception { String resBody = ""; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(appUrl); CloseableHttpResponse response1 = httpclient.execute(httpGet); try { System.out.println(new Date() + ":Calling:" + appUrl + "," + response1.getStatusLine()); resBody = getResponseBodyAsString(response1); } catch (IOException e) { e.printStackTrace(); } finally { try { response1.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resBody; } private boolean submitPostRequest(String expectedResponse, String appUrl) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(appUrl); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); } return true; } public static String getResponseBodyAsString(HttpResponse response) throws Exception { StringBuilder sb = new StringBuilder(); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { httpEntity = new BufferedHttpEntity(httpEntity); InputStream is = httpEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String str; while ((str = br.readLine()) != null) { sb.append(str); } is.close(); } return sb.toString(); } }
package com.sepoe.wbitdd.pos; /** * Class to provide the price of an item with barcode. * * @author lumiha * @since 08/05/15. */ public class PointOfSale { private String barcodePattern = "\\d{12}"; private final ItemRepository itemRepository; private final OutputDevice outputDevice; public PointOfSale(final ItemRepository itemRepository, final OutputDevice outputDevice) { if (itemRepository == null) throw new IllegalArgumentException("Missing item repository"); if (outputDevice == null) throw new IllegalArgumentException("Missing output device"); this.itemRepository = itemRepository; this.outputDevice = outputDevice; } public void onBarcode(final String barcode) { try { if (isInvalidBarcode(barcode)) { outputDevice.writeItemPrice(String.format("Invalid barcode '%s'", barcode)); } else { String output; try { final String trimmedBarcode = barcode.trim(); final Double price = itemRepository.lookupItem(trimmedBarcode); output = generateOutput(trimmedBarcode, price); } catch (Exception e) { output = String.format("ERROR '%s'", e.getMessage()); } outputDevice.writeItemPrice(output); } } catch (Throwable throwable){ // in case the output itself throws an exception we cannot write the error to the output // which would cause and endless loop. throwable.printStackTrace(); } } private boolean isInvalidBarcode(final String barcode) { return barcode == null || barcode.isEmpty() || !barcode.trim().matches(barcodePattern); } private String generateOutput(final String barcode, final Double price) { return (price == null) ? String.format("No item for barcode %s", barcode) : String.format("$%.2f", price); } }
package com.socrata.datasync; import com.google.common.net.HttpHeaders; import com.socrata.datasync.config.userpreferences.UserPreferences; import org.apache.commons.net.util.Base64; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HttpContext; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; public class HttpUtility { private CloseableHttpClient httpClient = null; private RequestConfig proxyConfig = null; private String authHeader; private String appToken; private boolean authRequired = false; private static final String datasyncVersionHeader = "X-Socrata-DataSync-Version"; private static final String appHeader = "X-App-Token"; private static final String userAgent = "datasync"; public HttpUtility() { this(null, false); } public HttpUtility(UserPreferences userPrefs, boolean useAuth) { HttpClientBuilder clientBuilder = HttpClients.custom(); if (useAuth) { authHeader = getAuthHeader(userPrefs.getUsername(), userPrefs.getPassword()); appToken = userPrefs.getAPIKey(); } authRequired = useAuth; if(userPrefs != null) { String proxyHost = userPrefs.getProxyHost(); String proxyPort = userPrefs.getProxyPort(); if (canUse(proxyHost) && canUse(proxyPort)) { HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort)); proxyConfig = RequestConfig.custom().setProxy(proxy).build(); if (canUse(userPrefs.getProxyUsername()) && canUse(userPrefs.getProxyPassword())) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(proxyHost, Integer.valueOf(proxyPort)), new UsernamePasswordCredentials(userPrefs.getProxyUsername(), userPrefs.getProxyPassword())); clientBuilder.setDefaultCredentialsProvider(credsProvider); } } } clientBuilder.setRetryHandler(datasyncDefaultHandler); clientBuilder.setKeepAliveStrategy(datasyncDefaultKeepAliveStrategy); httpClient = clientBuilder.build(); } /** * Conducts a basic get, passing the auth information in the header. * @param uri the uri from which the get will be made * @param contentType the expected contentType of the return value * @return the unproccessed query results */ public CloseableHttpResponse get(URI uri, String contentType) throws IOException { HttpGet httpGet = new HttpGet(uri); httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent); httpGet.addHeader(HttpHeaders.ACCEPT, contentType); httpGet.addHeader(datasyncVersionHeader, VersionProvider.getThisVersion()); if (proxyConfig != null) httpGet.setConfig(proxyConfig); if (authRequired) { httpGet.setHeader(appHeader, appToken); httpGet.setHeader(HttpHeaders.AUTHORIZATION, authHeader); } return httpClient.execute(httpGet); } /** * Conducts a basic post of the given entity; auth information is passed in the header. * @param uri the uri to which the entity will be posted * @param entity an entity to post * @return the unprocessed results of the post */ public CloseableHttpResponse post(URI uri, HttpEntity entity) throws IOException { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader(HttpHeaders.USER_AGENT, userAgent); httpPost.setHeader(entity.getContentType()); httpPost.addHeader(datasyncVersionHeader, VersionProvider.getThisVersion()); httpPost.setEntity(entity); if (proxyConfig != null) httpPost.setConfig(proxyConfig); if (authRequired) { httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader); httpPost.setHeader(appHeader, appToken); } return httpClient.execute(httpPost); } public void close() throws IOException { httpClient.close(); } private String getAuthHeader(String username, String password) { String auth = username + ":" + password; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII"))); return "Basic " + new String(encodedAuth); } private boolean canUse(String option) { return option != null && !option.isEmpty(); } HttpRequestRetryHandler datasyncDefaultHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // Do not retry if over max retry count if (executionCount >= 5) return false; // Do not retry calls to the github api HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); for (Header header : request.getHeaders("Host")) { if (header.getValue().contains("github")) return false; } // Do not retry calls that are not idempotent - posts in our case // currently, we make 2 types of posts: // 1) posting blobs - this is idempotent // 2) posting commit of blob ids - this is not idempotent and we need to fall back to the logic // in DeltaImporter2Publisher.commitBlobPostings boolean idempotent = !(request.getRequestLine().getUri().contains("commit")); if (idempotent) { // Retry if the request is considered idempotent double wait = Math.pow(3.5, executionCount); System.err.println("Request failed. Retrying request in " + Math.round(wait) + " seconds"); try { Thread.sleep((long) wait*1000); return true; } catch (InterruptedException e) { e.printStackTrace(); return false; } } return false; } }; ConnectionKeepAliveStrategy datasyncDefaultKeepAliveStrategy = new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { return 30 * 1000; } }; }
package com.voltvoodoo.brew; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.plexus.util.FileUtils; import org.mozilla.javascript.ErrorReporter; /** * * @goal optimize * @phase process-classes * */ public class OptimizeMojo extends AbstractMojo { /** * Javascript source directory. * * @parameter expression="${project.build.outputDirectory}" */ private File optimizeSourceDir; /** * Source tree is copied here, minified and aggregated. * * @parameter expression="${project.build.outputDirectory}" */ private File optimizeBuildDir; /** * Built modules are put here, moved from the build directory after * minification and aggregation. By default this is the same as the * output directory. * * @parameter expression="${project.build.outputDirectory}" */ private File optimizeOutputDir; /** * File name suffix for optimized modules. * * @parameter expression="-min" */ private String optimizedFileNameSuffix; /** * Used to inline i18n resources into the built file. If no locale * is specified, i18n resources will not be inlined. Only one locale * can be inlined for a build. Root bundles referenced by a build layer * will be included in a build layer regardless of locale being set. * * @parameter expression="${requirejs.locale}" default="en-us" */ private String locale = "en-us"; /** * How to optimize all the JS files in the build output directory. * Right now only the following values * are supported: * - "uglify": uses UglifyJS to minify the code. * - "closure": (default) uses Google's Closure Compiler in simple optimization * mode to minify the code. * - "closure.keepLines": Same as closure option, but keeps line returns * in the minified files. * - "none": no minification will be done. * @parameter expression="${requirejs.jsOptimizer}" default="uglify" */ private String jsOptimizer = "uglify"; /** * Allow CSS optimizations. Allowed values: * - "standard": @import inlining, comment removal and line returns. * Removing line returns may have problems in IE, depending on the type * of CSS. * - "standard.keepLines": like "standard" but keeps line returns. * - "none": skip CSS optimizations. * @parameter expression="${requirejs.cssOptimizer}" default="standard" */ private String cssOptimizer = "standard"; /** * If optimizeCss is in use, a list of of files to ignore for the @import * inlining. The value of this option should be a comma separated list * of CSS file names to ignore. The file names should match whatever * strings are used in the @import calls. * @parameter */ private List<String> cssExcludes; /** * If includeRequire is specified on a module, then import require.js from * the specified resource. * @parameter expression="${requirejs.requireUrl}" default=false */ private String requireUrl = "require.js"; /** * Inlines the text for any text! dependencies, to avoid the separate * async XMLHttpRequest calls to load those dependencies. * @parameter expression="${requirejs.inlineText}" default=true */ private boolean inlineText = true; /** * Allow "use strict"; be included in the RequireJS files. * Default is false because there are not many browsers that can properly * process and give errors on code for ES5 strict mode, * and there is a lot of legacy code that will not work in strict mode. * @parameter expression="${requirejs.useStrictJs}" default=false */ private boolean useStrictJs = false; /** * Specify build pragmas. If the source files contain comments like so: * >>excludeStart("fooExclude", pragmas.fooExclude); * >>excludeEnd("fooExclude"); * Then the comments that start with //>> are the build pragmas. * excludeStart/excludeEnd and includeStart/includeEnd work, and the * the pragmas value to the includeStart or excludeStart lines * is evaluated to see if the code between the Start and End pragma * lines should be included or excluded. * @parameter */ private Map<String, Boolean> pragmas; /** * Skip processing for pragmas. * @parameter expression="${requirejs.skipPragmas}" default=false */ private boolean skipPragmas = false; /** * If skipModuleInsertion is false, then files that do not use define() * to define modules will get a define() placeholder inserted for them * Also, require.pause/resume calls will be inserted. * Set it to true to avoid this. This is useful if you are building code that * does not use require() in the built project or in the JS files, but you * still want to use the optimization tool from RequireJS to concatenate modules * together. * @parameter default-value=false */ private boolean skipModuleInsertion = false; /** * Shorthand for specifying a single module to compile. * This will be overriden if you use the {@link #modules} parameter. * @parameter expression="${requirejs.module}" default="main" */ private String module = "main"; /** * List the modules that will be optimized. All their immediate and deep * dependencies will be included in the module's file when the build is * done. If that module or any of its dependencies includes i18n bundles, * only the root bundles will be included unless the locale: section is set above. * @parameter */ private List<Module> modules; /** * Set paths for modules. If relative paths, set relative to baseUrl above. * If a special value of "empty:" is used for the path value, then that * acts like mapping the path to an empty file. It allows the optimizer to * resolve the dependency to path, but then does not include it in the output. * Useful to map module names that are to resources on a CDN or other * http: URL when running in the browser and during an optimization that * file should be skipped because it has no dependencies. * @parameter */ private Map<String, String> paths = Collections.emptyMap(); private Map<String, List<String>> packagePaths; /** * @parameter */ private List<String> packages; private Uglify uglify; /** * If using Closure Compiler for script optimization, these config options * can be used to configure Closure Compiler. See the documentation for * Closure compiler for more information. * @parameter */ private Closure closure; /** * Same as "pragmas", but only applied once during the file save phase * of an optimization. "pragmas" are applied both during the dependency * mapping and file saving phases on an optimization. Some pragmas * should not be processed during the dependency mapping phase of an * operation, such as the pragma in the CoffeeScript loader plugin, * which wants the CoffeeScript compiler during the dependency mapping * phase, but once files are saved as plain JavaScript, the CoffeeScript * compiler is no longer needed. In that case, pragmasOnSave would be used * to exclude the compiler code during the save phase. * @parameter */ private Map<String, Boolean> pragmasOnSave; private Map<String, Boolean> has; /** * Similar to pragmasOnSave, but for has tests -- only applied during the * file save phase of optimization, where "has" is applied to both * dependency mapping and file save phases. * @parameter */ private Map<String, Boolean> hasOnSave; private String namespace; /** * If it is not a one file optimization, scan through all .js files in the * output directory for any plugin resource dependencies, and if the plugin * supports optimizing them as separate files, optimize them. Can be a * slower optimization. Only use if there are some plugins that use things * like XMLHttpRequest that do not work across domains, but the built code * will be placed on another domain. * @parameter default-value=false */ private boolean optimizeAllPluginResources; /** * Wrap any build layer in a start and end text specified by wrap. * @parameter */ private Wrap wrap; /** * Defines whether the default requirejs plugins text, order and i18n should * be copied to the working directory. * @parameter default-value=false */ private boolean providePlugins = false; public void execute() throws MojoExecutionException, MojoFailureException { try { Optimizer builder = new Optimizer(); ErrorReporter reporter = new DefaultErrorReporter(getLog(), true); builder.build( optimizeBuildDir, providePlugins, createBuildProfile(), reporter ); moveModulesToOutputDir(); } catch (RuntimeException exc) { throw exc; } catch (Exception exc) { throw new MojoExecutionException(exc.getMessage(), exc); } } public String getBaseUrl() { return optimizeSourceDir.getAbsolutePath(); } public File getDir() { return optimizeBuildDir; } public String getLocale() { return locale; } public String getRequireUrl() { return requireUrl; } public String getOptimize() { return jsOptimizer; } public String getOptimizeCss() { return cssOptimizer; } public boolean isInlineText() { return inlineText; } public boolean isUseStrict() { return useStrictJs; } public boolean isSkipPragmas() { return skipPragmas; } public Map<String, Boolean> getPragmas() { return pragmas; } public List<String> getCssImportIgnore() { return cssExcludes; } public boolean isSkipModuleInsertion() { return skipModuleInsertion; } public List<Module> getModules() { if(modules == null) { modules = new ArrayList<Module>(); modules.add( new Module(module)); } return modules; } public Map<String, String> getPaths() { return paths; } public Map<String, List<String>> getPackagePaths() { return packagePaths; } public List<String> getPackages() { return packages; } public Uglify getUglify() { return uglify; } public Closure getClosure() { return closure; } public Map<String, Boolean> getPragmasOnSave() { return pragmasOnSave; } public Map<String, Boolean> getHas() { return has; } public Map<String, Boolean> getHasOnSave() { return hasOnSave; } public String getNamespace() { return namespace; } public boolean isOptimizeAllPluginResources() { return optimizeAllPluginResources; } public Wrap getWrap() { return wrap; } @JsonIgnore public Log getLog() { return super.getLog(); } @SuppressWarnings( "rawtypes" ) @JsonIgnore public Map getPluginContext() { return super.getPluginContext(); } private File createBuildProfile() throws IOException { File profileFile = File.createTempFile( "profile", "js" ); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue( profileFile, this ); return profileFile; } private void moveModulesToOutputDir() throws IOException { File from, to; for(Module mod : getModules() ) { from = new File(optimizeBuildDir, mod.getName() + ".js"); to = new File(optimizeOutputDir, mod.getName() + optimizedFileNameSuffix + ".js"); FileUtils.copyFile( from, to ); } } }
package de.jeha.s3srv.xml; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; /** * @author jenshadlich@googlemail.com */ public class JaxbMarshaller { private static Marshaller MARSHALLER = null; private static Unmarshaller UNMARSHALLER = null; static { try { MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); } catch (JAXBException e) { throw new RuntimeException("Unable to initialize JAXB Marshaller", e); } try { UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); } } public synchronized static String marshall(Object object) throws JAXBException, IOException { StringWriter stringWriter = new StringWriter(); stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); stringWriter.append("\n"); MARSHALLER.marshal(object, stringWriter); stringWriter.close(); return stringWriter.toString(); } public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); } }
package de.prob2.ui.groovy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.scene.control.ContextMenu; import javafx.scene.control.TextArea; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; public class GroovyConsole extends TextArea { private int charCounterInLine = 0; private int currentPosInLine = 0; private static final KeyCode[] REST = {KeyCode.ESCAPE,KeyCode.SCROLL_LOCK,KeyCode.PAUSE,KeyCode.NUM_LOCK,KeyCode.INSERT,KeyCode.CONTEXT_MENU,KeyCode.CAPS}; private List<Instruction> instructions; private int posInList = -1; private GroovyInterpreter interpreter; public GroovyConsole() { super(); this.setContextMenu(new ContextMenu()); this.instructions = new ArrayList<>(); this.appendText("Prob 2.0 Groovy Console \n >"); setListeners(); } public void setInterpreter(GroovyInterpreter interpreter) { this.interpreter = interpreter; } @Override public void paste() { if(this.getLength() - 1 - this.getCaretPosition() >= charCounterInLine) { goToLastPos(); } String oldText = this.getText(); int posOfEnter = oldText.lastIndexOf('\n'); super.paste(); int diff = this.getLength() - oldText.length(); String currentLine = this.getText().substring(posOfEnter + 3, this.getText().length()); if(currentLine.contains("\n")) { this.setText(oldText); goToLastPos(); return; } charCounterInLine += diff; currentPosInLine += diff; } @Override public void copy() { super.copy(); goToLastPos(); } @Override public void forward() { if(currentPosInLine <= charCounterInLine && this.getLength() - this.getCaretPosition() <= charCounterInLine) { super.forward(); currentPosInLine = charCounterInLine - (this.getLength() - this.getCaretPosition()); this.setScrollTop(Double.MIN_VALUE); } } @Override public void backward() { //handleLeft if(currentPosInLine > 0 && this.getLength() - this.getCaretPosition() <= charCounterInLine) { super.backward(); currentPosInLine = charCounterInLine - (this.getLength() - this.getCaretPosition()); this.setScrollTop(Double.MIN_VALUE); } else if(currentPosInLine == 0) { super.deselect(); } } @Override public void selectForward() { if(currentPosInLine != charCounterInLine) { super.selectForward(); currentPosInLine++; } } @Override public void selectBackward() { if(currentPosInLine != 0) { super.selectBackward(); currentPosInLine } } private void setListeners() { this.addEventHandler(CodeCompletionEvent.CODECOMPLETION, e-> { if(e instanceof CodeCompletionEvent) { if(((CodeCompletionEvent) e).getCode() == KeyCode.ENTER) { String choice = ((CodeCompletionEvent) e).getChoice(); this.appendText(choice); currentPosInLine += choice.length(); charCounterInLine += choice.length(); } } }); this.addEventFilter(KeyEvent.ANY, e -> { if(e.getCode() == KeyCode.Z && (e.isShortcutDown() || e.isAltDown())) { e.consume(); } }); this.addEventFilter(MouseEvent.ANY, e -> { if(e.getButton() == MouseButton.PRIMARY && (this.getLength() - 1 - this.getCaretPosition() < charCounterInLine)) { currentPosInLine = charCounterInLine - (this.getLength() - this.getCaretPosition()); } }); this.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN) { handleArrowKeys(e); this.setScrollTop(Double.MAX_VALUE); } else if (e.getCode().isNavigationKey()) { if(e.getCode() != KeyCode.LEFT && e.getCode() != KeyCode.RIGHT) { e.consume(); } } else if (e.getCode() == KeyCode.BACK_SPACE || e.getCode() == KeyCode.DELETE) { handleDeletion(e); } else if (e.getCode() == KeyCode.ENTER) { handleEnter(e); } else if (!e.getCode().isFunctionKey() && !e.getCode().isMediaKey() && !e.getCode().isModifierKey()) { handleInsertChar(e); } else { handleRest(e); } }); } private void goToLastPos() { this.positionCaret(this.getLength()); currentPosInLine = charCounterInLine; } private void handleInsertChar(KeyEvent e) { if(e.getText().isEmpty() || (!(e.isShortcutDown() || e.isAltDown()) && (this.getLength() - this.getCaretPosition()) > charCounterInLine)) { if(!(e.getCode() == KeyCode.UNDEFINED || e.getCode() == KeyCode.ALT_GRAPH)) { goToLastPos(); } if(e.getText().isEmpty()) { e.consume(); return; } } if (e.isShortcutDown() || e.isAltDown()) { return; } if(".".equals(e.getText())) { interpreter.triggerCodeCompletion(this, getCurrentLine()); } charCounterInLine++; currentPosInLine++; posInList = instructions.size() - 1; } private void handleEnter(KeyEvent e) { charCounterInLine = 0; currentPosInLine = 0; e.consume(); if(getCurrentLine().isEmpty()) { this.appendText("\n null"); } else { if(!instructions.isEmpty() && instructions.get(instructions.size() - 1).getOption() != InstructionOption.ENTER) { instructions.set(instructions.size() - 1, new Instruction(getCurrentLine(), InstructionOption.ENTER)); } else { instructions.add(new Instruction(getCurrentLine(), InstructionOption.ENTER)); } posInList = instructions.size() - 1; this.appendText("\n" + interpreter.exec(instructions.get(posInList))); } this.appendText("\n >"); } private void handleArrowKeys(KeyEvent e) { boolean needReturn; if(e.getCode().equals(KeyCode.UP)) { needReturn = handleUp(e); } else { needReturn = handleDown(e); } if(needReturn) { return; } setTextAfterArrowKey(); } private boolean handleUp(KeyEvent e) { e.consume(); if(posInList == -1) { return true; } if(posInList == instructions.size() - 1) { String lastinstruction = instructions.get(instructions.size()-1).getInstruction(); if(!lastinstruction.equals(getCurrentLine()) && posInList == instructions.size() - 1) { if(instructions.get(posInList).getOption() == InstructionOption.UP) { instructions.set(instructions.size() - 1, new Instruction(getCurrentLine(), InstructionOption.UP)); } else { instructions.add(new Instruction(getCurrentLine(), InstructionOption.UP)); setTextAfterArrowKey(); return true; } } } posInList = Math.max(posInList - 1, 0); return false; } private boolean handleDown(KeyEvent e) { e.consume(); if(posInList == instructions.size() - 1) { return true; } posInList = Math.min(posInList+1, instructions.size() - 1); return false; } private void setTextAfterArrowKey() { int posOfEnter = this.getText().lastIndexOf("\n"); this.setText(this.getText().substring(0, posOfEnter + 3)); String currentLine = instructions.get(posInList).getInstruction(); charCounterInLine = currentLine.length(); currentPosInLine = charCounterInLine; this.appendText(currentLine); } private void handleRest(KeyEvent e) { if(Arrays.asList(REST).contains(e.getCode())) { e.consume(); } } private void handleDeletion(KeyEvent e) { boolean needReturn; if(!this.getSelectedText().isEmpty() || this.getLength() - this.getCaretPosition() > charCounterInLine || e.isShortcutDown() || e.isAltDown()) { e.consume(); return; } if(e.getCode().equals(KeyCode.BACK_SPACE)) { needReturn = handleBackspace(e); if(needReturn) { return; } } else { needReturn = handleDelete(e); if(needReturn) { return; } } } private boolean handleBackspace(KeyEvent e) { if(currentPosInLine > 0) { currentPosInLine = Math.max(currentPosInLine - 1, 0); charCounterInLine = Math.max(charCounterInLine - 1, 0); } else { e.consume(); return true; } return false; } private boolean handleDelete(KeyEvent e) { if(currentPosInLine < charCounterInLine) { charCounterInLine = Math.max(charCounterInLine - 1, 0); } else if(currentPosInLine == charCounterInLine) { e.consume(); return true; } return false; } public String getCurrentLine() { int posOfEnter = this.getText().lastIndexOf("\n"); return this.getText().substring(posOfEnter + 3, this.getText().length()); } public void closeObjectStage() { interpreter.closeObjectStage(); } }
package server; import java.io.*; import java.util.HashMap; import java.util.Map; @SuppressWarnings("Since15") class ServerMenu { private File file = new File("TestDir1"); String way = file.getAbsolutePath(); private String newWay, root = way; private int bufferFile = 128; private int divTail, sends; private String separator = System.getProperty("file.separator"); private DataInputStream in; private DataOutputStream out; private Map<String, ServerActions> serverActionsHashMap = new HashMap<>(); ServerMenu(DataOutputStream out, DataInputStream in) { //this.path = Paths.get(System.getProperty("pathDir.dir")); this.in = in; this.out = out; } void fillServerActions(){ this.serverActionsHashMap.put("cd", new EnterFolder()); this.serverActionsHashMap.put("back", new ExitFolder()); this.serverActionsHashMap.put("list", new ShowList()); this.serverActionsHashMap.put("exit", new ExitApp()); this.serverActionsHashMap.put("download", new Download()); this.serverActionsHashMap.put("upload", new Upload()); } void select(ToDo toDo) throws IOException { if (serverActionsHashMap.containsKey(toDo.getKeyToDo())){ this.serverActionsHashMap.get(toDo.getKeyToDo()).execute(toDo); } } // public String getWay(){ // return this.way; private class EnterFolder implements ServerActions{ public String commandName() { return "cd"; } public void execute(ToDo value) throws IOException { System.out.println(System.getProperty("os.name")); newWay = way.concat(separator).concat(value.getTarget()); File file = new File(newWay); if (file.exists()){ out.writeUTF(newWay); way = newWay; out.writeBoolean(true); } else { out.writeUTF(way); out.writeBoolean(false); } } } private class ExitFolder implements ServerActions { public String commandName() { return "back"; } public void execute(ToDo value) throws IOException { File file1 = new File(way); boolean isExist = false; String parent = null; if (file1.getParentFile().exists() && !way.equals(root)){ isExist = true; parent = file1.getParent(); } out.writeBoolean(isExist); if (isExist){ way = parent; } out.writeUTF(way); } } private class ExitApp implements ServerActions { public String commandName() { return "exit"; } public void execute(ToDo value) throws IOException { } } private class ShowList implements ServerActions { public String commandName() { return "list"; } public void execute(ToDo value) throws IOException { File fl = new File(way); boolean isDir; isDir = fl.isDirectory(); out.writeBoolean(isDir); if (isDir) { File[] files = fl.listFiles(); int quantity = 0; if (files != null) { quantity = files.length; } out.writeInt(quantity); if (quantity != 0) { for (File file1 : files) { out.writeUTF(file1.getName()); if (file1.isDirectory()) { out.writeBoolean(true); } else { out.writeBoolean(false); } } } } out.writeUTF(way); } } private class Download implements ServerActions { public String commandName() { return "download"; } public void execute(ToDo value) throws IOException { newWay = way.concat(separator).concat(value.getTarget()); boolean isExist = false; if (new File(newWay).exists()){ isExist = true; way = newWay; } out.writeBoolean(isExist); if (isExist) { out.writeUTF(way); File file = new File(way); boolean isFolder = false; if (file.isDirectory()) { isFolder = true; } out.writeBoolean(isFolder); if (!isFolder) { int fileSize = (int) file.length(); out.writeInt(fileSize); if (fileSize > bufferFile) { divTail = fileSize % bufferFile; sends = (fileSize - divTail) / bufferFile; out.writeInt(bufferFile); out.writeInt(sends); out.writeInt(divTail); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){ byte []buffer = new byte[bufferFile]; for (int i = 0; i < sends; i++){ bis.read(buffer, 0, buffer.length); out.write(buffer, 0, buffer.length); } if (divTail != 0){ byte []tailBuffer = new byte[divTail]; bis.read(tailBuffer, 0, tailBuffer.length); out.write(tailBuffer, 0, tailBuffer.length); } bis.close(); } catch (Exception ex){ ex.printStackTrace(); } } else { //bufferFile = fileSize; out.writeInt(fileSize); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){ byte []buffer = new byte[fileSize]; bis.read(buffer, 0, buffer.length); out.write(buffer, 0, buffer.length); } catch (Exception ex){ ex.printStackTrace(); } } } } } } private class Upload implements ServerActions { @Override public String commandName() { return "upload"; } @Override public void execute(ToDo value) throws IOException { boolean isExist = in.readBoolean(); if (isExist) { boolean isDirectory = in.readBoolean(); if (!isDirectory){ File file = new File(value.getTarget()); out.writeInt(bufferFile); int fileSize = in.readInt(); boolean oneSent = in.readBoolean(); if (!oneSent){ try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){ sends = in.readInt(); divTail = in.readInt(); byte []buffer = new byte[bufferFile]; for (int i = 0; i < sends; i++){ in.read(buffer, 0, buffer.length); bos.write(buffer, 0, buffer.length); } if (divTail != 0){ byte []tailBuffer = new byte[divTail]; in.read(tailBuffer, 0, tailBuffer.length); bos.write(tailBuffer, 0, tailBuffer.length); } bos.flush(); } catch (Exception ex){ ex.printStackTrace(); } } else { try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){ byte []buffer = new byte[fileSize]; in.read(buffer, 0, buffer.length); bos.write(buffer, 0, buffer.length); bos.flush(); } catch (Exception ex){ ex.printStackTrace(); } } } } } } }
package de.prob2.ui.internal; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Provides; import com.google.inject.util.Providers; import de.codecentric.centerdevice.MenuToolkit; import de.prob.MainModule; import de.prob2.ui.MainController; import de.prob2.ui.config.RuntimeOptions; import de.prob2.ui.helpsystem.HelpButton; import de.prob2.ui.history.HistoryView; import de.prob2.ui.menu.ConsolesMenu; import de.prob2.ui.menu.EditMenu; import de.prob2.ui.menu.FileMenu; import de.prob2.ui.menu.FormulaMenu; import de.prob2.ui.menu.HelpMenu; import de.prob2.ui.menu.MainView; import de.prob2.ui.menu.MenuController; import de.prob2.ui.menu.PerspectivesMenu; import de.prob2.ui.menu.PluginMenu; import de.prob2.ui.menu.ViewMenu; import de.prob2.ui.operations.OperationsView; import de.prob2.ui.plugin.ProBConnection; import de.prob2.ui.plugin.ProBPluginManager; import de.prob2.ui.preferences.PreferencesView; import de.prob2.ui.project.ProjectTab; import de.prob2.ui.project.ProjectView; import de.prob2.ui.project.machines.MachinesTab; import de.prob2.ui.project.preferences.PreferencesTab; import de.prob2.ui.project.runconfigurations.RunconfigurationsTab; import de.prob2.ui.states.StatesView; import de.prob2.ui.stats.StatsView; import de.prob2.ui.statusbar.StatusBar; import de.prob2.ui.verifications.MachineTableView; import de.prob2.ui.verifications.VerificationsView; import de.prob2.ui.verifications.cbc.CBCView; import de.prob2.ui.verifications.ltl.LTLView; import de.prob2.ui.verifications.ltl.formula.LTLFormulaChecker; import de.prob2.ui.verifications.modelchecking.ModelcheckingController; import de.prob2.ui.visualisation.StateVisualisationView; import de.prob2.ui.visualisation.VisualisationView; import javafx.fxml.FXMLLoader; public class ProB2Module extends AbstractModule { /** * Custom {@link ResourceBundle.Control} subclass that loads property bundles as UTF-8 instead of the default ISO-8859-1. */ private static final class UTF8PropertiesControl extends ResourceBundle.Control { private UTF8PropertiesControl() { super(); } @Override public ResourceBundle newBundle( final String baseName, final Locale locale, final String format, final ClassLoader loader, final boolean reload ) throws IllegalAccessException, InstantiationException, IOException { if ("java.properties".equals(format)) { // This is mostly copied from the default ResourceBundle.Control.newBundle implementation. final String resourceName = toResourceName(toBundleName(baseName, locale), "properties"); final URL url = loader.getResource(resourceName); if (url != null) { final URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(!reload); try ( final InputStream stream = connection.getInputStream(); final Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); ) { return new PropertyResourceBundle(reader); } } } return null; } else { return super.newBundle(baseName, locale, format, loader, reload); } } } public static final boolean IS_MAC = System.getProperty("os.name", "").toLowerCase().contains("mac"); private final RuntimeOptions runtimeOptions; public ProB2Module(final RuntimeOptions runtimeOptions) { super(); this.runtimeOptions = runtimeOptions; } @Override protected void configure() { install(new MainModule()); // General stuff final Locale locale = Locale.getDefault(); bind(Locale.class).toInstance(locale); final ResourceBundle bundle = ResourceBundle.getBundle("de.prob2.ui.prob2", locale, new ProB2Module.UTF8PropertiesControl()); bind(ResourceBundle.class).toInstance(bundle); final MenuToolkit toolkit = IS_MAC ? MenuToolkit.toolkit(locale) : null; bind(MenuToolkit.class).toProvider(Providers.of(toolkit)); bind(RuntimeOptions.class).toInstance(this.runtimeOptions); // Controllers bind(CBCView.class); bind(HistoryView.class); bind(MainController.class); bind(LTLFormulaChecker.class); bind(HelpButton.class); bind(MachineTableView.class); bind(LTLView.class); bind(MachinesTab.class); bind(MainView.class); bind(MenuController.class); bind(FileMenu.class); bind(EditMenu.class); bind(FormulaMenu.class); bind(ConsolesMenu.class); bind(PerspectivesMenu.class); bind(ViewMenu.class); bind(PluginMenu.class); bind(HelpMenu.class); bind(ModelcheckingController.class); bind(OperationsView.class); bind(PreferencesTab.class); bind(PreferencesView.class); bind(ProjectView.class); bind(ProjectTab.class); bind(RunconfigurationsTab.class); bind(StatesView.class); bind(StatsView.class); bind(StatusBar.class); bind(VerificationsView.class); bind(VisualisationView.class); bind(StateVisualisationView.class); bind(ProBPluginManager.class); bind(ProBConnection.class); } @Provides public FXMLLoader provideLoader(final Injector injector, GuiceBuilderFactory builderFactory, ResourceBundle bundle) { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setBuilderFactory(builderFactory); fxmlLoader.setControllerFactory(injector::getInstance); fxmlLoader.setResources(bundle); return fxmlLoader; } }
package de.team33.libs.reflect.v3; import java.lang.reflect.Field; import java.util.function.Function; import java.util.function.IntPredicate; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Utility for dealing with fields. */ public class Fields { /** * Streams all {@link Field}s straightly declared by a given {@link Class} */ public static Stream<Field> flat(final Class<?> subject) { return fieldsOf(Classes.optional(subject)); } /** * Streams all {@link Field}s declared by a given {@link Class} or any of its superclasses. */ public static Stream<Field> deep(final Class<?> subject) { return fieldsOf(Classes.deep(subject)); } /** * Streams all {@link Field}s declared by a given {@link Class}, any of its superclasses or any of its * superinterfaces. */ public static Stream<Field> wide(final Class<?> subject) { return fieldsOf(Classes.wide(subject)); } /** * Determines a canonical, fully qualified name for a given field. */ public static String canonicalName(final Field field) { return field.getDeclaringClass().getCanonicalName() + "." + field.getName(); } private static Stream<Field> fieldsOf(final Stream<Class<?>> classes) { return classes.map(Class::getDeclaredFields) .map(Stream::of) .reduce(Stream::concat) .orElseGet(Stream::empty); } /** * Provides some predefined {@linkplain Predicate filters} for {@link Field Fields}. */ public enum Filter implements Predicate<Field> { /** * Defines a filter accepting all fields (including static fields). */ ANY(Modifiers.Predicate.TRUE), /** * Defines a filter accepting all public fields. */ PUBLIC(Modifiers.Predicate.PUBLIC), /** * Defines a filter accepting all private fields. */ PRIVATE(Modifiers.Predicate.PRIVATE), /** * Defines a filter accepting all protected fields. */ PROTECTED(Modifiers.Predicate.PROTECTED), /** * Defines a filter accepting all static fields. */ STATIC(Modifiers.Predicate.STATIC), /** * Defines a filter accepting all final fields. */ FINAL(Modifiers.Predicate.FINAL), /** * Defines a filter accepting all transient fields. */ TRANSIENT(Modifiers.Predicate.TRANSIENT), /** * Defines a filter accepting all instance-fields (non-static fields). */ INSTANCE(Modifiers.Predicate.STATIC.negate()), /** * Defines a filter accepting all but static or transient fields. * Those fields should be significant for a type with value semantics. */ SIGNIFICANT(Modifiers.Predicate.STATIC.or(Modifiers.Predicate.TRANSIENT).negate()); private final IntPredicate filter; Filter(final IntPredicate filter) { this.filter = filter; } @Override public final boolean test(final Field field) { return filter.test(field.getModifiers()); } } /** * Defines some typical {@link Function}s that serve to find a name for a {@link Field}. */ public interface Naming extends Function<Field, String> { /** * A {@link Function} that simply returns the plain {@linkplain Field#getName() name} of a given {@link Field}. */ Naming SIMPLE = Field::getName; /** * A {@link Function} that returns a canonical, full qualified name for a given {@link Field}. */ Naming CANONICAL = Fields::canonicalName; /** * Defines some typical {@link Function}s that serve to find a name for a {@link Field} * that is as unique as possible in the context of a particular class. */ interface ContextSensitive extends Function<Class<?>, Function<Field, String>> { /** * A {@link Function} that simply returns the plain {@linkplain Field#getName() name} of the given * {@link Field} if inquired in the context of the Field's declaring class. Otherwise it returns a * canonical, full qualified name. */ ContextSensitive QUALIFIED = context -> field -> context.equals(field.getDeclaringClass()) ? field.getName() : canonicalName(field); /** * A {@link Function} that returns the plane {@linkplain Field#getName() name} of the given {@link Field}, * preceded by a corresponding number of points (".") depending on the distance of the context to the * declaring class of the field. */ ContextSensitive COMPACT = context -> field -> Stream.generate(() -> ".") .limit(Classes.distance(context, field.getDeclaringClass())) .collect(Collectors.joining("", "", field.getName())); } } }
package edu.jhu.nlp.joint; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import org.apache.commons.cli.ParseException; import org.apache.log4j.Logger; import edu.jhu.autodiff.erma.DepParseDecodeLoss.DepParseDecodeLossFactory; import edu.jhu.autodiff.erma.ErmaBp.ErmaBpPrm; import edu.jhu.autodiff.erma.ErmaObjective.BeliefsModuleFactory; import edu.jhu.autodiff.erma.ExpectedRecall.ExpectedRecallFactory; import edu.jhu.autodiff.erma.InsideOutsideDepParse; import edu.jhu.autodiff.erma.MeanSquaredError.MeanSquaredErrorFactory; import edu.jhu.gm.data.FgExampleListBuilder.CacheType; import edu.jhu.gm.decode.MbrDecoder.Loss; import edu.jhu.gm.decode.MbrDecoder.MbrDecoderPrm; import edu.jhu.gm.feat.ObsFeatureConjoiner.ObsFeatureConjoinerPrm; import edu.jhu.gm.inf.BeliefPropagation.BpScheduleType; import edu.jhu.gm.inf.BeliefPropagation.BpUpdateOrder; import edu.jhu.gm.inf.BruteForceInferencer.BruteForceInferencerPrm; import edu.jhu.gm.inf.FgInferencerFactory; import edu.jhu.gm.model.Var.VarType; import edu.jhu.gm.train.CrfTrainer.CrfTrainerPrm; import edu.jhu.gm.train.CrfTrainer.Trainer; import edu.jhu.hlt.optimize.AdaDelta; import edu.jhu.hlt.optimize.AdaDelta.AdaDeltaPrm; import edu.jhu.hlt.optimize.AdaGradSchedule; import edu.jhu.hlt.optimize.AdaGradSchedule.AdaGradSchedulePrm; import edu.jhu.hlt.optimize.BottouSchedule; import edu.jhu.hlt.optimize.BottouSchedule.BottouSchedulePrm; import edu.jhu.hlt.optimize.MalletLBFGS; import edu.jhu.hlt.optimize.MalletLBFGS.MalletLBFGSPrm; import edu.jhu.hlt.optimize.SGD; import edu.jhu.hlt.optimize.SGD.SGDPrm; import edu.jhu.hlt.optimize.SGDFobos; import edu.jhu.hlt.optimize.SGDFobos.SGDFobosPrm; import edu.jhu.hlt.optimize.StanfordQNMinimizer; import edu.jhu.hlt.optimize.function.DifferentiableFunction; import edu.jhu.hlt.optimize.functions.L2; import edu.jhu.nlp.AnnoPipeline; import edu.jhu.nlp.Annotator; import edu.jhu.nlp.CorpusStatistics.CorpusStatisticsPrm; import edu.jhu.nlp.EvalPipeline; import edu.jhu.nlp.InformationGainFeatureTemplateSelector; import edu.jhu.nlp.InformationGainFeatureTemplateSelector.InformationGainFeatureTemplateSelectorPrm; import edu.jhu.nlp.InformationGainFeatureTemplateSelector.SrlFeatTemplates; import edu.jhu.nlp.data.simple.AnnoSentenceCollection; import edu.jhu.nlp.data.simple.CorpusHandler; import edu.jhu.nlp.depparse.DepParseFeatureExtractor.DepParseFeatureExtractorPrm; import edu.jhu.nlp.depparse.FirstOrderPruner; import edu.jhu.nlp.depparse.PosTagDistancePruner; import edu.jhu.nlp.embed.Embeddings.Scaling; import edu.jhu.nlp.embed.EmbeddingsAnnotator; import edu.jhu.nlp.embed.EmbeddingsAnnotator.EmbeddingsAnnotatorPrm; import edu.jhu.nlp.eval.DepParseEvaluator; import edu.jhu.nlp.eval.OraclePruningAccuracy; import edu.jhu.nlp.eval.RelationEvaluator; import edu.jhu.nlp.eval.SrlEvaluator; import edu.jhu.nlp.eval.SrlSelfLoops; import edu.jhu.nlp.features.TemplateLanguage; import edu.jhu.nlp.features.TemplateLanguage.AT; import edu.jhu.nlp.features.TemplateLanguage.FeatTemplate; import edu.jhu.nlp.features.TemplateReader; import edu.jhu.nlp.features.TemplateSets; import edu.jhu.nlp.features.TemplateWriter; import edu.jhu.nlp.joint.JointNlpAnnotator.InitParams; import edu.jhu.nlp.joint.JointNlpAnnotator.JointNlpAnnotatorPrm; import edu.jhu.nlp.joint.JointNlpDecoder.JointNlpDecoderPrm; import edu.jhu.nlp.joint.JointNlpEncoder.JointNlpFeatureExtractorPrm; import edu.jhu.nlp.joint.JointNlpFgExamplesBuilder.JointNlpFgExampleBuilderPrm; import edu.jhu.nlp.relations.RelationsOptions; import edu.jhu.nlp.srl.SrlFactorGraphBuilder.RoleStructure; import edu.jhu.nlp.srl.SrlFeatureExtractor.SrlFeatureExtractorPrm; import edu.jhu.nlp.tag.BrownClusterTagger; import edu.jhu.nlp.tag.BrownClusterTagger.BrownClusterTaggerPrm; import edu.jhu.prim.util.math.FastMath; import edu.jhu.util.Prng; import edu.jhu.util.Timer; import edu.jhu.util.cli.ArgParser; import edu.jhu.util.cli.Opt; import edu.jhu.util.collections.Lists; import edu.jhu.util.report.Reporter; import edu.jhu.util.report.ReporterManager; import edu.jhu.util.semiring.Algebra; import edu.jhu.util.semiring.Algebras; /** * Pipeline runner for SRL experiments. * @author mgormley * @author mmitchell */ public class JointNlpRunner { public static enum Optimizer { LBFGS, QN, SGD, ADAGRAD, ADADELTA, FOBOS }; public enum ErmaLoss { MSE, EXPECTED_RECALL, DP_DECODE_LOSS }; public enum Inference { BRUTE_FORCE, BP }; public enum RegularizerType { L2, NONE }; public enum AlgebraType { REAL(Algebras.REAL_ALGEBRA), LOG(Algebras.LOG_SEMIRING), LOG_SIGN(Algebras.LOG_SIGN_ALGEBRA), // SHIFTED_REAL and SPLIT algebras are for testing only. SHIFTED_REAL(Algebras.SHIFTED_REAL_ALGEBRA), SPLIT(Algebras.SPLIT_ALGEBRA); private Algebra s; private AlgebraType(Algebra s) { this.s = s; } public Algebra getAlgebra() { return s; } } private static final Logger log = Logger.getLogger(JointNlpRunner.class); private static final Reporter rep = Reporter.getReporter(JointNlpRunner.class); // Options not specific to the model @Opt(name = "seed", hasArg = true, description = "Pseudo random number generator seed for everything else.") public static long seed = Prng.DEFAULT_SEED; @Opt(hasArg = true, description = "Number of threads for computation.") public static int threads = 1; @Opt(hasArg = true, description = "Whether to use a log-add table for faster computation.") public static boolean useLogAddTable = false; // Options for model IO @Opt(hasArg = true, description = "File from which to read a serialized model.") public static File modelIn = null; @Opt(hasArg = true, description = "File to which to serialize the model.") public static File modelOut = null; @Opt(hasArg = true, description = "File to which to print a human readable version of the model.") public static File printModel = null; // Options for initialization. @Opt(hasArg = true, description = "How to initialize the parameters of the model.") public static InitParams initParams = InitParams.UNIFORM; // Options for inference. @Opt(hasArg = true, description = "Type of inference method.") public static Inference inference = Inference.BP; @Opt(hasArg = true, description = "Whether to run inference in the log-domain.") public static AlgebraType algebra = AlgebraType.REAL; @Opt(hasArg = true, description = "Whether to run inference in the log-domain.") public static boolean logDomain = true; @Opt(hasArg = true, description = "The BP schedule type.") public static BpScheduleType bpSchedule = BpScheduleType.TREE_LIKE; @Opt(hasArg = true, description = "The BP update order.") public static BpUpdateOrder bpUpdateOrder = BpUpdateOrder.SEQUENTIAL; @Opt(hasArg = true, description = "The max number of BP iterations.") public static int bpMaxIterations = 1; @Opt(hasArg = true, description = "Whether to normalize the messages.") public static boolean normalizeMessages = false; @Opt(hasArg = true, description = "The maximum message residual for convergence testing.") public static double bpConvergenceThreshold = 1e-3; @Opt(hasArg = true, description = "Directory to dump debugging information for BP.") public static File bpDumpDir = null; // Options for Brown clusters. @Opt(hasArg = true, description = "Brown cluster file") public static File brownClusters = null; // Options for Embeddings. @Opt(hasArg=true, description="Path to word embeddings text file.") public static File embeddingsFile = null; @Opt(hasArg=true, description="Method for normalization of the embeddings.") public static Scaling embNorm = Scaling.L1_NORM; @Opt(hasArg=true, description="Amount to scale embeddings after normalization.") public static double embScaler = 15.0; // Options for SRL factor graph structure. @Opt(hasArg = true, description = "The structure of the Role variables.") public static RoleStructure roleStructure = RoleStructure.PREDS_GIVEN; @Opt(hasArg = true, description = "Whether Role variables with unknown predicates should be latent.") public static boolean makeUnknownPredRolesLatent = true; @Opt(hasArg = true, description = "Whether to allow a predicate to assign a role to itself. (This should be turned on for English)") public static boolean allowPredArgSelfLoops = false; @Opt(hasArg = true, description = "Whether to include factors between the sense and role variables.") public static boolean binarySenseRoleFactors = false; @Opt(hasArg = true, description = "Whether to predict predicate sense.") public static boolean predictSense = false; @Opt(hasArg = true, description = "Whether to predict predicate positions.") public static boolean predictPredPos = false; // Options for joint factor graph structure. @Opt(hasArg = true, description = "Whether to include unary factors in the model.") public static boolean unaryFactors = false; // Options for SRL feature selection. @Opt(hasArg = true, description = "Whether to do feature selection.") public static boolean featureSelection = true; @Opt(hasArg = true, description = "The number of feature bigrams to form.") public static int numFeatsToSelect = 32; @Opt(hasArg = true, description = "The max number of sentences to use for feature selection") public static int numSentsForFeatSelect = 1000; // Options for feature extraction. @Opt(hasArg = true, description = "For testing only: whether to use only the bias feature.") public static boolean biasOnly = false; @Opt(hasArg = true, description = "The value of the mod for use in the feature hashing trick. If <= 0, feature-hashing will be disabled.") public static int featureHashMod = 524288; // 2^19 // Options for SRL feature extraction. @Opt(hasArg = true, description = "Cutoff for OOV words.") public static int cutoff = 3; @Opt(hasArg = true, description = "For preprocessing: Minimum feature count for caching.") public static int featCountCutoff = 4; @Opt(hasArg = true, description = "Whether to include unsupported features.") public static boolean includeUnsupportedFeatures = false; @Opt(hasArg = true, description = "Whether to add the Simple features.") public static boolean useSimpleFeats = true; @Opt(hasArg = true, description = "Whether to add the Naradowsky features.") public static boolean useNaradFeats = true; @Opt(hasArg = true, description = "Whether to add the Zhao features.") public static boolean useZhaoFeats = true; @Opt(hasArg = true, description = "Whether to add the Bjorkelund features.") public static boolean useBjorkelundFeats = true; @Opt(hasArg = true, description = "Whether to add dependency path features.") public static boolean useLexicalDepPathFeats = false; @Opt(hasArg = true, description = "Whether to include pairs of features.") public static boolean useTemplates = false; @Opt(hasArg = true, description = "Sense feature templates.") public static String senseFeatTpls = TemplateSets.bjorkelundSenseFeatsResource; @Opt(hasArg = true, description = "Arg feature templates.") public static String argFeatTpls = TemplateSets.bjorkelundArgFeatsResource; @Opt(hasArg = true, description = "Sense feature template output file.") public static File senseFeatTplsOut = null; @Opt(hasArg = true, description = "Arg feature template output file.") public static File argFeatTplsOut = null; // Options for dependency parse factor graph structure. @Opt(hasArg = true, description = "The type of the link variables.") public static VarType linkVarType = VarType.LATENT; @Opt(hasArg = true, description = "Whether to include a projective dependency tree global factor.") public static boolean useProjDepTreeFactor = false; @Opt(hasArg = true, description = "Whether to include 2nd-order grandparent factors in the model.") public static boolean grandparentFactors = false; @Opt(hasArg = true, description = "Whether to include 2nd-order sibling factors in the model.") public static boolean siblingFactors = false; @Opt(hasArg = true, description = "Whether to exclude non-projective grandparent factors.") public static boolean excludeNonprojectiveGrandparents = true; // Options for dependency parsing pruning. @Opt(hasArg = true, description = "File from which to read a first-order pruning model.") public static File pruneModel = null; @Opt(hasArg = true, description = "Whether to prune higher-order factors via a first-order pruning model.") public static boolean pruneByModel = false; @Opt(hasArg = true, description = "Whether to prune edges with a deterministic distance-based pruning approach.") public static boolean pruneByDist = false; // Options for Dependency parser feature extraction. @Opt(hasArg = true, description = "1st-order factor feature templates.") public static String dp1FeatTpls = TemplateSets.mcdonaldDepFeatsResource; @Opt(hasArg = true, description = "2nd-order factor feature templates.") public static String dp2FeatTpls = TemplateSets.carreras07Dep2FeatsResource; @Opt(hasArg = true, description = "Whether to use SRL features for dep parsing.") public static boolean acl14DepFeats = true; @Opt(hasArg = true, description = "Whether to use the fast feature set for dep parsing.") public static boolean dpFastFeats = true; // Options for relation extraction. @Opt(hasArg = true, description = "Relation feature templates.") public static String relFeatTpls = null; // Options for data munging. @Deprecated @Opt(hasArg=true, description="Whether to normalize and clean words.") public static boolean normalizeWords = false; // Options for caching. @Opt(hasArg = true, description = "The type of cache/store to use for training/testing instances.") public static CacheType cacheType = CacheType.CACHE; @Opt(hasArg = true, description = "When caching, the maximum number of examples to keep cached in memory or -1 for SoftReference caching.") public static int maxEntriesInMemory = 100; @Opt(hasArg = true, description = "Whether to gzip an object before caching it.") public static boolean gzipCache = false; // Options for optimization. @Opt(hasArg=true, description="The optimization method to use for training.") public static Optimizer optimizer = Optimizer.LBFGS; @Opt(hasArg=true, description="The variance for the L2 regularizer.") public static double l2variance = 1.0; @Opt(hasArg=true, description="The type of regularizer.") public static RegularizerType regularizer = RegularizerType.L2; @Opt(hasArg=true, description="Max iterations for L-BFGS training.") public static int maxLbfgsIterations = 1000; @Opt(hasArg=true, description="Number of effective passes over the dataset for SGD.") public static int sgdNumPasses = 30; @Opt(hasArg=true, description="The batch size to use at each step of SGD.") public static int sgdBatchSize = 15; @Opt(hasArg=true, description="The initial learning rate for SGD.") public static double sgdInitialLr = 0.1; @Opt(hasArg=true, description="Whether to sample with replacement for SGD.") public static boolean sgdWithRepl = false; @Opt(hasArg=true, description="Whether to automatically select the learning rate.") public static boolean sgdAutoSelectLr = true; @Opt(hasArg=true, description="How many epochs between auto-select runs.") public static int sgdAutoSelecFreq = 5; @Opt(hasArg=true, description="Whether to compute the function value on iterations other than the last.") public static boolean sgdComputeValueOnNonFinalIter = true; @Opt(hasArg=true, description="The AdaGrad parameter for scaling the learning rate.") public static double adaGradEta = 0.1; @Opt(hasArg=true, description="The constant addend for AdaGrad.") public static double adaGradConstantAddend = 1e-9; @Opt(hasArg=true, description="The decay rate for AdaDelta.") public static double adaDeltaDecayRate = 0.95; @Opt(hasArg=true, description="The constant addend for AdaDelta.") public static double adaDeltaConstantAddend = Math.pow(Math.E, -6.); @Opt(hasArg=true, description="Stop training by this date/time.") public static Date stopTrainingBy = null; // Options for training. @Opt(hasArg=true, description="Whether to use the mean squared error instead of conditional log-likelihood when evaluating training quality.") public static boolean useMseForValue = false; @Opt(hasArg=true, description="The type of trainer to use (e.g. conditional log-likelihood, ERMA).") public static Trainer trainer = Trainer.CLL; // Options for training a dependency parser with ERMA. @Opt(hasArg=true, description="The start temperature for the softmax MBR decoder for dependency parsing.") public static double dpStartTemp = 10; @Opt(hasArg=true, description="The end temperature for the softmax MBR decoder for dependency parsing.") public static double dpEndTemp = .1; @Opt(hasArg=true, description="Whether to transition from MSE to the softmax MBR decoder with expected recall.") public static boolean dpAnnealMse = true; @Opt(hasArg=true, description="Whether to transition from MSE to the softmax MBR decoder with expected recall.") public static ErmaLoss dpLoss = ErmaLoss.DP_DECODE_LOSS; public JointNlpRunner() { } public void run() throws ParseException, IOException { Timer t = new Timer(); t.start(); FastMath.useLogAddTable = useLogAddTable; if (useLogAddTable) { log.warn("Using log-add table instead of exact computation. When using global factors, this may result in numerical instability."); } if (stopTrainingBy != null && new Date().after(stopTrainingBy)) { log.warn("Training will never begin since stopTrainingBy has already happened: " + stopTrainingBy); log.warn("Ignoring stopTrainingBy by setting it to null."); stopTrainingBy = null; } // Initialize the data reader/writer. CorpusHandler corpus = new CorpusHandler(); // Get a model. if (modelIn == null && !corpus.hasTrain()) { throw new ParseException("Either --modelIn or --train must be specified."); } JointNlpAnnotatorPrm prm = getJointNlpAnnotatorPrm(); if (modelIn == null && corpus.hasTrain()) { // Feature selection. // TODO: Move feature selection into the pipeline. featureSelection(corpus.getTrainGold(), prm.buPrm.fePrm); } AnnoPipeline anno = new AnnoPipeline(); EvalPipeline eval = new EvalPipeline(); JointNlpAnnotator jointAnno = new JointNlpAnnotator(prm); if (modelIn != null) { jointAnno.loadModel(modelIn); } { // Add Brown clusters. if (brownClusters != null) { anno.add(new Annotator() { @Override public void annotate(AnnoSentenceCollection sents) { log.info("Adding Brown clusters."); BrownClusterTagger bct = new BrownClusterTagger(getBrownCluterTaggerPrm()); bct.read(brownClusters); bct.annotate(sents); log.info("Brown cluster hit rate: " + bct.getHitRate()); } }); } else { log.info("No Brown clusters file specified."); } // Add word embeddings. if (embeddingsFile != null) { anno.add(new Annotator() { @Override public void annotate(AnnoSentenceCollection sents) { log.info("Adding word embeddings."); EmbeddingsAnnotator ea = new EmbeddingsAnnotator(getEmbeddingsAnnotatorPrm()); ea.annotate(sents); log.info("Embeddings hit rate: " + ea.getHitRate()); } }); } else { log.info("No embeddings file specified."); } if (pruneByDist) { // Prune via the distance-based pruner. anno.add(new PosTagDistancePruner()); } if (pruneByModel) { if (pruneModel == null) { throw new IllegalStateException("If pruneEdges is true, pruneModel must be specified."); } anno.add(new FirstOrderPruner(pruneModel, getSrlFgExampleBuilderPrm(null), getDecoderPrm())); } // Various NLP annotations. anno.add(jointAnno); } { if (pruneByDist || pruneByModel) { eval.add(new OraclePruningAccuracy()); } if (CorpusHandler.getGoldOnlyAts().contains(AT.DEP_TREE)) { eval.add(new DepParseEvaluator()); } if (CorpusHandler.getGoldOnlyAts().contains(AT.SRL)) { eval.add(new SrlSelfLoops()); eval.add(new SrlEvaluator()); } if (CorpusHandler.getGoldOnlyAts().contains(AT.REL_LABELS)) { eval.add(new RelationEvaluator()); } } if (corpus.hasTrain()) { String name = "train"; AnnoSentenceCollection trainGold = corpus.getTrainGold(); AnnoSentenceCollection trainInput = corpus.getTrainInput(); // (Dev data might be null.) AnnoSentenceCollection devGold = corpus.getDevGold(); AnnoSentenceCollection devInput = corpus.getDevInput(); // Train a model. (The PipelineAnnotator also annotates all the input.) anno.train(trainInput, trainGold, devInput, devGold); // Decode and evaluate the train data. corpus.writeTrainPreds(trainInput); eval.evaluate(trainInput, trainGold, name); corpus.clearTrainCache(); if (corpus.hasDev()) { // Write dev data predictions. name = "dev"; corpus.writeDevPreds(devInput); // Evaluate dev data. eval.evaluate(devInput, devGold, name); corpus.clearDevCache(); } } if (modelOut != null) { jointAnno.saveModel(modelOut); } if (printModel != null) { jointAnno.printModel(printModel); } if (corpus.hasTest()) { // Decode test data. String name = "test"; AnnoSentenceCollection testInput = corpus.getTestInput(); anno.annotate(testInput); corpus.writeTestPreds(testInput); // Evaluate test data. AnnoSentenceCollection testGold = corpus.getTestGold(); eval.evaluate(testInput, testGold, name); corpus.clearTestCache(); } t.stop(); rep.report("elapsedSec", t.totSec()); } /** * Do feature selection and update fePrm with the chosen feature templates. */ private void featureSelection(AnnoSentenceCollection sents, JointNlpFeatureExtractorPrm fePrm) throws IOException, ParseException { SrlFeatureExtractorPrm srlFePrm = fePrm.srlFePrm; // Remove annotation types from the features which are explicitly excluded. removeAts(fePrm); if (useTemplates && featureSelection) { CorpusStatisticsPrm csPrm = getCorpusStatisticsPrm(); InformationGainFeatureTemplateSelectorPrm prm = new InformationGainFeatureTemplateSelectorPrm(); prm.featureHashMod = featureHashMod; prm.numThreads = threads; prm.numToSelect = numFeatsToSelect; prm.maxNumSentences = numSentsForFeatSelect; prm.selectSense = predictSense; SrlFeatTemplates sft = new SrlFeatTemplates(srlFePrm.fePrm.soloTemplates, srlFePrm.fePrm.pairTemplates, null); InformationGainFeatureTemplateSelector ig = new InformationGainFeatureTemplateSelector(prm); sft = ig.getFeatTemplatesForSrl(sents, csPrm, sft); ig.shutdown(); srlFePrm.fePrm.soloTemplates = sft.srlSense; srlFePrm.fePrm.pairTemplates = sft.srlArg; } if (CorpusHandler.getGoldOnlyAts().contains(AT.SRL) && acl14DepFeats) { fePrm.dpFePrm.firstOrderTpls = srlFePrm.fePrm.pairTemplates; } if (useTemplates) { log.info("Num sense feature templates: " + srlFePrm.fePrm.soloTemplates.size()); log.info("Num arg feature templates: " + srlFePrm.fePrm.pairTemplates.size()); if (senseFeatTplsOut != null) { TemplateWriter.write(senseFeatTplsOut, srlFePrm.fePrm.soloTemplates); } if (argFeatTplsOut != null) { TemplateWriter.write(argFeatTplsOut, srlFePrm.fePrm.pairTemplates); } } } private void removeAts(JointNlpEncoder.JointNlpFeatureExtractorPrm fePrm) { List<AT> ats = Lists.union(CorpusHandler.getRemoveAts(), CorpusHandler.getPredAts()); if (brownClusters == null) { // Filter out the Brown cluster features. log.warn("Filtering out Brown cluster features."); ats.add(AT.BROWN); } for (AT at : ats) { fePrm.srlFePrm.fePrm.soloTemplates = TemplateLanguage.filterOutRequiring(fePrm.srlFePrm.fePrm.soloTemplates, at); fePrm.srlFePrm.fePrm.pairTemplates = TemplateLanguage.filterOutRequiring(fePrm.srlFePrm.fePrm.pairTemplates, at); fePrm.dpFePrm.firstOrderTpls = TemplateLanguage.filterOutRequiring(fePrm.dpFePrm.firstOrderTpls, at); fePrm.dpFePrm.secondOrderTpls = TemplateLanguage.filterOutRequiring(fePrm.dpFePrm.secondOrderTpls, at); } } private static JointNlpAnnotatorPrm getJointNlpAnnotatorPrm() throws ParseException { JointNlpAnnotatorPrm prm = new JointNlpAnnotatorPrm(); prm.crfPrm = getCrfTrainerPrm(); prm.csPrm = getCorpusStatisticsPrm(); prm.dePrm = getDecoderPrm(); prm.initParams = initParams; prm.ofcPrm = getObsFeatureConjoinerPrm(); JointNlpFeatureExtractorPrm fePrm = getJointNlpFeatureExtractorPrm(); prm.buPrm = getSrlFgExampleBuilderPrm(fePrm); return prm; } private static JointNlpFgExampleBuilderPrm getSrlFgExampleBuilderPrm(JointNlpEncoder.JointNlpFeatureExtractorPrm fePrm) { JointNlpFgExampleBuilderPrm prm = new JointNlpFgExampleBuilderPrm(); // Factor graph structure. prm.fgPrm.dpPrm.linkVarType = linkVarType; prm.fgPrm.dpPrm.useProjDepTreeFactor = useProjDepTreeFactor; prm.fgPrm.dpPrm.unaryFactors = unaryFactors; prm.fgPrm.dpPrm.excludeNonprojectiveGrandparents = excludeNonprojectiveGrandparents; prm.fgPrm.dpPrm.grandparentFactors = grandparentFactors; prm.fgPrm.dpPrm.siblingFactors = siblingFactors; prm.fgPrm.dpPrm.pruneEdges = pruneByDist || pruneByModel; prm.fgPrm.srlPrm.makeUnknownPredRolesLatent = makeUnknownPredRolesLatent; prm.fgPrm.srlPrm.roleStructure = roleStructure; prm.fgPrm.srlPrm.allowPredArgSelfLoops = allowPredArgSelfLoops; prm.fgPrm.srlPrm.unaryFactors = unaryFactors; prm.fgPrm.srlPrm.binarySenseRoleFactors = binarySenseRoleFactors; prm.fgPrm.srlPrm.predictSense = predictSense; prm.fgPrm.srlPrm.predictPredPos = predictPredPos; // Relation Feature extraction. if (CorpusHandler.getGoldOnlyAts().contains(AT.REL_LABELS)) { if (relFeatTpls != null) { prm.fgPrm.relPrm.templates = getFeatTpls(relFeatTpls); } prm.fgPrm.relPrm.featureHashMod = featureHashMod; } prm.fgPrm.includeDp = CorpusHandler.getGoldOnlyAts().contains(AT.DEP_TREE); prm.fgPrm.includeSrl = CorpusHandler.getGoldOnlyAts().contains(AT.SRL); prm.fgPrm.includeRel = CorpusHandler.getGoldOnlyAts().contains(AT.REL_LABELS); // Feature extraction. prm.fePrm = fePrm; // Example construction and storage. prm.exPrm.cacheType = cacheType; prm.exPrm.gzipped = gzipCache; prm.exPrm.maxEntriesInMemory = maxEntriesInMemory; return prm; } private static ObsFeatureConjoinerPrm getObsFeatureConjoinerPrm() { ObsFeatureConjoinerPrm prm = new ObsFeatureConjoinerPrm(); prm.featCountCutoff = featCountCutoff; prm.includeUnsupportedFeatures = includeUnsupportedFeatures; return prm; } private static JointNlpFeatureExtractorPrm getJointNlpFeatureExtractorPrm() { // SRL Feature Extraction. SrlFeatureExtractorPrm srlFePrm = new SrlFeatureExtractorPrm(); srlFePrm.fePrm.biasOnly = biasOnly; srlFePrm.fePrm.useSimpleFeats = useSimpleFeats; srlFePrm.fePrm.useNaradFeats = useNaradFeats; srlFePrm.fePrm.useZhaoFeats = useZhaoFeats; srlFePrm.fePrm.useBjorkelundFeats = useBjorkelundFeats; srlFePrm.fePrm.useLexicalDepPathFeats = useLexicalDepPathFeats; srlFePrm.fePrm.useTemplates = useTemplates; srlFePrm.fePrm.soloTemplates = getFeatTpls(senseFeatTpls); srlFePrm.fePrm.pairTemplates = getFeatTpls(argFeatTpls); srlFePrm.featureHashMod = featureHashMod; // Dependency parsing Feature Extraction DepParseFeatureExtractorPrm dpFePrm = new DepParseFeatureExtractorPrm(); dpFePrm.biasOnly = biasOnly; dpFePrm.firstOrderTpls = getFeatTpls(dp1FeatTpls); dpFePrm.secondOrderTpls = getFeatTpls(dp2FeatTpls); dpFePrm.featureHashMod = featureHashMod; if (CorpusHandler.getGoldOnlyAts().contains(AT.SRL) && acl14DepFeats) { // This special case is only for historical consistency. dpFePrm.onlyTrueBias = false; dpFePrm.onlyTrueEdges = false; } dpFePrm.onlyFast = dpFastFeats; JointNlpFeatureExtractorPrm fePrm = new JointNlpFeatureExtractorPrm(); fePrm.srlFePrm = srlFePrm; fePrm.dpFePrm = dpFePrm; return fePrm; } /** * Gets feature templates from multiple files or resources. * @param featTpls A colon separated list of paths to feature template files or resources. * @return The feature templates from all the paths. */ private static List<FeatTemplate> getFeatTpls(String featTpls) { Collection<FeatTemplate> tpls = new LinkedHashSet<FeatTemplate>(); TemplateReader tr = new TemplateReader(); for (String path : featTpls.split(":")) { if (path.equals("coarse1") || path.equals("coarse2")) { List<FeatTemplate> coarseUnigramSet; if (path.equals("coarse1")) { coarseUnigramSet = TemplateSets.getCoarseUnigramSet1(); } else if (path.equals("coarse2")) { coarseUnigramSet = TemplateSets.getCoarseUnigramSet2(); } else { throw new IllegalStateException(); } tpls.addAll(coarseUnigramSet); } else { try { tr.readFromFile(path); } catch (IOException e) { try { tr.readFromResource(path); } catch (IOException e1) { throw new IllegalStateException("Unable to read templates as file or resource: " + path, e1); } } } } tpls.addAll(tr.getTemplates()); return new ArrayList<FeatTemplate>(tpls); } private static CorpusStatisticsPrm getCorpusStatisticsPrm() { CorpusStatisticsPrm prm = new CorpusStatisticsPrm(); prm.cutoff = cutoff; prm.language = CorpusHandler.language; prm.useGoldSyntax = CorpusHandler.useGoldSyntax; prm.normalizeWords = normalizeWords; return prm; } private static CrfTrainerPrm getCrfTrainerPrm() throws ParseException { FgInferencerFactory infPrm = getInfFactory(); CrfTrainerPrm prm = new CrfTrainerPrm(); prm.infFactory = infPrm; if (infPrm instanceof BeliefsModuleFactory) { // TODO: This is a temporary hack to which assumes we always use ErmaBp. prm.bFactory = (BeliefsModuleFactory) infPrm; } if (optimizer == Optimizer.LBFGS) { prm.optimizer = getMalletLbfgs(); prm.batchOptimizer = null; } else if (optimizer == Optimizer.QN) { prm.optimizer = getStanfordLbfgs(); prm.batchOptimizer = null; } else if (optimizer == Optimizer.SGD || optimizer == Optimizer.ADAGRAD || optimizer == Optimizer.ADADELTA) { prm.optimizer = null; SGDPrm sgdPrm = getSgdPrm(); if (optimizer == Optimizer.SGD){ BottouSchedulePrm boPrm = new BottouSchedulePrm(); boPrm.initialLr = sgdInitialLr; boPrm.lambda = 1.0 / l2variance; sgdPrm.sched = new BottouSchedule(boPrm); } else if (optimizer == Optimizer.ADAGRAD){ AdaGradSchedulePrm adaGradPrm = new AdaGradSchedulePrm(); adaGradPrm.eta = adaGradEta; sgdPrm.sched = new AdaGradSchedule(adaGradPrm); } else if (optimizer == Optimizer.ADADELTA){ AdaDeltaPrm adaDeltaPrm = new AdaDeltaPrm(); adaDeltaPrm.decayRate = adaDeltaDecayRate; adaDeltaPrm.constantAddend = adaDeltaConstantAddend; sgdPrm.sched = new AdaDelta(adaDeltaPrm); sgdPrm.autoSelectLr = false; } prm.batchOptimizer = new SGD(sgdPrm); } else if (optimizer == Optimizer.FOBOS) { SGDFobosPrm sgdPrm = new SGDFobosPrm(); setSgdPrm(sgdPrm); //TODO: sgdPrm.l1Lambda = l2Lambda; sgdPrm.l2Lambda = 1.0 / l2variance; BottouSchedulePrm boPrm = new BottouSchedulePrm(); boPrm.initialLr = sgdInitialLr; boPrm.lambda = 1.0 / l2variance; sgdPrm.sched = new BottouSchedule(boPrm); prm.optimizer = null; prm.batchOptimizer = new SGDFobos(sgdPrm); } else { throw new RuntimeException("Optimizer not supported: " + optimizer); } if (regularizer == RegularizerType.L2) { prm.regularizer = new L2(l2variance); } else if (regularizer == RegularizerType.NONE) { prm.regularizer = null; } else { throw new ParseException("Unsupported regularizer: " + regularizer); } prm.numThreads = threads; prm.useMseForValue = useMseForValue; prm.trainer = trainer; // TODO: add options for other loss functions. if (prm.trainer == Trainer.ERMA && CorpusHandler.getPredAts().equals(Lists.getList(AT.DEP_TREE))) { if (dpLoss == ErmaLoss.DP_DECODE_LOSS) { DepParseDecodeLossFactory lossPrm = new DepParseDecodeLossFactory(); lossPrm.annealMse = dpAnnealMse; lossPrm.startTemp = dpStartTemp; lossPrm.endTemp = dpEndTemp; prm.dlFactory = lossPrm; } else if (dpLoss == ErmaLoss.MSE) { prm.dlFactory = new MeanSquaredErrorFactory(); } else if (dpLoss == ErmaLoss.EXPECTED_RECALL) { prm.dlFactory = new ExpectedRecallFactory(); } } return prm; } private static edu.jhu.hlt.optimize.Optimizer<DifferentiableFunction> getMalletLbfgs() { MalletLBFGSPrm prm = new MalletLBFGSPrm(); prm.maxIterations = maxLbfgsIterations; return new MalletLBFGS(prm); } private static edu.jhu.hlt.optimize.Optimizer<DifferentiableFunction> getStanfordLbfgs() { return new StanfordQNMinimizer(maxLbfgsIterations); } private static SGDPrm getSgdPrm() { SGDPrm prm = new SGDPrm(); setSgdPrm(prm); return prm; } private static void setSgdPrm(SGDPrm prm) { prm.numPasses = sgdNumPasses; prm.batchSize = sgdBatchSize; prm.withReplacement = sgdWithRepl; prm.stopBy = stopTrainingBy; prm.autoSelectLr = sgdAutoSelectLr; prm.autoSelectFreq = sgdAutoSelecFreq; prm.computeValueOnNonFinalIter = sgdComputeValueOnNonFinalIter; // Make sure we correctly set the schedule somewhere else. prm.sched = null; } private static FgInferencerFactory getInfFactory() throws ParseException { if (inference == Inference.BRUTE_FORCE) { BruteForceInferencerPrm prm = new BruteForceInferencerPrm(algebra.getAlgebra()); return prm; } else if (inference == Inference.BP) { ErmaBpPrm bpPrm = new ErmaBpPrm(); bpPrm.logDomain = logDomain; bpPrm.s = algebra.getAlgebra(); bpPrm.schedule = bpSchedule; bpPrm.updateOrder = bpUpdateOrder; bpPrm.normalizeMessages = normalizeMessages; bpPrm.maxIterations = bpMaxIterations; bpPrm.convergenceThreshold = bpConvergenceThreshold; bpPrm.keepTape = (trainer == Trainer.ERMA); if (bpDumpDir != null) { bpPrm.dumpDir = Paths.get(bpDumpDir.getAbsolutePath()); } return bpPrm; } else { throw new ParseException("Unsupported inference method: " + inference); } } private static JointNlpDecoderPrm getDecoderPrm() throws ParseException { MbrDecoderPrm mbrPrm = new MbrDecoderPrm(); mbrPrm.infFactory = getInfFactory(); mbrPrm.loss = Loss.L1; JointNlpDecoderPrm prm = new JointNlpDecoderPrm(); prm.mbrPrm = mbrPrm; return prm; } private static BrownClusterTaggerPrm getBrownCluterTaggerPrm() { BrownClusterTaggerPrm bcPrm = new BrownClusterTaggerPrm(); bcPrm.language = CorpusHandler.language; return bcPrm; } private static EmbeddingsAnnotatorPrm getEmbeddingsAnnotatorPrm() { EmbeddingsAnnotatorPrm prm = new EmbeddingsAnnotatorPrm(); prm.embeddingsFile = embeddingsFile; prm.embNorm = embNorm; prm.embScaler= embScaler; return prm; } public static void main(String[] args) { int exitCode = 0; ArgParser parser = null; try { parser = new ArgParser(JointNlpRunner.class); parser.addClass(JointNlpRunner.class); parser.addClass(CorpusHandler.class); parser.addClass(RelationsOptions.class); parser.addClass(InsideOutsideDepParse.class); parser.addClass(ReporterManager.class); parser.parseArgs(args); ReporterManager.init(ReporterManager.reportOut, true); Prng.seed(seed); JointNlpRunner pipeline = new JointNlpRunner(); pipeline.run(); } catch (ParseException e1) { log.error(e1.getMessage()); if (parser != null) { parser.printUsage(); } exitCode = 1; } catch (Throwable t) { t.printStackTrace(); exitCode = 1; } finally { ReporterManager.close(); } System.exit(exitCode); } }
package edu.mayo.ve.VCFParser; import com.mongodb.*; import edu.mayo.concurrency.exceptions.ProcessTerminatedException; import edu.mayo.concurrency.workerQueue.Task; import edu.mayo.concurrency.workerQueue.WorkerLogic; import edu.mayo.parsers.ParserInterface; import edu.mayo.util.MongoConnection; import edu.mayo.util.Tokens; import edu.mayo.ve.resources.MetaData; import edu.mayo.util.SystemProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.HashMap; public class LoadWorker implements WorkerLogic { private static final Logger logger = LoggerFactory.getLogger(LoadWorker.class); ParserInterface parser = null; private boolean deleteAfterLoad = true; private boolean logStackTrace = true; private Mongo m = MongoConnection.getMongo(); public static void main(String[] args)throws ProcessTerminatedException { VCFParser parser = new VCFParser(); LoadWorker worker = new LoadWorker(parser, 100000); Task t = new Task(); HashMap<String,String> hm = new HashMap<String,String>(); hm.put(Tokens.VCF_LOAD_FILE,"src/test/resources/testData/example.vcf"); hm.put(Tokens.KEY,"w9c3fb5f300ab5073128749de49b1ff52d4819099"); t.setCommandContext(hm); worker.compute(t); } private int theadCache; public LoadWorker(ParserInterface parser, int lookAheadCacheSize){ this.parser = parser; this.theadCache = lookAheadCacheSize; } boolean report = false; public LoadWorker(ParserInterface parser, int lookAheadCacheSize, boolean reporting){ this.parser = parser; this.theadCache = lookAheadCacheSize; this.report = reporting; } public Task compute(Task t) throws ProcessTerminatedException { //System.out.println("Started up a worker"); //In the case of a LoadWorker, the command context is a hashmap that we can get values on HashMap<String,String> context = (HashMap) t.getCommandContext(); String workspace = context.get(Tokens.KEY); String loadfile = context.get(Tokens.VCF_LOAD_FILE); MetaData meta = new MetaData(); try { long startTime = System.currentTimeMillis(); if(report) System.out.println("Setting up the mongo connection"); setMongo(); if(report) System.out.println("I am working on loading this file: " + loadfile); //change the status from queued to loading: meta.flagAsNotReady(workspace); if(report) System.out.println("Parsing the file..."); parser.parse(loadfile,workspace); //make the third to last one false in production! make the second to last one false in production! if(report) System.out.println("File loading done"); if(report) System.out.println("Checking to see if the file upload worked or failed."); HashMap<String,Integer> icontext = (HashMap) t.getCommandContext(); //need to cast this to an integer parser.checkAndUpdateLoadStatus(workspace, icontext.get(Tokens.DATA_LINE_COUNT), false); if(report) System.out.println("Running map-reduce to produce TypeAhead collection..."); createTypeAheadCollection(MongoConnection.getDB().getCollection(workspace)); if(report) System.out.println("TypeAhead collection done."); //calculate and log the processing time long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; icontext.put("TimeElapsed", (int) totalTime); //change to logger! System.out.println("__LOADTIME__ Loading to workspace: " + workspace + " LOADFILE: " + loadfile + " total time (millis): " + totalTime); //update the system's metadata with loading statistics meta.updateLoadStatistics(workspace,icontext); meta.flagAsReady(workspace); }catch(Throwable e){ //this thread is working in the background... so we need to make sure that it outputs an error if one came up // dump to server log via STDERR logger.error(e.getMessage(), e); // write stacktrace to the workspace errors log so the user can view it StringWriter stackTraceWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stackTraceWriter)); String mesg = String.format( "Internal System Error\n" + "\n" + "Validate your VCF file using vcf-validate (see http://vcftools.sourceforge.net).\n" + "If your VCF file passes validation, please send the diagnostic information below to the development team:\n" + "\n%s" ,stackTraceWriter.toString()); try { writeToErrorFile(workspace, mesg); meta.updateLoadStatistics(workspace, (HashMap) t.getCommandContext()); } catch (IOException ioe) { ioe.printStackTrace(); } meta.flagAsFailed(workspace,"The Load Failed with Exception: " + e.getMessage()); } //delete the load file if(deleteAfterLoad){ if(report) System.out.println("Now I am deleting the file"); File file = new File(loadfile); file.delete(); //t.setResultContext(new Long(sum)); //put the result in result context, if needed } return t; } public boolean isTerminated(){ return false; } /** * Writes the given mesg to the workspace errors file. * @param workspace * The workspace key. * @param mesg * The error message to write to the file. * @throws IOException */ private void writeToErrorFile(String workspace, String mesg) throws IOException { String errorFile = VCFErrorFileUtils.getLoadErrorFilePath(workspace); PrintWriter pWtr = new PrintWriter(new FileWriter(errorFile)); try { pWtr.println("ERROR: " + mesg); } finally { pWtr.close(); } } public static boolean isLoadSamples() { return loadSamples; } public static void setLoadSamples(boolean loadSamples) { LoadWorker.loadSamples = loadSamples; } public boolean isDeleteAfterLoad() { return deleteAfterLoad; } public void setDeleteAfterLoad(boolean deleteAfterLoad) { this.deleteAfterLoad = deleteAfterLoad; } private static String host = "localhost"; private static int port = 27017; private static SystemProperties sysprop = null; private static boolean loadSamples = false; public void setMongo() throws IOException { if(sysprop == null){ if(report){System.out.println("Reading sys.properties to get the configuration");} sysprop = new SystemProperties(); host = sysprop.get("mongo_server"); port = new Integer(sysprop.get("mongo_port")); //just do this at this time because we can loadSamples = new Boolean(sysprop.get("load_samples")); } //make a new MongoConnection for this worker -- let mongo take care of static references and singleton and so on if(report){System.out.println("Setting the MongoDB connection on the parser");} //Mongo m = new MongoClient(host , port); Mongo m = MongoConnection.getMongo(); parser.setM(m); // DB db = MongoConnection.getDB(); // DBCollection col = db.getCollection("meta"); // DBCursor dbc = col.find(); // while(dbc.hasNext()){ // System.out.println(dbc.next()); } public boolean isLogStackTrace() { return logStackTrace; } public void setLogStackTrace(boolean logStackTrace) { this.logStackTrace = logStackTrace; } public boolean isReport() { return report; } public void setReport(boolean report) { this.report = report; } /** * Creates a new Mongo collection for the typeahead data as a post-processing step. * * @param variantCollection The collection of variant data. */ private void createTypeAheadCollection(DBCollection variantCollection) { // The MAP produces unique keys that will be counted in the REDUCE function. // The format of the key is: // <INFO field name>|<INFO field value> // Example: // SNPEFF_GENE_NAME|AGRN // The emit() passes a value of "1" to signify 1 instance was found of this key String map = "function () {" + "for (var name in this.INFO) {" + "var value = this.INFO[name];" + "if ((typeof value == 'string' || value instanceof String) && (value != '.')) {" + "var key = name + '|' + value;" + "emit(key, 1);" + "}" + "}" + "}"; // The REDUCE simply sums the instances together into a single total (e.g. count). String reduce = "function (key, counts) {" + "return Array.sum(counts);" + "}"; // The FINALIZE parses the key into separate field and value attributes. String finalize = "function (key, reducedCount) {" + "var nameValueArray = key.split('|');" + "var typeahead = new Object();" + "typeahead.field = 'INFO.' + nameValueArray[0];" + "typeahead.value = nameValueArray[1];" + "typeahead.count = reducedCount;" + "return typeahead;" + "}"; final String typeaheadCollectionName = variantCollection.getName()+".typeahead"; MapReduceCommand cmd = new MapReduceCommand(variantCollection, map, reduce, typeaheadCollectionName, MapReduceCommand.OutputType.REPLACE, null); cmd.setFinalize(finalize); variantCollection.mapReduce(cmd); // transform the typeahead schema DBCollection typeaheadCol = MongoConnection.getDB().getCollection(typeaheadCollectionName); final DBObject grabEverythingQuery = new BasicDBObject(); // STEP 1 - rename "value" to "temp" final DBObject renameToTemp = new BasicDBObject("$rename", new BasicDBObject("value", "temp")); typeaheadCol.update(grabEverythingQuery, renameToTemp, false, true); // STEP 2 - move "temp" attributes up a level final DBObject moveUp = new BasicDBObject("$rename", new BasicDBObject("temp.field", "field").append("temp.value", "value").append("temp.count", "count")); typeaheadCol.update(grabEverythingQuery, moveUp, false, true); // STEP 3 - delete "temp" final DBObject delete = new BasicDBObject("$unset", new BasicDBObject("temp", "")); typeaheadCol.update(grabEverythingQuery, delete, false, true); } }
package edu.pitt.isg; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import edu.pitt.isg.mdc.dats2_2.*; import edu.pitt.isg.mdc.dats2_2.Date; import eu.trentorise.opendata.jackan.CkanClient; import eu.trentorise.opendata.jackan.CkanQuery; import eu.trentorise.opendata.jackan.model.CkanDataset; import eu.trentorise.opendata.jackan.model.CkanResource; import eu.trentorise.opendata.jackan.model.CkanTag; import org.apache.commons.lang.WordUtils; import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.*; public class CkanToDatsConverter { private static HashMap<String, List<String>> snomedMap; private static HashMap<String, String> ncbiMap; private static String APIKEY = "f060b29e-fc9a-4dcd-b3be-9741466dbc4a"; private static Set<String> failures; private static Set<String> blacklist; public class ConverterResult { public List<String> getDiseaseLookupLogMessages() { return diseaseLookupLogMessages; } public void setDiseaseLookupLogMessages(List<String> diseaseLookupLogMessages) { this.diseaseLookupLogMessages = diseaseLookupLogMessages; } public Object getDataset() { return dataset; } public void setDataset(Object dataset) { this.dataset = dataset; } private List<String> diseaseLookupLogMessages; private Object dataset; } public static void main(String[] args) { CkanToDatsConverter converter = new CkanToDatsConverter(); converter.manuallyAddToDiseaseCache("Spotted Fever Rickettsiosis", "186772009"); CkanClient ckanClient = new CkanClient("http://catalog.data.gov/"); CkanQuery query = CkanQuery.filter().byTagNames("nndss"); // CkanQuery query = CkanQuery.filter().byTagNames("vaccination"); // List<CkanDataset> filteredDatasets = ckanClient.searchDatasets(query, 100, 0).getResults(); // List<DatasetWithOrganization> convertedDatasets = new ArrayList<>(); // for (CkanDataset dataset : filteredDatasets) { // ConverterResult convertedDataset = new CkanToDatsConverter().convertCkanToDats(dataset, ckanClient.getCatalogUrl()); // if (convertedDataset != null) { // convertedDatasets.add((DatasetWithOrganization) convertedDataset.getDataset()); ConverterResult result = new CkanToDatsConverter().convertCkanToDats( ckanClient.getDataset("70dca0aa-1598-4925-af8c-5464fdb212b1"), ckanClient.getCatalogUrl()); System.out.println("Done"); } public ConverterResult convertCkanToDats(CkanDataset ckanDataset, String catalogUrl) { ConverterResult result = new ConverterResult(); DatasetWithOrganization dataset = new DatasetWithOrganization(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //Set Distributions List<CkanResource> resources = ckanDataset.getResources(); for (CkanResource resource : resources) { //If the resources contained in the ckan dataset are not csv, rdf, json, or xml then it is not the type we want in the MDC if (resource.getFormat().equals("CSV") || resource.getFormat().equals("RDF") || resource.getFormat().equals("JSON") || resource.getFormat().equals("XML")) { Distribution distribution = new Distribution(); distribution.getFormats().add(resource.getFormat()); Identifier distributionIdentifier = new Identifier(); distributionIdentifier.setIdentifier(resource.getId()); distributionIdentifier.setIdentifierSource(catalogUrl); distribution.setIdentifier(distributionIdentifier); Access access = new Access(); access.setAccessURL(resource.getUrl()); access.setLandingPage(ckanDataset.getExtrasAsHashMap().get("landingPage")); distribution.setAccess(access); Date date = new Date(); Annotation distributionType = new Annotation(); java.util.Date datetime = new java.util.Date(resource.getCreated().getTime()); date.setDate(sdf.format(datetime)); distributionType.setValue("creation"); distributionType.setValueIRI("http://purl.obolibrary.org/obo/GENEPIO_0001882"); date.setType(distributionType); distribution.getDates().add(date); dataset.getDistributions().add(distribution); } } //if no distributions are added then the ckan dataset is not the format we want to convert, return null if (dataset.getDistributions().isEmpty()) { return null; } dataset.setTitle(ckanDataset.getTitle()); dataset.setDescription(ckanDataset.getNotes()); //Set Creator Organization organization = new Organization(); organization.setName(ckanDataset.getExtrasAsHashMap().get("publisher")); dataset.getCreators().add(organization); //Set Identifier Identifier identifier = new Identifier(); identifier.setIdentifierSource("https://data.cdc.gov"); identifier.setIdentifier(ckanDataset.getExtrasAsHashMap().get("identifier")); dataset.setIdentifier(identifier); //Set Produced By Study study = new Study(); study.setName(ckanDataset.getExtrasAsHashMap().get("publisher")); Date modifiedDate = new Date(); Annotation type = new Annotation(); type.setValue("modified"); type.setValueIRI("http://purl.obolibrary.org/obo/GENEPIO_0001874"); modifiedDate.setDate(ckanDataset.getExtrasAsHashMap().get("modified")); modifiedDate.setType(type); study.setStartDate(modifiedDate); dataset.setProducedBy(study); //Set extraProperties CategoryValuePair createdMetaData = new CategoryValuePair(); createdMetaData.setCategory("CKAN metadata_created"); Annotation createdMetaDataAnnotation = new Annotation(); createdMetaDataAnnotation.setValue(sdf.format(ckanDataset.getMetadataCreated())); createdMetaDataAnnotation.setValueIRI("http://purl.obolibrary.org/obo/GENEPIO_0001882"); createdMetaData.getValues().add(createdMetaDataAnnotation); dataset.getExtraProperties().add(createdMetaData); if (ckanDataset.getMetadataModified() != null) { CategoryValuePair modifiedMetaData = new CategoryValuePair(); modifiedMetaData.setCategory("CKAN metadata_modified"); Annotation modifiedMetaDataAnnotation = new Annotation(); modifiedMetaDataAnnotation.setValue(sdf.format(ckanDataset.getMetadataModified())); modifiedMetaDataAnnotation.setValueIRI("http://purl.obolibrary.org/obo/GENEPIO_0001874"); modifiedMetaData.getValues().add(modifiedMetaDataAnnotation); dataset.getExtraProperties().add(modifiedMetaData); } CategoryValuePair revisionMetaData = new CategoryValuePair(); revisionMetaData.setCategory("CKAN revision_id"); Annotation revisionAnnotation = new Annotation(); revisionAnnotation.setValue(ckanDataset.getRevisionId()); revisionMetaData.getValues().add(revisionAnnotation); dataset.getExtraProperties().add(revisionMetaData); //Set isAbout List<CkanTag> tags = ckanDataset.getTags(); result.diseaseLookupLogMessages = new ArrayList<>(); for (CkanTag tag : tags) { String diseaseInfo[] = lookupIsAboutInformation(tag.getDisplayName(), result.diseaseLookupLogMessages); if (diseaseInfo != null) { BiologicalEntity entity = new BiologicalEntity(); entity.setName(diseaseInfo[0]); Identifier tagIdentifier = new Identifier(); tagIdentifier.setIdentifier(diseaseInfo[1]); tagIdentifier.setIdentifierSource(diseaseInfo[2]); entity.setIdentifier(tagIdentifier); dataset.getIsAbout().add(entity); } } writeDiseaseFile(); result.setDataset(dataset); return result; } public String[] lookupIsAboutInformation(String diseaseName, List<String> diseaseLookupLogMessages) { //Disease name, snomed or ncbi code, identifier source String diseaseInfo[] = new String[3]; //Normalize name diseaseName = diseaseName.replace("-", " "); diseaseName = WordUtils.capitalize(diseaseName); if (diseaseName.equals("Hansen039s Disease")) { diseaseName = "Hansen Disease"; } if (snomedMap == null) { snomedMap = new HashMap<>(); failures = new HashSet<>(); populateBlacklist(); populateNcbiMap(); try { InputStream file = CkanToDatsConverter.class.getClassLoader().getResourceAsStream("diseases.csv"); Scanner diseaseScan = new Scanner(file, "UTF-8"); while (diseaseScan.hasNextLine()) { String diseaseInFile = diseaseScan.nextLine(); String[] diseaseArray = diseaseInFile.split(","); if (diseaseArray.length > 1) { List<String> list = new ArrayList<>(); list.add(diseaseArray[1]); list.add(diseaseArray[2]); snomedMap.put(diseaseArray[0].trim(), list); } } diseaseScan.close(); } catch (Exception e) { e.printStackTrace(); } } //If it is a disease if (blacklist.contains(diseaseName)) { //skip diseaseInfo = null; } else if (snomedMap.containsKey(diseaseName)) { diseaseInfo[0] = diseaseName; List<String> diseaseInfoList = snomedMap.get(diseaseName); diseaseInfo[1] = diseaseInfoList.get(0); diseaseLookupLogMessages.add(diseaseInfoList.get(1)); diseaseInfo[2] = "https://biosharing.org/bsg-s000098"; } else if (ncbiMap.containsKey(diseaseName)) { diseaseInfo[0] = diseaseName; diseaseInfo[1] = ncbiMap.get(diseaseName); diseaseInfo[2] = "https://biosharing.org/bsg-s000154"; } else { try { String snomed = lookupSNOMED(diseaseName, diseaseLookupLogMessages); if (snomed != "") { List<String> diseaseInfoList = new ArrayList<>(); diseaseInfoList.add(snomed); diseaseInfoList.add(diseaseLookupLogMessages.get(diseaseLookupLogMessages.size()-1)); snomedMap.put(diseaseName, diseaseInfoList); diseaseInfo[0] = diseaseName; diseaseInfo[1] = snomed; diseaseInfo[2] = "https://biosharing.org/bsg-s000098"; } else { diseaseInfo = null; } } catch (IOException e) { diseaseInfo = null; e.printStackTrace(); } } return diseaseInfo; } public String lookupSNOMED(String diseaseName, List<String> diseaseLookupLogMessages) throws MalformedURLException, IOException { if (failures.contains(diseaseName)) { return ""; } URL url = new URL("http://data.bioontology.org/search?q=" + URLEncoder.encode(diseaseName, "UTF-8") + "&apikey=" + APIKEY); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); if (connection.getResponseCode() != 200) { diseaseLookupLogMessages.add("Failed : HTTP error code : " + connection.getResponseCode() + ". Searching with: " + diseaseName); return ""; } BufferedReader br = new BufferedReader(new InputStreamReader( (connection.getInputStream()))); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = br.readLine()) != null) { response.append(inputLine); } connection.disconnect(); JsonObject obj = new JsonParser().parse(response.toString()).getAsJsonObject(); //iterate over "collection" until we find @id with SNOMEDCT in it JsonArray collection = obj.get("collection").getAsJsonArray(); String snomed = ""; for (JsonElement member : collection) { JsonObject memberObject = member.getAsJsonObject(); String id = memberObject.get("@id").getAsString(); if (id.contains("SNOMEDCT")) { StringBuilder builder = new StringBuilder(); if (memberObject.get("synonym") != null) { for (JsonElement synonym : memberObject.get("synonym").getAsJsonArray()) { if (builder.length() > 0) { builder.append("; "); } builder.append(synonym.getAsString()); } } snomed = id.substring(id.lastIndexOf('/') + 1); System.out.println("Searching for: " + diseaseName + ". Found: " + memberObject.get("prefLabel").getAsString() + ". Synonyms are: " + builder.toString()); diseaseLookupLogMessages.add("Searching for: " + diseaseName + ". Found: " + memberObject.get("prefLabel").getAsString() + ". Synonyms are: " + builder.toString()); break; } } if (snomed.equals("")) { System.out.println("Failed to find SNOMED code for " + diseaseName); diseaseLookupLogMessages.add("Failed to find SNOMED code for " + diseaseName); failures.add(diseaseName); } return snomed; } private void writeDiseaseFile() { //This writes to the diseases.csv file in target. Copy to diseases.csv in resources to update cache StringBuilder builder = new StringBuilder(); for (Map.Entry<String, List<String>> kvp : snomedMap.entrySet()) { builder.append(kvp.getKey()); builder.append(","); builder.append(kvp.getValue().get(0)); builder.append(","); builder.append(kvp.getValue().get(1)); builder.append("\r\n"); } String content = builder.toString().trim(); try { PrintWriter writer = new PrintWriter(new File(CkanToDatsConverter.class.getClassLoader().getResource("diseases.csv").getPath())); writer.println(content); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } private void manuallyAddToDiseaseCache(String diseaseName, String snomedCode){ try { URL url = new URL("http://data.bioontology.org/search?q=" + URLEncoder.encode(snomedCode, "UTF-8") + "&apikey=" + APIKEY); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); if (connection.getResponseCode() != 200) { System.out.println("Failed : HTTP error code : " + connection.getResponseCode() + ". Searching with: " + diseaseName); return; } BufferedReader br = new BufferedReader(new InputStreamReader( (connection.getInputStream()))); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = br.readLine()) != null) { response.append(inputLine); } connection.disconnect(); JsonObject obj = new JsonParser().parse(response.toString()).getAsJsonObject(); //iterate over "collection" until we find @id with SNOMEDCT in it JsonArray collection = obj.get("collection").getAsJsonArray(); String snomed = ""; JsonObject memberObject = collection.get(0).getAsJsonObject(); StringBuilder builder = new StringBuilder(); if (memberObject.get("synonym") != null) { for (JsonElement synonym : memberObject.get("synonym").getAsJsonArray()) { if (builder.length() > 0) { builder.append("; "); } builder.append(synonym.getAsString()); } } BufferedWriter bw = new BufferedWriter(new FileWriter(CkanToDatsConverter.class.getClassLoader().getResource("diseases.csv").getPath(), true)); bw.write(diseaseName + "," + snomedCode + ",Searching for: " + diseaseName + ". Found: " + memberObject.get("prefLabel").getAsString() + ". Synonyms are: " + builder.toString()); bw.newLine(); bw.flush(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void populateNcbiMap() { ncbiMap = new HashMap<>(); ncbiMap.put("Human", "9606"); } private void populateBlacklist() { blacklist = new HashSet<>(); blacklist.add("Invasive Disease All Ages"); blacklist.add("Paralytic"); blacklist.add("Week"); blacklist.add("Undetermined"); blacklist.add("Serogroup B"); blacklist.add("Serotype B"); blacklist.add("Congenital"); blacklist.add("Nonparalytic"); blacklist.add("Perinatal Virus Infection"); blacklist.add("Surveillance"); blacklist.add("Congenital Syndrome"); blacklist.add("Unknown Serotype"); blacklist.add("By Type C"); blacklist.add("Perinatal Infection"); blacklist.add("Invasive Disease Age Lt5 Yrs"); blacklist.add("Foodborne"); blacklist.add("Other Than Toxigenic Vibrio Cholerae O1 Or O139"); blacklist.add("Age Lt5"); blacklist.add("Primary And Secondary"); blacklist.add("By Type A Amp B"); blacklist.add("Neuroinvasive And Nonneuroinvasive"); blacklist.add("Reported Diseases"); blacklist.add("All Serogroups"); blacklist.add("Non Hantavirus Pulmonary Syndrome"); blacklist.add("Unknown Serogroups"); blacklist.add("Non Congenital"); blacklist.add("All Serotypes"); blacklist.add("All Ages"); blacklist.add("Nontypeable"); blacklist.add("Other Serogroups"); blacklist.add("Non Hps"); blacklist.add("Total"); blacklist.add("Influenza Associated Pediatric Mortality"); blacklist.add("Meningococcal Disease Neisseria Meningitidis"); blacklist.add("Non B Serotype"); blacklist.add("Environmental Health"); blacklist.add("Kindergarten"); blacklist.add("Location"); blacklist.add("Child Health"); blacklist.add("San Francisco"); blacklist.add("Lifelong Learning"); blacklist.add("Statistic"); blacklist.add("Youth"); blacklist.add("Zip"); blacklist.add("Zip Code"); blacklist.add("Air Quality"); blacklist.add("Air Quality Index"); blacklist.add("Air Quality System"); blacklist.add("Caa 109 Clean Air Act Section 109"); blacklist.add("Daily 24 Hour Average Concentration"); blacklist.add("Daily Maximum 8 Hour Average Concentration"); blacklist.add("Hourly Observations"); blacklist.add("National Ambient Air Quality Standards"); blacklist.add("National Environmental Health Tracking Network"); blacklist.add("O3"); blacklist.add("Ozone Residual"); blacklist.add("Particle Pollution"); blacklist.add("Particulate Matter"); blacklist.add("Particulate Matter Pm2 5"); blacklist.add("Particulate Matter Lt 2 5 Um"); blacklist.add("Pm Fine 0 2 5 Um Stp"); blacklist.add("Pm2 5"); blacklist.add("Pm2 5 Local Conditions"); blacklist.add("Site Monitoring Data"); blacklist.add("Tracking"); blacklist.add("Tracking Network"); blacklist.add("Tracking Program"); blacklist.add("Code"); } }
package eu.lp0.cursus.ui; import java.sql.SQLException; import javax.swing.JOptionPane; import eu.lp0.cursus.db.DatabaseVersionException; import eu.lp0.cursus.util.Constants; import eu.lp0.cursus.util.Messages; class DatabaseManager { private final MainWindow win; DatabaseManager(MainWindow win) { this.win = win; } /** * Try and save the database if one is open * * @param action * text name of the action being performed * @return true if the database was saved or discarded */ boolean trySaveDatabase(String action) { if (win.getMain().isOpen() && !win.getDatabase().isSaved()) { switch (JOptionPane.showConfirmDialog(win, String.format(Messages.getString("warn.current-db-not-saved"), win.getDatabase().getName()), //$NON-NLS-1$ Constants.APP_NAME + Constants.EN_DASH + action, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE)) { case JOptionPane.YES_OPTION: if (saveDatabase()) { return win.getMain().close(); } return false; case JOptionPane.NO_OPTION: win.getDatabase().close(true); break; case JOptionPane.CANCEL_OPTION: return false; } } return true; } void newDatabase() { if (trySaveDatabase(Messages.getString("menu.file.new"))) { //$NON-NLS-1$ boolean ok = true; try { ok = win.getMain().open(); } catch (SQLException e) { // TODO log ok = false; } catch (DatabaseVersionException e) { // TODO log ok = false; } if (!ok) { JOptionPane.showMessageDialog(win, Messages.getString("err.unable-to-create-new-db"), Constants.APP_NAME, JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ } } } boolean openDatabase() { // TODO open database JOptionPane.showMessageDialog(win, Messages.getString("err.feat-not-impl"), //$NON-NLS-1$ Constants.APP_NAME + Constants.EN_DASH + Messages.getString("menu.file.open"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ return false; } boolean saveDatabase() { // TODO save database to current or new file JOptionPane.showMessageDialog(win, Messages.getString("err.feat-not-impl"), //$NON-NLS-1$ Constants.APP_NAME + Constants.EN_DASH + Messages.getString("menu.file.save"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ return false; } boolean saveAsDatabase() { // TODO save database to new file JOptionPane.showMessageDialog(win, Messages.getString("err.feat-not-impl"), //$NON-NLS-1$ Constants.APP_NAME + Constants.EN_DASH + Messages.getString("menu.file.save-as"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ return false; } void closeDatabase() { if (trySaveDatabase(Messages.getString("menu.file.close"))) { //$NON-NLS-1$ win.getMain().close(); } } }
package rres.knetminer.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static uk.ac.ebi.utils.exceptions.ExceptionUtils.buildEx; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import org.junit.BeforeClass; import org.junit.Test; import uk.ac.ebi.utils.exceptions.ExceptionUtils; import uk.ac.ebi.utils.exceptions.UnexpectedEventException; import uk.ac.ebi.utils.xml.XPathReader; public class ApiIT { private static Logger clog = LogManager.getLogger ( ApiIT.class ); private Logger log = LogManager.getLogger ( this.getClass () ); @BeforeClass public static void initialDelay () throws InterruptedException { clog.info ( "Making a pause to give the server time to initialise." ); Thread.sleep ( 10 * 1000 ); } @Test public void testCountHits () throws JSONException, IOException, URISyntaxException { testCountHits ( "seed" ); } /** * Testing indexing of accessions. */ @Test public void testCountHitsPhraseQuery () throws JSONException, IOException, URISyntaxException { testCountHits ( "cell cycle" ); } /** * Invokes /countHits with the given keyword and verifies that the result is >0. * This is used by test methods below with various keywords. */ private void testCountHits ( String keyword ) throws JSONException, IOException, URISyntaxException { String encKeyword = URLEncoder.encode ( keyword, "UTF-8" ); JSONObject js = new JSONObject ( IOUtils.toString ( new URI ( System.getProperty ( "knetminer.api.baseUrl" ) + "/aratiny/countHits?keyword=" + encKeyword ), "UTF-8" )); Stream.of ( "luceneCount", "luceneLinkedCount", "geneCount" ) .forEach ( key -> assertTrue ( "countHits for '" + keyword + "' returned a wrong result (" + key + ")!", js.getInt ( key ) > 0 ) ); } @Test public void testGenomeGrowth () { testGenome ( "growth", "ABI3" ); } @Test public void testGenomeASK7 () { testGenome ( "'AT5G14750'", "ASK7" ); } /** * This is actually run only if we're running the neo4j profile (we receive a flag by Maven, reporting that). */ @Test public void testGenomeNeo4j () { if ( !"neo4j".equals ( getMavenProfileId () ) ) { log.warn ( "Skipping test for neo4j profile-only" ); return; } testGenome ( "'Lorem ipsum dolor'", "TEST-GENE-01" ); } @Test public void testGeneFilter () { Stream.of ( "ABI3", "ABI4", "CPC", "EGL3" ) .forEach ( expectedGeneLabel -> testGenome ( "flowering FLC FT", expectedGeneLabel, "AT1G63650", "aBi?", "MYB*" ) ); } /** * Invokes {@code /genome?keyword=XXX&qtl=}, then verifies the result * (eg, geneCount is > 0, gviewer != null). * * @param expectedGeneLabel is checked against the 'gviewer' result, * to see if {@code /genome/feature/geneLabel} has the expected value. * * @param geneAccFilters (optional), the list of genes to restrict the search on. This is * the same as the "Gene List Search" box, it's case-insensitive and can contains Lucene * wildcards ('*', '?', '-'). * */ private void testGenome ( String keyword, String expectedGeneLabel, String...geneAccFilters ) { if ( geneAccFilters == null ) geneAccFilters = new String [ 0 ]; JSONObject js = invokeApi ( "genome", "keyword", keyword, "qtl", new String[0], "list", geneAccFilters ); assertTrue ( "geneCount from /genome + " + keyword + " is wrong!", js.getInt ( "geneCount" ) > 0 ); String xmlView = js.getString ( "gviewer" ); assertNotNull ( "gviewer from /genome + " + keyword + " is null!", xmlView ); XPathReader xpath = new XPathReader ( xmlView ); assertNotNull ( "Gene " + expectedGeneLabel + " not returned by /genome", xpath.readString ( "/genome/feature[./label = '" + expectedGeneLabel + "']" ) ); } /** * Defaults to true * * @param callName * @param jsonFields * @return */ public static JSONObject invokeApi ( String urlOrCallName, Object... jsonFields ) { return invokeApiFailOpt ( urlOrCallName, true, jsonFields ); } public static JSONObject invokeApiFailOpt ( String urlOrCallName, boolean failOnError, Object... jsonFields ) { String url = urlOrCallName.startsWith ( "http: ? urlOrCallName : System.getProperty ( "knetminer.api.baseUrl" ) + "/aratiny/" + urlOrCallName; try { JSONObject js = new JSONObject (); for ( int i = 0; i < jsonFields.length; i++ ) js.put ( (String) jsonFields [ i ], jsonFields [ ++i ] ); HttpPost post = new HttpPost ( url ); StringEntity jsEntity = new StringEntity( js.toString (), ContentType.APPLICATION_JSON ); post.setEntity ( jsEntity ); HttpClient client = HttpClientBuilder.create ().build (); HttpResponse response = client.execute ( post ); int httpCode = response.getStatusLine ().getStatusCode (); if ( httpCode != 200 ) { if ( failOnError ) ExceptionUtils.throwEx ( HttpException.class, "Http response code %s is not 200", Integer.valueOf ( httpCode ) ); clog.warn ( "Return code for {} is {}", url, httpCode ); } String jsStr = IOUtils.toString ( response.getEntity ().getContent (), "UTF-8" ); clog.info ( "JSON got from <{}>:\n{}", url, jsStr ); return new JSONObject ( jsStr ); } catch ( JSONException | IOException | HttpException ex ) { throw buildEx ( UnexpectedEventException.class, "Error while invoking <%s>: %s", url, ex.getMessage () ); } } @Test public void testBadCallError () { JSONObject js = invokeApiFailOpt ( "foo", false ); assertEquals ( "Bad type for the /foo call!", "org.springframework.web.client.HttpClientErrorException", js.getString ( "type" ) ); assertEquals ( "Bad status for the /foo call!", 400, js.getInt ( "status" ) ); assertTrue ( "Bad title for the /foo call!", js.getString ( "title" ).contains ( "Bad API call 'foo'" ) ); assertEquals ( "Bad path for the /foo call!", System.getProperty ( "knetminer.api.baseUrl" ) + "/aratiny/foo", js.getString ( "path" ) ); assertTrue ( "Bad detail for the /foo call!", js.getString ( "detail" ).contains ( "KnetminerServer.handle(KnetminerServer" ) ); assertEquals ( "Bad statusReasonPhrase for the /foo call!", "Bad Request", js.getString ( "statusReasonPhrase" ) ); } @Test public void testBadParametersCallError () { JSONObject js = invokeApiFailOpt ( "countHits", false, "keyword", "*" ); log.info ( "JSON from bad parameter API:\n{}", js.toString () ); assertEquals ( "Bad type for the /countHits call!", "java.lang.RuntimeException", js.getString ( "type" ) ); assertEquals ( "Bad status for the /countHits call!", 500, js.getInt ( "status" ) ); assertTrue ( "Bad title for the /countHits call!", js.getString ( "title" ) .contains ( "Application error while running the API call 'countHits': " + "Internal error while searchin over Ondex index: Cannot parse '*': '*' or '?' not allowed " + "as first character in WildcardQuery" ) ); assertEquals ( "Bad path for the /countHits call!", System.getProperty ( "knetminer.api.baseUrl" ) + "/aratiny/countHits", js.getString ( "path" ) ); assertTrue ( "Bad detail for the /countHits call!", js.getString ( "detail" ).contains ( "classic.QueryParserBase.parse" ) ); assertEquals ( "Bad statusReasonPhrase for the /countHits call!", "Internal Server Error", js.getString ( "statusReasonPhrase" ) ); } @Test public void testForbiddenEx () { // in this mode it might return a regular answer, not an error if ( "console".equals ( getMavenProfileId () ) ) return; String url = System.getProperty ( "knetminer.api.baseUrl" ) + "/cydebug/traverser/report"; JSONObject js = invokeApiFailOpt ( url, false ); assertEquals ( "Bad type for the /cydebug call!", "rres.knetminer.datasource.server.CypherDebuggerService$ForbiddenException", js.getString ( "type" ) ); assertEquals ( "Bad status for the /cydebug call!", 403, js.getInt ( "status" ) ); assertTrue ( "Bad title for the /cydebug call!", js.getString ( "title" ).contains ( "Unauthorized. Knetminer must be built with knetminer.backend.cypherDebugger.enabled for this to work" ) ); assertEquals ( "Bad path for the /cydebug call!", url, js.getString ( "path" ) ); assertTrue ( "Bad detail for the /cydebug call!", js.getString ( "detail" ).contains ( "ForbiddenException: Unauthorized. Knetminer must be built with knetminer.backend" ) ); assertEquals ( "Bad statusReasonPhrase for the /cydebug call!", "Forbidden", js.getString ( "statusReasonPhrase" ) ); } /** * It's a pseudo-test that works with the 'run' profile. It just stops the Maven build at the integration-test phase, * so that the test Jetty server is kept on for manual inspection. * * See the POM for details. */ @Test public void blockingPseudoTest () throws IOException { if ( !"console".equals ( getMavenProfileId () ) ) return; log.info ( "\n\n\n\t======= SERVER RUNNING MODE, Press [Enter] key to shutdown =======\n\n" ); log.info ( "The API should be available at " + System.getProperty ( "knetminer.api.baseUrl" ) + "/aratiny/" ); log.info ( "NOTE: DON'T use Ctrl-C to stop the hereby process, I need to run proper shutdown" ); System.in.read (); } /** * Using a property set by it, returns the current profile in use. * This is used by tests like {@link #blockingPseudoTest()} to establish * what to do. */ public static String getMavenProfileId () { String neoPropType = "maven.profileId"; String result = System.getProperty ( neoPropType, null ); assertNotNull ( "Property '" + neoPropType + "' is null! It must be set on Maven and failsafe plugin", result ); return result; } }
package hu.mcp2200.impl; import hu.mcp2200.IMCP2200Connection; import hu.mcp2200.IMCP2200Device; import hu.mcp2200.MCP2200Configuration; import hu.mcp2200.MCP2200Exception; import hu.mcp2200.MCP2200JNI; /** * @author balazs.grill * */ public class MCP2200Connection implements IMCP2200Connection { private final int connectionID; private final MCP2200Device device; /** * @throws MCP2200Exception * */ public MCP2200Connection(MCP2200Device device) throws MCP2200Exception { this.device = device; this.connectionID = MCP2200JNI.getInstance().connect(device.getIndex()); if (this.connectionID < 0) throw new MCP2200Exception(connectionID); } /* (non-Javadoc) * @see hu.mcp2200.api.IMCP2200Connection#dispose() */ @Override public void dispose() { MCP2200JNI.getInstance().disconnect(connectionID); } @Override public void configure(MCP2200Configuration configuration) throws MCP2200Exception { int r = MCP2200JNI.getInstance().hid_configure( connectionID, configuration.get_IO_map(), configuration.get_config_alt_pins(), configuration.get_default_IO_map(), configuration.get_config_alt_options(), configuration.getBaud()); if (r != 0) throw new MCP2200Exception(r); } @Override public void setPin(int pin) throws MCP2200Exception { int set_bmap = (1<<pin)&0xFF; int r = MCP2200JNI.getInstance().hid_set_clear_output(connectionID, set_bmap, 0); if (r != 0) throw new MCP2200Exception(r); } @Override public void clearPin(int pin) throws MCP2200Exception { int clr_bmap = (1<<pin)&0xFF; int r = MCP2200JNI.getInstance().hid_set_clear_output(connectionID, 0, clr_bmap); if (r != 0) throw new MCP2200Exception(r); } @Override public void writeEEPROM(int address, int value) throws MCP2200Exception { int r = MCP2200JNI.getInstance().hid_write_ee(connectionID, address&0xFF, value&0xFF); if (r != 0) throw new MCP2200Exception(r); } @Override public int readEEPROM(int address) throws MCP2200Exception { int r = MCP2200JNI.getInstance().hid_read_ee(connectionID, address&0xFF); if (r < 0) throw new MCP2200Exception(r); return r&0xFF; } @Override public IMCP2200Device getDevice() { return device; } }
package grupp14.IV1201.view; import grupp14.IV1201.DTO.PersonDTO; import grupp14.IV1201.controller.ControllerEJB; import grupp14.IV1201.util.ValidEmail; import java.io.IOException; import java.io.Serializable; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.validation.constraints.Size; /** * RegisterBean that handles requests for creation of users * @author marcelmattsson */ @Named(value = "registerBean") @RequestScoped public class RegisterBean implements Serializable { @EJB ControllerEJB contr; @Size(min=1, message="You need to enter a name") private String name; @Size(min=1, message="You need to enter a surname") private String surname; private String ssn; @ValidEmail private String email; @Size(min=2, max=16, message="username needs to be between" + " 2 and 16 characters long") private String username; @Size(min=6, max=16, message="Password needs to be between" + " 6 and 16 characters long") private String password; private String roll_id; public RegisterBean(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getSsn() { return ssn; } public void setSsn(String ssn) { this.ssn = ssn; } public String getEmail() { return email; } public void setEmail(String mail) { this.email = mail; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRoll_id() { return roll_id; } public void setRoll_id(String roll_id) { this.roll_id = roll_id; } public void register() throws IOException{ ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); PersonDTO person = new PersonDTO(name,surname,ssn,email,username,password, "applicant"); boolean valid = contr.validateRegistration(username); if (valid) { contr.registerUser(person); externalContext.redirect(externalContext.getRequestContextPath() + "/index.xhtml"); } else externalContext.redirect(externalContext.getRequestContextPath() + "/registererror.xhtml"); } private void clear(){ name = ""; surname = ""; ssn = ""; email = ""; password=""; username =""; } }
package hudson.plugins.ec2; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import hudson.util.Secret; import jenkins.model.Jenkins; import jenkins.slaves.iterators.api.NodeIterator; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.*; import hudson.Extension; import hudson.Util; import hudson.model.*; import hudson.model.Descriptor.FormException; import hudson.model.labels.LabelAtom; import hudson.plugins.ec2.util.DeviceMappingParser; import hudson.util.FormValidation; import hudson.util.ListBoxModel; /** * Template of {@link EC2AbstractSlave} to launch. * * @author Kohsuke Kawaguchi */ public class SlaveTemplate implements Describable<SlaveTemplate> { private static final Logger LOGGER = Logger.getLogger(SlaveTemplate.class.getName()); public String ami; public final String description; public final String zone; public final SpotConfiguration spotConfig; public final String securityGroups; public final String remoteFS; public final InstanceType type; public final boolean ebsOptimized; public final String labels; public final Node.Mode mode; public final String initScript; public final String tmpDir; public final String userData; public final String numExecutors; public final String remoteAdmin; public final String jvmopts; public final String subnetId; public final String idleTerminationMinutes; public final String iamInstanceProfile; public final boolean useEphemeralDevices; public final String customDeviceMapping; public int instanceCap; public final boolean stopOnTerminate; private final List<EC2Tag> tags; public final boolean usePrivateDnsName; public final boolean associatePublicIp; protected transient EC2Cloud parent; public final boolean useDedicatedTenancy; public AMITypeData amiType; public int launchTimeout; public boolean connectBySSHProcess; public final boolean connectUsingPublicIp; private transient/* almost final */Set<LabelAtom> labelSet; private transient/* almost final */Set<String> securityGroupSet; /* * Necessary to handle reading from old configurations. The UnixData object is created in readResolve() */ @Deprecated public transient String sshPort; @Deprecated public transient String rootCommandPrefix; @DataBoundConstructor public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess, boolean connectUsingPublicIp) { this.ami = ami; this.zone = zone; this.spotConfig = spotConfig; this.securityGroups = securityGroups; this.remoteFS = remoteFS; this.amiType = amiType; this.type = type; this.ebsOptimized = ebsOptimized; this.labels = Util.fixNull(labelString); this.mode = mode; this.description = description; this.initScript = initScript; this.tmpDir = tmpDir; this.userData = userData; this.numExecutors = Util.fixNull(numExecutors).trim(); this.remoteAdmin = remoteAdmin; this.jvmopts = jvmopts; this.stopOnTerminate = stopOnTerminate; this.subnetId = subnetId; this.tags = tags; this.idleTerminationMinutes = idleTerminationMinutes; this.usePrivateDnsName = usePrivateDnsName; this.associatePublicIp = associatePublicIp; this.connectUsingPublicIp = connectUsingPublicIp; this.useDedicatedTenancy = useDedicatedTenancy; this.connectBySSHProcess = connectBySSHProcess; if (null == instanceCapStr || instanceCapStr.isEmpty()) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } try { this.launchTimeout = Integer.parseInt(launchTimeoutStr); } catch (NumberFormatException nfe) { this.launchTimeout = Integer.MAX_VALUE; } this.iamInstanceProfile = iamInstanceProfile; this.useEphemeralDevices = useEphemeralDevices; this.customDeviceMapping = customDeviceMapping; readResolve(); // initialize } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, false); } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, false); } /** * Backward compatible constructor for reloading previous version data */ public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, String sshPort, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, String launchTimeoutStr) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, new UnixData(rootCommandPrefix, sshPort), jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, false, launchTimeoutStr, false, null); } public boolean isConnectBySSHProcess() { // See // src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-connectBySSHProcess.html return connectBySSHProcess; } public EC2Cloud getParent() { return parent; } public String getLabelString() { return labels; } public Node.Mode getMode() { return mode; } public String getDisplayName() { return description + " (" + ami + ")"; } String getZone() { return zone; } public String getSecurityGroupString() { return securityGroups; } public Set<String> getSecurityGroupSet() { return securityGroupSet; } public Set<String> parseSecurityGroups() { if (securityGroups == null || "".equals(securityGroups.trim())) { return Collections.emptySet(); } else { return new HashSet<String>(Arrays.asList(securityGroups.split("\\s*,\\s*"))); } } public int getNumExecutors() { try { return Integer.parseInt(numExecutors); } catch (NumberFormatException e) { return EC2AbstractSlave.toNumExecutors(type); } } public int getSshPort() { try { String sshPort = ""; if (amiType.isUnix()) { sshPort = ((UnixData) amiType).getSshPort(); } return Integer.parseInt(sshPort); } catch (NumberFormatException e) { return 22; } } public String getRemoteAdmin() { return remoteAdmin; } public String getRootCommandPrefix() { return amiType.isUnix() ? ((UnixData) amiType).getRootCommandPrefix() : ""; } public String getSubnetId() { return subnetId; } public boolean getAssociatePublicIp() { return associatePublicIp; } public boolean isConnectUsingPublicIp() { return connectUsingPublicIp; } public List<EC2Tag> getTags() { if (null == tags) return null; return Collections.unmodifiableList(tags); } public String getidleTerminationMinutes() { return idleTerminationMinutes; } public boolean getUseDedicatedTenancy() { return useDedicatedTenancy; } public Set<LabelAtom> getLabelSet() { return labelSet; } public String getAmi() { return ami; } public void setAmi(String ami) { this.ami = ami; } public int getInstanceCap() { return instanceCap; } public String getInstanceCapStr() { if (instanceCap == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(instanceCap); } } public String getSpotMaxBidPrice() { if (spotConfig == null) return null; return SpotConfiguration.normalizeBid(spotConfig.spotMaxBidPrice); } public String getIamInstanceProfile() { return iamInstanceProfile; } enum ProvisionOptions { ALLOW_CREATE, FORCE_CREATE } /** * Provisions a new EC2 slave or starts a previously stopped on-demand instance. * * @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}. */ public EC2AbstractSlave provision(TaskListener listener, Label requiredLabel, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { if (this.spotConfig != null) { if (provisionOptions.contains(ProvisionOptions.ALLOW_CREATE) || provisionOptions.contains(ProvisionOptions.FORCE_CREATE)) return provisionSpot(listener); return null; } return provisionOndemand(listener, requiredLabel, provisionOptions); } /** * Determines whether the AMI of the given instance matches the AMI of template and has the required label (if requiredLabel is non-null) */ private boolean checkInstance(PrintStream logger, Instance existingInstance, Label requiredLabel, EC2AbstractSlave[] returnNode) { logProvision(logger, "checkInstance: " + existingInstance); if (StringUtils.isNotBlank(getIamInstanceProfile())) { if (existingInstance.getIamInstanceProfile() != null) { if (!existingInstance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) { logProvision(logger, " false - IAM Instance profile does not match"); return false; } // Match, fall through } else { logProvision(logger, " false - Null IAM Instance profile"); return false; } } if (existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.Terminated.toString()) || existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.ShuttingDown.toString())) { logProvision(logger, " false - Instance is terminated or shutting down"); return false; } // See if we know about this and it has capacity for (EC2AbstractSlave node : NodeIterator.nodes(EC2AbstractSlave.class)) { if (node.getInstanceId().equals(existingInstance.getInstanceId())) { logProvision(logger, "Found existing corresponding Jenkins slave: " + node.getInstanceId()); if (!node.toComputer().isPartiallyIdle()) { logProvision(logger, " false - Node is not partially idle"); return false; } // REMOVEME - this was added to force provision to work, but might not allow // stopped instances to be found - need to investigate further else if (false && node.toComputer().isOffline()) { logProvision(logger, " false - Node is offline"); return false; } else if (requiredLabel != null && !requiredLabel.matches(node.getAssignedLabels())) { logProvision(logger, " false - we need a Node having label " + requiredLabel); return false; } else { logProvision(logger, " true - Node has capacity - can use it"); returnNode[0] = node; return true; } } } logProvision(logger, " true - Instance has no node, but can be used"); return true; } private static void logProvision(PrintStream logger, String message) { logger.println(message); LOGGER.fine(message); } private static void logProvisionInfo(PrintStream logger, String message) { logger.println(message); LOGGER.info(message); } /** * Provisions an On-demand EC2 slave by launching a new instance or starting a previously-stopped instance. */ private EC2AbstractSlave provisionOndemand(TaskListener listener, Label requiredLabel, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logProvisionInfo(logger, "Considering launching " + ami + " for template " + description); KeyPair keyPair = getKeyPair(ec2); RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); riRequest.setEbsOptimized(ebsOptimized); if (useEphemeralDevices) { setupEphemeralDeviceMapping(riRequest); } else { setupCustomDeviceMapping(riRequest); } if(stopOnTerminate){ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Stop); logProvisionInfo(logger, "Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Stop"); }else{ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate); logProvisionInfo(logger, "Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Terminate"); } List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); if (getUseDedicatedTenancy()) { placement.setTenancy("dedicated"); } riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } else { riRequest.setSubnetId(getSubnetId()); } diFilters.add(new Filter("subnet-id").withValues(getSubnetId())); /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { riRequest.setSecurityGroupIds(groupIds); } diFilters.add(new Filter("instance.group-id").withValues(groupIds)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (!securityGroupSet.isEmpty()) { diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet)); } } String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8)); riRequest.setUserData(userDataString); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); riRequest.setInstanceType(type.toString()); diFilters.add(new Filter("instance-type").withValues(type.toString())); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); riRequest.withNetworkInterfaces(net); } boolean hasCustomTypeTag = false; HashSet<Tag> instTags = null; if (tags != null && !tags.isEmpty()) { instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); diFilters.add(new Filter("tag:" + t.getName()).withValues(t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { if (instTags == null) { instTags = new HashSet<Tag>(); } // Append template description as well to identify slaves provisioned per template instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue( EC2Cloud.EC2_SLAVE_TYPE_DEMAND, description))); } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diRequest.setFilters(diFilters); logProvision(logger, "Looking for existing instances with describe-instance: " + diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); EC2AbstractSlave[] ec2Node = new EC2AbstractSlave[1]; Instance existingInstance = null; if (!provisionOptions.contains(ProvisionOptions.FORCE_CREATE)) { reservationLoop: for (Reservation reservation : diResult.getReservations()) { for (Instance instance : reservation.getInstances()) { if (checkInstance(logger, instance, requiredLabel, ec2Node)) { existingInstance = instance; logProvision(logger, "Found existing instance: " + existingInstance + ((ec2Node[0] != null) ? (" node: " + ec2Node[0].getInstanceId()) : "")); break reservationLoop; } } } } if (existingInstance == null) { if (!provisionOptions.contains(ProvisionOptions.FORCE_CREATE) && !provisionOptions.contains(ProvisionOptions.ALLOW_CREATE)) { logProvision(logger, "No existing instance found - but cannot create new instance"); return null; } if (StringUtils.isNotBlank(getIamInstanceProfile())) { riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } // Have to create a new instance Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0); /* Now that we have our instance, we can set tags on it */ if (instTags != null) { updateRemoteTags(ec2, instTags, "InvalidInstanceID.NotFound", inst.getInstanceId()); // That was a remote request - we should also update our // local instance data. inst.setTags(instTags); } logProvisionInfo(logger, "No existing instance found - created new instance: " + inst); return newOndemandSlave(inst); } if (existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopping.toString()) || existingInstance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopped.toString())) { List<String> instances = new ArrayList<String>(); instances.add(existingInstance.getInstanceId()); StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logProvisionInfo(logger, "Found stopped instance - starting it: " + existingInstance + " result:" + siResult); } else { // Should be pending or running at this point, just let it come up logProvisionInfo(logger, "Found existing pending or running: " + existingInstance.getState().getName() + " instance: " + existingInstance); } if (ec2Node[0] != null) { logProvisionInfo(logger, "Using existing slave: " + ec2Node[0].getInstanceId()); return ec2Node[0]; } // Existing slave not found logProvision(logger, "Creating new slave for existing instance: " + existingInstance); return newOndemandSlave(existingInstance); } catch (FormException e) { throw new AssertionError(e); // we should have discovered all // configuration issues upfront } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } private List<BlockDeviceMapping> getNewEphemeralDeviceMapping() { final List<BlockDeviceMapping> oldDeviceMapping = getAmiBlockDeviceMappings(); final Set<String> occupiedDevices = new HashSet<String>(); for (final BlockDeviceMapping mapping : oldDeviceMapping) { occupiedDevices.add(mapping.getDeviceName()); } final List<String> available = new ArrayList<String>( Arrays.asList("ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3")); final List<BlockDeviceMapping> newDeviceMapping = new ArrayList<BlockDeviceMapping>(4); for (char suffix = 'b'; suffix <= 'z' && !available.isEmpty(); suffix++) { final String deviceName = String.format("/dev/xvd%s", suffix); if (occupiedDevices.contains(deviceName)) continue; final BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(deviceName).withVirtualName( available.get(0)); newDeviceMapping.add(newMapping); available.remove(0); } return newDeviceMapping; } private void setupEphemeralDeviceMapping(RunInstancesRequest riRequest) { riRequest.withBlockDeviceMappings(getNewEphemeralDeviceMapping()); } private void setupEphemeralDeviceMapping(LaunchSpecification launchSpec) { launchSpec.withBlockDeviceMappings(getNewEphemeralDeviceMapping()); } private List<BlockDeviceMapping> getAmiBlockDeviceMappings() { for (final Image image : getParent().connect().describeImages().getImages()) { if (ami.equals(image.getImageId())) { return image.getBlockDeviceMappings(); } } throw new AmazonClientException("Unable to get AMI device mapping for " + ami); } private void setupCustomDeviceMapping(RunInstancesRequest riRequest) { if (StringUtils.isNotBlank(customDeviceMapping)) { riRequest.setBlockDeviceMappings(DeviceMappingParser.parse(customDeviceMapping)); } } private void setupCustomDeviceMapping(LaunchSpecification launchSpec) { if (StringUtils.isNotBlank(customDeviceMapping)) { launchSpec.setBlockDeviceMappings(DeviceMappingParser.parse(customDeviceMapping)); } } /** * Provision a new slave for an EC2 spot instance to call back to Jenkins */ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Launching " + ami + " for template " + description); LOGGER.info("Launching " + ami + " for template " + description); KeyPair keyPair = getKeyPair(ec2); RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest(); // Validate spot bid before making the request if (getSpotMaxBidPrice() == null) { // throw new FormException("Invalid Spot price specified: " + // getSpotMaxBidPrice(), "spotMaxBidPrice"); throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice()); } spotRequest.setSpotPrice(getSpotMaxBidPrice()); spotRequest.setInstanceCount(1); LaunchSpecification launchSpecification = new LaunchSpecification(); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); launchSpecification.setImageId(ami); launchSpecification.setInstanceType(type); launchSpecification.setEbsOptimized(ebsOptimized); if (StringUtils.isNotBlank(getZone())) { SpotPlacement placement = new SpotPlacement(getZone()); launchSpecification.setPlacement(placement); } if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } else { launchSpecification.setSubnetId(getSubnetId()); } /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>(); for (String group_id : groupIds) { GroupIdentifier group = new GroupIdentifier(); group.setGroupId(group_id); groups.add(group); } if (!groups.isEmpty()) launchSpecification.setAllSecurityGroups(groups); } } } } else { /* No subnet: we can use standard security groups by name */ if (!securityGroupSet.isEmpty()) { launchSpecification.setSecurityGroups(securityGroupSet); } } String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8)); launchSpecification.setUserData(userDataString); launchSpecification.setKeyName(keyPair.getKeyName()); launchSpecification.setInstanceType(type.toString()); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); launchSpecification.withNetworkInterfaces(net); } boolean hasCustomTypeTag = false; HashSet<Tag> instTags = null; if (tags != null && !tags.isEmpty()) { instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { if (instTags != null) instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue( EC2Cloud.EC2_SLAVE_TYPE_SPOT, description))); } if (StringUtils.isNotBlank(getIamInstanceProfile())) { launchSpecification.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } if (useEphemeralDevices) { setupEphemeralDeviceMapping(launchSpecification); } else { setupCustomDeviceMapping(launchSpecification); } spotRequest.setLaunchSpecification(launchSpecification); // Make the request for a new Spot instance RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest); List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests(); if (reqInstances.isEmpty()) { throw new AmazonClientException("No spot instances found"); } SpotInstanceRequest spotInstReq = reqInstances.get(0); if (spotInstReq == null) { throw new AmazonClientException("Spot instance request is null"); } String slaveName = spotInstReq.getSpotInstanceRequestId(); /* Now that we have our Spot request, we can set tags on it */ if (instTags != null) { updateRemoteTags(ec2, instTags, "InvalidSpotInstanceRequestID.NotFound", spotInstReq.getSpotInstanceRequestId()); // That was a remote request - we should also update our local // instance data. spotInstReq.setTags(instTags); } logger.println("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId()); LOGGER.info("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId()); return newSpotSlave(spotInstReq, slaveName); } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } protected EC2OndemandSlave newOndemandSlave(Instance inst) throws FormException, IOException { return new EC2OndemandSlave(inst.getInstanceId(), description, remoteFS, getNumExecutors(), labels, mode, initScript, tmpDir, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, inst.getPublicDnsName(), inst.getPrivateDnsName(), EC2Tag.fromAmazonTags(inst.getTags()), parent.name, usePrivateDnsName, useDedicatedTenancy, getLaunchTimeout(), amiType); } protected EC2SpotSlave newSpotSlave(SpotInstanceRequest sir, String name) throws FormException, IOException { return new EC2SpotSlave(name, sir.getSpotInstanceRequestId(), description, remoteFS, getNumExecutors(), mode, initScript, tmpDir, labels, remoteAdmin, jvmopts, idleTerminationMinutes, EC2Tag.fromAmazonTags(sir.getTags()), parent.name, usePrivateDnsName, getLaunchTimeout(), amiType); } /** * Get a KeyPair from the configured information for the slave template */ private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException { KeyPair keyPair = parent.getPrivateKey().find(ec2); if (keyPair == null) { throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?"); } return keyPair; } /** * Update the tags stored in EC2 with the specified information. Re-try 5 times if instances isn't up by * catchErrorCode - e.g. InvalidSpotInstanceRequestID.NotFound or InvalidInstanceRequestID.NotFound * * @param ec2 * @param instTags * @param catchErrorCode * @param params * @throws InterruptedException */ private void updateRemoteTags(AmazonEC2 ec2, Collection<Tag> instTags, String catchErrorCode, String... params) throws InterruptedException { for (int i = 0; i < 5; i++) { try { CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(params).setTags(instTags); ec2.createTags(tagRequest); break; } catch (AmazonServiceException e) { if (e.getErrorCode().equals(catchErrorCode)) { Thread.sleep(5000); continue; } LOGGER.log(Level.SEVERE, e.getErrorMessage(), e); } } } /** * Get a list of security group ids for the slave */ private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException { List<String> groupIds = new ArrayList<String>(); DescribeSecurityGroupsResult groupResult = getSecurityGroupsBy("group-name", securityGroupSet, ec2); if (groupResult.getSecurityGroups().size() == 0) { groupResult = getSecurityGroupsBy("group-id", securityGroupSet, ec2); } for (SecurityGroup group : groupResult.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getSubnetId())); DescribeSubnetsRequest subnetReq = new DescribeSubnetsRequest(); subnetReq.withFilters(filters); DescribeSubnetsResult subnetResult = ec2.describeSubnets(subnetReq); List<Subnet> subnets = subnetResult.getSubnets(); if (subnets != null && !subnets.isEmpty()) { groupIds.add(group.getGroupId()); } } } if (securityGroupSet.size() != groupIds.size()) { throw new AmazonClientException("Security groups must all be VPC security groups to work in a VPC context"); } return groupIds; } private DescribeSecurityGroupsResult getSecurityGroupsBy(String filterName, Set<String> filterValues, AmazonEC2 ec2) { DescribeSecurityGroupsRequest groupReq = new DescribeSecurityGroupsRequest(); groupReq.withFilters(new Filter(filterName).withValues(filterValues)); return ec2.describeSecurityGroups(groupReq); } /** * Provisions a new EC2 slave based on the currently running instance on EC2, instead of starting a new one. */ public EC2AbstractSlave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Attaching to " + instanceId); LOGGER.info("Attaching to " + instanceId); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(Collections.singletonList(instanceId)); Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0); return newOndemandSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } } /** * Initializes data structure that we don't persist. */ protected Object readResolve() { labelSet = Label.parse(labels); securityGroupSet = parseSecurityGroups(); /** * In releases of this plugin prior to 1.18, template-specific instance caps could be configured but were not * enforced. As a result, it was possible to have the instance cap for a template be configured to 0 (zero) with * no ill effects. Starting with version 1.18, template-specific instance caps are enforced, so if a * configuration has a cap of zero for a template, no instances will be launched from that template. Since there * is no practical value of intentionally setting the cap to zero, this block will override such a setting to a * value that means 'no cap'. */ if (instanceCap == 0) { instanceCap = Integer.MAX_VALUE; } if (amiType == null) { amiType = new UnixData(rootCommandPrefix, sshPort); } return this; } public Descriptor<SlaveTemplate> getDescriptor() { return Jenkins.getInstance().getDescriptor(getClass()); } public int getLaunchTimeout() { return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout; } public String getLaunchTimeoutStr() { if (launchTimeout == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(launchTimeout); } } public boolean isWindowsSlave() { return amiType.isWindows(); } public boolean isUnixSlave() { return amiType.isUnix(); } public Secret getAdminPassword() { return amiType.isWindows() ? ((WindowsData) amiType).getPassword() : Secret.fromString(""); } public boolean isUseHTTPS() { return amiType.isWindows() && ((WindowsData) amiType).isUseHTTPS(); } @Extension public static final class DescriptorImpl extends Descriptor<SlaveTemplate> { @Override public String getDisplayName() { return null; } public List<Descriptor<AMITypeData>> getAMITypeDescriptors() { return Jenkins.getInstance().<AMITypeData, Descriptor<AMITypeData>> getDescriptorList(AMITypeData.class); } /** * Since this shares much of the configuration with {@link EC2Computer}, check its help page, too. */ @Override public String getHelpFile(String fieldName) { String p = super.getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName); return p; } /*** * Check that the AMI requested is available in the cloud and can be used. */ public FormValidation doValidateAmi(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String ec2endpoint, @QueryParameter String region, final @QueryParameter String ami) throws IOException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2; if (region != null) { ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); } else { ec2 = EC2Cloud.connect(credentialsProvider, new URL(ec2endpoint)); } if (ec2 != null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); DescribeImagesRequest request = new DescribeImagesRequest(); request.setImageIds(images); request.setOwners(owners); request.setExecutableUsers(users); List<Image> img = ec2.describeImages(request).getImages(); if (img == null || img.isEmpty()) { // de-registered AMI causes an empty list to be // returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: " + ami); } String ownerAlias = img.get(0).getImageOwnerAlias(); return FormValidation.ok(img.get(0).getImageLocation() + (ownerAlias != null ? " by " + ownerAlias : "")); } catch (AmazonClientException e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test } public FormValidation doCheckLabelString(@QueryParameter String value, @QueryParameter Node.Mode mode) { if (mode == Node.Mode.EXCLUSIVE && (value == null || value.trim().isEmpty())) { return FormValidation.warning("You may want to assign labels to this node;" + " it's marked to only run jobs that are exclusively tied to itself or a label."); } return FormValidation.ok(); } public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= -59) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Idle Termination time must be a greater than -59 (or null)"); } public FormValidation doCheckInstanceCapStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val > 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("InstanceCap must be a non-negative integer (or null)"); } public FormValidation doCheckLaunchTimeoutStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Launch Timeout must be a non-negative integer (or null)"); } public ListBoxModel doFillZoneItems(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region) throws IOException, ServletException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); return EC2AbstractSlave.fillZoneItems(credentialsProvider, region); } /* * Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001 */ public FormValidation doCheckSpotMaxBidPrice(@QueryParameter String spotMaxBidPrice) { if (SpotConfiguration.normalizeBid(spotMaxBidPrice) != null) { return FormValidation.ok(); } return FormValidation.error("Not a correct bid price"); } // Retrieve the availability zones for the region private ArrayList<String> getAvailabilityZones(AmazonEC2 ec2) { ArrayList<String> availabilityZones = new ArrayList<String>(); DescribeAvailabilityZonesResult zones = ec2.describeAvailabilityZones(); List<AvailabilityZone> zoneList = zones.getAvailabilityZones(); for (AvailabilityZone z : zoneList) { availabilityZones.add(z.getZoneName()); } return availabilityZones; } /* * Check the current Spot price of the selected instance type for the selected region */ public FormValidation doCurrentSpotPrice(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region, @QueryParameter String type, @QueryParameter String zone) throws IOException, ServletException { String cp = ""; String zoneStr = ""; // Connect to the EC2 cloud with the access id, secret key, and // region queried from the created cloud AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); if (ec2 != null) { try { // Build a new price history request with the currently // selected type DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest(); // If a zone is specified, set the availability zone in the // request // Else, proceed with no availability zone which will result // with the cheapest Spot price if (getAvailabilityZones(ec2).contains(zone)) { request.setAvailabilityZone(zone); zoneStr = zone + " availability zone"; } else { zoneStr = region + " region"; } /* * Iterate through the AWS instance types to see if can find a match for the databound String type. * This is necessary because the AWS API needs the instance type string formatted a particular way * to retrieve prices and the form gives us the strings in a different format. For example "T1Micro" * vs "t1.micro". */ InstanceType ec2Type = null; for (InstanceType it : InstanceType.values()) { if (it.name().equals(type)) { ec2Type = it; break; } } /* * If the type string cannot be matched with an instance type, throw a Form error */ if (ec2Type == null) { return FormValidation.error("Could not resolve instance type: " + type); } Collection<String> instanceType = new ArrayList<String>(); instanceType.add(ec2Type.toString()); request.setInstanceTypes(instanceType); request.setStartTime(new Date()); // Retrieve the price history request result and store the // current price DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory(request); if (!result.getSpotPriceHistory().isEmpty()) { SpotPrice currentPrice = result.getSpotPriceHistory().get(0); cp = currentPrice.getSpotPrice(); } } catch (AmazonServiceException e) { return FormValidation.error(e.getMessage()); } } /* * If we could not return the current price of the instance display an error Else, remove the additional * zeros from the current price and return it to the interface in the form of a message */ if (cp.isEmpty()) { return FormValidation.error("Could not retrieve current Spot price"); } else { cp = cp.substring(0, cp.length() - 3); return FormValidation.ok("The current Spot price for a " + type + " in the " + zoneStr + " is $" + cp); } } } }
package io.cfp.controller; import io.cfp.dto.RoomDto; import io.cfp.entity.Event; import io.cfp.entity.Role; import io.cfp.entity.Room; import io.cfp.repository.EventRepository; import io.cfp.repository.RoomRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; import java.util.stream.Collectors; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.*; @RestController @RequestMapping(value = { "/v0/rooms", "/api/rooms" }, produces = APPLICATION_JSON_UTF8_VALUE) public class RoomsControler { @Autowired private RoomRepo rooms; @Autowired private EventRepository events; @RequestMapping(method = GET) public Collection<RoomDto> all() { return rooms .findByEventId(Event.current()) .stream() .map( r -> new RoomDto(r) ) .collect(Collectors.toList()); } @RequestMapping(method = POST) @Transactional @Secured(Role.OWNER) public RoomDto create(@RequestBody RoomDto room) { return new RoomDto( rooms.save( new Room() .withEvent(events.findOne(Event.current())) .withName(room.getName()))); } @RequestMapping(value = "/{id}", method = PUT) @Transactional @Secured(Role.OWNER) public void update(@PathVariable int id, @RequestBody RoomDto update) { Room room = rooms.findByIdAndEventId(id, Event.current()); // make sure the track belongs to the current event if (room != null) { rooms.save( room.withName(update.getName())); } } @RequestMapping(value = "/{id}", method = DELETE) @Transactional @Secured(Role.OWNER) public void delete(@PathVariable int id) { Room room = rooms.findByIdAndEventId(id, Event.current()); // make sure the track belongs to the current event if (room != null && !isReferenced(room)) { rooms.delete(id); } } private boolean isReferenced(Room room) { return false; /** TODO check schedule */ } }
package org.jboss.forge.furnace.proxy; import org.jboss.forge.furnace.util.Assert; /** * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> */ class Arrays { @SafeVarargs public static <ELEMENTTYPE> ELEMENTTYPE[] append(ELEMENTTYPE[] array, ELEMENTTYPE... elements) { final int length = array.length; array = java.util.Arrays.copyOf(array, length + elements.length); System.arraycopy(elements, 0, array, length, elements.length); return array; } @SafeVarargs public static <ELEMENTTYPE> ELEMENTTYPE[] prepend(ELEMENTTYPE[] array, ELEMENTTYPE... elements) { final int length = array.length; array = java.util.Arrays.copyOf(array, length + elements.length); System.arraycopy(array, 0, array, elements.length, length); System.arraycopy(elements, 0, array, 0, elements.length); return array; } public static <ELEMENTTYPE> ELEMENTTYPE[] copy(ELEMENTTYPE[] source, ELEMENTTYPE[] target) { Assert.isTrue(source.length == target.length, "Source and destination arrays must be of the same length."); System.arraycopy(source, 0, target, 0, source.length); return target; } public static <ELEMENTTYPE> ELEMENTTYPE[] shiftLeft(ELEMENTTYPE[] source, ELEMENTTYPE[] target) { Assert.isTrue(source.length > 0, "Source array length cannot be zero."); Assert.isTrue(source.length - 1 == target.length, "Destination array must be one element shorter than the source array."); System.arraycopy(source, 1, target, 0, target.length); return target; } public static <ELEMENTTYPE> boolean contains(ELEMENTTYPE[] array, ELEMENTTYPE value) { return indexOf(array, value) >= 0; } public static <ELEMENTTYPE> int indexOf(ELEMENTTYPE[] array, ELEMENTTYPE value) { if (array.length == 0) return -1; for (int i = 0; i < array.length; i++) { ELEMENTTYPE element = array[i]; if (element == value) return i; } return -1; } public static <ELEMENTTYPE> ELEMENTTYPE[] removeElementAtIndex(ELEMENTTYPE[] array, int index) { Assert.isTrue(array.length > 0, "Cannot remove an element from an already empty array."); ELEMENTTYPE[] result = java.util.Arrays.copyOf(array, array.length - 1); if (result.length > 0 && array.length + 1 != index && index != result.length) System.arraycopy(array, index + 1, result, index, array.length - (array.length - index)); return result; } }
package io.honeybadger.reporter.dto; import org.slf4j.LoggerFactory; import java.io.File; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.util.Scanner; public class Load implements Serializable { private static final long serialVersionUID = 3398000045209329774L; public final Number one; public final Number five; public final Number fifteen; public Load() { Number[] loadAverages = findLoadAverages(); this.one = loadAverages[0]; this.five = loadAverages[1]; this.fifteen = loadAverages[2]; } public Load(Number one, Number five, Number fifteen) { this.one = one; this.five = five; this.fifteen = fifteen; } /** * Attempts to find all three load values in a way that is safe for an in-process * operation. This leads to platform specific code. We attempt to avoid forking to * call external processes because this would be a bad thing to do on every error * that came into the system. * * @return an array containing all three load averages (1, 5, 15) in that order */ static Number[] findLoadAverages() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); String os = osBean.getName(); if (os.equals("Linux")) { return findLinuxLoadAverages(osBean); } else { return defaultLoadAverages(osBean); } } static Number[] findLinuxLoadAverages(OperatingSystemMXBean osBean) { File loadavg = new File("/proc/loadavg"); if (loadavg.exists() && loadavg.isFile() && loadavg.canRead()) { try (Scanner scanner = new Scanner(loadavg)) { if (!scanner.hasNext()) { return defaultLoadAverages(osBean); } String line = scanner.nextLine(); String[] values = line.split(" ", 4); return new Number[]{ Double.parseDouble(values[0]), Double.parseDouble(values[1]), Double.parseDouble(values[2]) }; } catch (Exception e) { LoggerFactory.getLogger(Load.class) .debug("Error reading /proc/loadavg", e); return defaultLoadAverages(osBean); } } else { LoggerFactory.getLogger(Load.class) .debug("Couldn't fid or access /proc/loadavg"); return defaultLoadAverages(osBean); } } static Number[] defaultLoadAverages(OperatingSystemMXBean osBean) { return new Number[] { osBean.getSystemLoadAverage(), null, null }; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Load load = (Load) o; if (one != null ? !one.equals(load.one) : load.one != null) return false; if (five != null ? !five.equals(load.five) : load.five != null) return false; return !(fifteen != null ? !fifteen.equals(load.fifteen) : load.fifteen != null); } @Override public int hashCode() { int result = one != null ? one.hashCode() : 0; result = 31 * result + (five != null ? five.hashCode() : 0); result = 31 * result + (fifteen != null ? fifteen.hashCode() : 0); return result; } @Override public String toString() { return "Load{" + "one=" + one + ", five=" + five + ", fifteen=" + fifteen + '}'; } }
package io.rocketchat.core; import io.rocketchat.common.data.model.Room; import io.rocketchat.common.data.model.UserObject; import io.rocketchat.common.data.rpc.RPC; import io.rocketchat.common.listener.ConnectListener; import io.rocketchat.common.listener.SimpleListener; import io.rocketchat.common.listener.SubscribeListener; import io.rocketchat.common.listener.TypingListener; import io.rocketchat.common.network.Socket; import io.rocketchat.common.utils.Utils; import io.rocketchat.core.callback.*; import io.rocketchat.core.factory.ChatRoomFactory; import io.rocketchat.core.middleware.CoreMiddleware; import io.rocketchat.core.middleware.CoreStreamMiddleware; import io.rocketchat.core.model.RocketChatMessage; import io.rocketchat.core.model.SubscriptionObject; import io.rocketchat.core.rpc.*; import org.json.JSONArray; import org.json.JSONObject; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; // TODO: 30/7/17 Make it singletone like eventbus, add builder class to RocketChatAPI in order to use it anywhere, maybe a common builder class public class RocketChatAPI extends Socket { AtomicInteger integer; String sessionId; UserObject userInfo; ConnectListener connectListener; CoreMiddleware coreMiddleware; CoreStreamMiddleware coreStreamMiddleware; // factory class ChatRoomFactory factory; public RocketChatAPI(String url) { super(url); integer=new AtomicInteger(1); coreMiddleware=CoreMiddleware.getInstance(); coreStreamMiddleware=CoreStreamMiddleware.getInstance(); factory=new ChatRoomFactory(this); } public String getMyUserName(){ return userInfo.getUserName(); } public JSONArray getMyEmails(){ return userInfo.getEmails(); } public ChatRoomFactory getFactory() { return factory; } //Tested public void login(String username, String password, LoginListener loginListener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,loginListener, CoreMiddleware.ListenerType.LOGIN); sendDataInBackground(BasicRPC.login(uniqueID,username,password)); } //Tested public void loginUsingToken(String token,LoginListener loginListener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,loginListener, CoreMiddleware.ListenerType.LOGIN); sendDataInBackground(BasicRPC.loginUsingToken(uniqueID,token)); } //Tested public void getPermissions(AccountListener.getPermissionsListener listener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.GETPERMISSIONS); sendDataInBackground(AccountRPC.getPermissions(uniqueID,null)); } //Tested public void getPublicSettings(AccountListener.getPublicSettingsListener listener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.GETPUBLICSETTINGS); sendDataInBackground(AccountRPC.getPublicSettings(uniqueID,null)); } //Tested public void getUserRoles(UserListener.getUserRoleListener userRoleListener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,userRoleListener, CoreMiddleware.ListenerType.GETUSERROLES); sendDataInBackground(BasicRPC.getUserRoles(uniqueID)); } //Tested public void listCustomEmoji(EmojiListener listener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.LISTCUSTOMEMOJI); sendDataInBackground(BasicRPC.listCustomEmoji(uniqueID)); } //Tested public void logout(SimpleListener listener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.LOGOUT); sendDataInBackground(BasicRPC.logout(uniqueID)); } //Tested public void getSubscriptions(SubscriptionListener.GetSubscriptionListener getSubscriptionListener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,getSubscriptionListener, CoreMiddleware.ListenerType.GETSUBSCRIPTIONS); sendDataInBackground(BasicRPC.getSubscriptions(uniqueID)); } //Tested public void getRooms(RoomListener.GetRoomListener getRoomListener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,getRoomListener, CoreMiddleware.ListenerType.GETROOMS); sendDataInBackground(BasicRPC.getRooms(uniqueID)); } //Tested private void getRoomRoles(String roomId,RoomListener.RoomRolesListener listener){ int uniqueID=integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.GETROOMROLES); sendDataInBackground(BasicRPC.getRoomRoles(uniqueID,roomId)); } //Tested private void getChatHistory(String roomID, int limit, Date oldestMessageTimestamp, Date lasttimestamp, HistoryListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.LOADHISTORY); sendDataInBackground(ChatHistoryRPC.loadHistory(uniqueID,roomID,oldestMessageTimestamp,limit,lasttimestamp)); } //Tested private void sendIsTyping(String roomId, String username, Boolean istyping){ int uniqueID = integer.getAndIncrement(); sendDataInBackground(TypingRPC.sendTyping(uniqueID,roomId,username,istyping)); } //Tested private void sendMessage(String msgId, String roomID, String message, MessageListener.MessageAckListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.SENDMESSAGE); sendDataInBackground(MessageRPC.sendMessage(uniqueID,msgId,roomID,message)); } //Tested private void deleteMessage(String msgId, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.MESSAGEOP); sendDataInBackground(MessageRPC.deleteMessage(uniqueID,msgId)); } //Tested private void updateMessage (String msgId, String roomId, String message, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.MESSAGEOP); sendDataInBackground(MessageRPC.updateMessage(uniqueID,msgId,roomId,message)); } //Tested private void pinMessage ( JSONObject message, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.MESSAGEOP); sendDataInBackground(MessageRPC.pinMessage(uniqueID,message)); } //Tested private void unpinMessage (JSONObject message, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.MESSAGEOP); sendDataInBackground(MessageRPC.unpinMessage(uniqueID,message)); } //Tested private void starMessage( String msgId, String roomId, Boolean starred, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.MESSAGEOP); sendDataInBackground(MessageRPC.starMessage(uniqueID,msgId,roomId,starred)); } //Tested private void setReaction (String emojiId, String msgId, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.MESSAGEOP); sendDataInBackground(MessageRPC.setReaction(uniqueID,emojiId,msgId)); } //Tested public void createPublicGroup(String groupName, String [] users, Boolean readOnly,RoomListener.GroupListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.CREATEGROUP); sendDataInBackground(RoomRPC.createPublicGroup(uniqueID,groupName, users, readOnly)); } //Tested public void createPrivateGroup(String groupName, String [] users, RoomListener.GroupListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.CREATEGROUP); sendDataInBackground(RoomRPC.createPrivateGroup(uniqueID,groupName,users)); } //Tested private void deleteGroup(String roomId, SimpleListener listener){ //Apply simpleListener int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.DELETEGROUP); sendDataInBackground(RoomRPC.deleteGroup(uniqueID,roomId)); } //Tested private void archiveRoom(String roomId, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.ARCHIEVE); sendDataInBackground(RoomRPC.archieveRoom(uniqueID,roomId)); } //Tested private void unarchiveRoom(String roomId, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.UNARCHIEVE); sendDataInBackground(RoomRPC.unarchiveRoom(uniqueID,roomId)); } //Tested public void joinPublicGroup(String roomId, String joinCode, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.JOINPUBLICGROUP); sendDataInBackground(RoomRPC.joinPublicGroup(uniqueID,roomId,joinCode)); } //Tested private void leaveGroup(String roomId, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.LEAVEGROUP); sendDataInBackground(RoomRPC.leaveGroup(uniqueID,roomId)); } //Tested private void hideRoom(String roomId, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.HIDEROOM); sendDataInBackground(RoomRPC.hideRoom(uniqueID,roomId)); } //Tested private void openRoom(String roomId, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.OPENROOM); sendDataInBackground(RoomRPC.openRoom(uniqueID,roomId)); } //Tested private void setFavouriteRoom(String roomId, Boolean isFavouriteRoom, SimpleListener listener){ int uniqueID = integer.getAndIncrement(); coreMiddleware.createCallback(uniqueID,listener, CoreMiddleware.ListenerType.SETFAVOURITEROOM); sendDataInBackground(RoomRPC.setFavouriteRoom(uniqueID,roomId,isFavouriteRoom)); } //Tested public void setStatus(PresenceRPC.Status s){ int uniqueID = integer.getAndIncrement(); sendDataInBackground(PresenceRPC.setDefaultStatus(uniqueID,s)); } //Tested private String subscribeRoomMessageEvent(String roomId, Boolean enable, SubscribeListener subscribeListener, MessageListener.SubscriptionListener listener){ String uniqueID= Utils.shortUUID(); coreStreamMiddleware.createSubCallback(uniqueID, subscribeListener); coreStreamMiddleware.subscribeRoomMessage(listener); sendDataInBackground(CoreSubRPC.subscribeRoomMessageEvent(uniqueID,roomId,enable)); return uniqueID; } private String subscribeRoomTypingEvent(String roomId, Boolean enable, SubscribeListener subscribeListener, TypingListener listener){ String uniqueID= Utils.shortUUID(); coreStreamMiddleware.createSubCallback(uniqueID, subscribeListener); coreStreamMiddleware.subscribeRoomTyping(listener); sendDataInBackground(CoreSubRPC.subscribeRoomTypingEvent(uniqueID,roomId,enable)); return uniqueID; } private void unsubscribeRoom(String subId, SubscribeListener subscribeListener){ sendDataInBackground(CoreSubRPC.unsubscribeRoom(subId)); coreStreamMiddleware.createSubCallback(subId, subscribeListener); } public void setConnectListener(ConnectListener connectListener) { this.connectListener = connectListener; } public void connect(ConnectListener connectListener){ createSocket(); this.connectListener = connectListener; super.connectAsync(); } @Override protected void onConnected() { integer.set(1); sendDataInBackground(BasicRPC.ConnectObject()); super.onConnected(); } @Override protected void onTextMessage(String text) throws Exception { JSONObject object = new JSONObject(text); switch (RPC.parse(object.optString("msg"))) { case PING: sendDataInBackground("{\"msg\":\"pong\"}"); break; case CONNECTED: sessionId = object.optString("session"); if (connectListener != null) { connectListener.onConnect(sessionId); } break; case ADDED: if (object.optString("collection").equals("users")) { userInfo = new UserObject(object.optJSONObject("fields")); } break; case RESULT: coreMiddleware.processCallback(Long.valueOf(object.optString("id")), object); break; case READY: coreStreamMiddleware.processSubSuccess(object); break; case CHANGED: coreStreamMiddleware.processCallback(object); break; case NOSUB: coreStreamMiddleware.processUnsubSuccess(object); break; case OTHER: break; default: break; } super.onTextMessage(text); } @Override protected void onConnectError(Exception websocketException) { if (connectListener!=null) { connectListener.onConnectError(websocketException); } super.onConnectError(websocketException); } @Override protected void onDisconnected(boolean closedByServer) { if (connectListener!=null) { connectListener.onDisconnect(closedByServer); } super.onDisconnected(closedByServer); } /** * ChatRoom class to access private methods */ public class ChatRoom { Room room; //Subscription Ids for new subscriptions private String roomSubId; // TODO: 29/7/17 check for persistent SubscriptionId of the room private String typingSubId; public ChatRoom(Room room){ this.room=room; } public Boolean isSubscriptionObject(){ return room instanceof SubscriptionObject; } public Room getRoomData() { return room; } //RPC methods public void getRoomRoles(RoomListener.RoomRolesListener listener){ RocketChatAPI.this.getRoomRoles(room.getRoomId(),listener); } public void getChatHistory(int limit, Date oldestMessageTimestamp, Date lasttimestamp, HistoryListener listener){ RocketChatAPI.this.getChatHistory(room.getRoomId(),limit,oldestMessageTimestamp,lasttimestamp,listener); } public void sendIsTyping(Boolean istyping){ RocketChatAPI.this.sendIsTyping(room.getRoomId(),getMyUserName(),istyping); } public void sendMessage(String message){ RocketChatAPI.this.sendMessage(Utils.shortUUID(),room.getRoomId(),message,null); } public void sendMessage(String message, MessageListener.MessageAckListener listener){ RocketChatAPI.this.sendMessage(Utils.shortUUID(),room.getRoomId(),message,listener); } // TODO: 27/7/17 Need more attention on replying to message private void replyMessage(RocketChatMessage msg, String message, MessageListener.MessageAckListener listener){ message="[ ](?msg="+msg.getMessageId()+") @"+msg.getSender().getUserName()+" "+message; RocketChatAPI.this.sendMessage(Utils.shortUUID(),room.getRoomId(),message,listener); } public void deleteMessage(String msgId, SimpleListener listener){ RocketChatAPI.this.deleteMessage(msgId ,listener); } public void updateMessage (String msgId, String message, SimpleListener listener){ RocketChatAPI.this.updateMessage(msgId, room.getRoomId(), message, listener); } public void pinMessage ( JSONObject message, SimpleListener listener){ RocketChatAPI.this.pinMessage(message, listener); } public void unpinMessage (JSONObject message, SimpleListener listener){ RocketChatAPI.this.unpinMessage(message, listener); } public void starMessage( String msgId, Boolean starred, SimpleListener listener){ RocketChatAPI.this.starMessage(msgId, room.getRoomId(),starred, listener); } public void setReaction (String emojiId, String msgId, SimpleListener listener){ RocketChatAPI.this.setReaction(emojiId,msgId,listener); } public void deleteGroup(SimpleListener listener){ RocketChatAPI.this.deleteGroup(room.getRoomId(),listener); } public void archive(SimpleListener listener){ RocketChatAPI.this.archiveRoom(room.getRoomId(),listener); } public void unarchive(SimpleListener listener){ RocketChatAPI.this.unarchiveRoom(room.getRoomId(),listener); } public void leave(SimpleListener listener){ RocketChatAPI.this.leaveGroup(room.getRoomId(),listener); } public void hide(SimpleListener listener){ RocketChatAPI.this.hideRoom(room.getRoomId(),listener); } public void open(SimpleListener listener){ RocketChatAPI.this.openRoom(room.getRoomId(),listener); } public void setFavourite(Boolean isFavoutite, SimpleListener listener){ RocketChatAPI.this.setFavouriteRoom(room.getRoomId(),isFavoutite,listener); } //Subscription methods public void subscribeRoomMessageEvent(SubscribeListener subscribeListener, MessageListener.SubscriptionListener listener){ if (roomSubId==null) { roomSubId=RocketChatAPI.this.subscribeRoomMessageEvent(room.getRoomId(), true, subscribeListener, listener); } } public void subscribeRoomTypingEvent(SubscribeListener subscribeListener, TypingListener listener){ if (typingSubId==null){ typingSubId= RocketChatAPI.this.subscribeRoomTypingEvent(room.getRoomId(), true, subscribeListener, listener); } } public void unSubscribeRoomMessageEvent(SubscribeListener subscribeListener){ if (roomSubId!=null) { RocketChatAPI.this.unsubscribeRoom(roomSubId, subscribeListener); roomSubId = null; } } public void unSubscribeRoomTypingEvent(SubscribeListener subscribeListener){ if (typingSubId!=null) { RocketChatAPI.this.unsubscribeRoom(typingSubId, subscribeListener); typingSubId = null; } } public void unSubscribeAllEvents(){ unSubscribeRoomMessageEvent(null); unSubscribeRoomTypingEvent(null); } // TODO: 29/7/17 refresh methods to be added, changing data should change internal data, maintain state of the room } }
package io.teiler.api.service; import io.teiler.server.dto.Person; import io.teiler.server.persistence.entities.PersonEntity; import io.teiler.server.persistence.repositories.PersonRepository; import io.teiler.server.util.exceptions.PeopleNameConflictException; import io.teiler.server.util.exceptions.PersonInactiveException; import io.teiler.server.util.exceptions.PersonNotFoundException; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PersonUtil { @Autowired private PersonRepository personRepository; public PersonUtil() { /* intentionally empty */ } /** * Checks whether the name of a Person is unique within a Group. * * @param groupId Id of the Group * @param name Name of the Person * @throws PeopleNameConflictException Name already exists in Group */ public void checkNamesAreUnique(String groupId, String name) throws PeopleNameConflictException { PersonEntity foundPerson = personRepository.getByName(groupId, name); // If the person was found AND is active, throw an exception // NEVER change the order around on this statement, otherwise you may get null pointers if (foundPerson != null && foundPerson.getActive()) { throw new PeopleNameConflictException(); } } /** * Checks whether a Person exists within a Group. * * @param groupId Id of the Group * @param personId Id of the Person * @throws PersonNotFoundException Person does not exists within Group */ public void checkPersonBelongsToThisGroup(String groupId, int personId)throws PersonNotFoundException { if (personRepository.getByGroupAndPersonId(groupId, personId) == null) { throw new PersonNotFoundException(); } } /** * Checks whether a Person exists. * * @param personId Id of the Person * @throws PersonNotFoundException Person does not exist */ public void checkPersonExists(int personId) throws PersonNotFoundException { if (personRepository.getById(personId) == null) { throw new PersonNotFoundException(); } } public java.util.List<Person> filterInactivePeople(java.util.List<Person> people) { return people.stream().filter(Person::isActive).collect(Collectors.toList()); } public void checkPersonIsActive(int personId) throws PersonInactiveException { if (!personRepository.getById(personId).getActive()) { throw new PersonInactiveException(); } } }
package main.java.meterstanden.domain; import java.io.IOException; import java.util.List; import javax.persistence.Query; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.hibernate.Session; import com.google.gson.Gson; import main.java.meterstanden.hibernate.HibernateUtil; import main.java.meterstanden.model.Metersoorten; /** * Servlet implementation class Meterstanden */ @WebServlet( description = "REST interface for meterstanden.", urlPatterns = { "/Meterstanden", "/meterstanden", "/METERSTANDEN" }) public class Meterstanden extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(Meterstanden.class); /** * @see HttpServlet#HttpServlet() */ public Meterstanden() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Meterstanden> myMeterstanden = getLastMeterstanden("0"); Gson gson = new Gson(); log.debug("The meterstanden JSON:"); log.debug(gson.toJson(myMeterstanden)); response.getWriter().append(gson.toJson(myMeterstanden)); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** * Get the last 20 Meterstanden. * * @param selectie ID of metersoort to get the Meterstanden from (0 = all) * @return The list of meterstanden */ @SuppressWarnings("unchecked") private List<Meterstanden> getLastMeterstanden(String selectie){ log.debug("Getting the 20 last Meterstanden"); Session session = HibernateUtil.getSessionFactory().openSession(); Long selectieInt = Long.valueOf(selectie); Metersoorten metersoort = null; boolean useSelection = selectieInt>0; String hql = "from Meterstanden m "; if (useSelection){ hql += "where m.metersoort = :metersoort "; metersoort = session.get(Metersoorten.class, selectieInt); } hql += "order by m.datum desc"; Query query = session.createQuery(hql); if (useSelection){ query.setParameter("metersoort", metersoort); } query.setMaxResults(20); //todo this 20 should be configured with a config file. List<?> rl = query.getResultList(); session.close(); return (List<Meterstanden>) rl; } }
package mitonize.datastore; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.UnresolvedAddressException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SocketManager { Logger logger = LoggerFactory.getLogger(SocketManager.class); /** * TCP */ class Endpoint { public Endpoint(InetAddress address, int port) { this.address = address; this.port = port; } final InetAddress address; final int port; private boolean offline = false; /** for canceling on being online */ ScheduledFuture<Object> offlineManagementFuture; /** * * @param endpoint * @param offline (true:false:) */ @SuppressWarnings("unchecked") synchronized void markEndpointOffline(boolean offline) { if (offline) { if (!this.offline) { OfflineManagementTask task = new OfflineManagementTask(this); this.offlineManagementFuture = (ScheduledFuture<Object>) offlineManagementService.scheduleWithFixedDelay(task, 0, 5, TimeUnit.SECONDS); this.offline = true; logger.warn("Mark offline - {}:{}", this.address.getHostName(), this.port); } } else { ScheduledFuture<Object> future = this.offlineManagementFuture; if (future != null) { future.cancel(true); this.offlineManagementFuture = null; } this.offline = false; logger.warn("Mark online - {}:{}", this.address.getHostName(), this.port); } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(address.getHostName()); builder.append(":"); builder.append(port); if (offline) { builder.append(" (offline)"); } return builder.toString(); } } /** * ("hostname:port") * * 1(0) */ Endpoint[] endpoints; long timestampLatelyPooled = 0; int maxCountOfCoucurrentSockets = 0; /** * Executor */ final ScheduledExecutorService offlineManagementService; /** * TCP() * TCP * 0 */ int delayToMarkOnlineInMillis = 3000; /** * TCP() */ int timeoutToConnectInMillis = 1000; int timeoutToReadInMillis = 1000; final protected ArrayBlockingQueue<SocketStreams> queue; final protected AtomicInteger activeSocketCount; final protected AtomicInteger currentEndpointIndex; private int maxPoolSize = 0; private DumpFilterStreamFactory dumpFilterStreamFactory; public SocketManager(String[] masternodes, int maxPoolSize) throws UnknownHostException { if (masternodes.length == 0) { throw new IllegalStateException("No connection endpoint setting specified."); } this.offlineManagementService = Executors.newSingleThreadScheduledExecutor(); this.queue = new ArrayBlockingQueue<SocketStreams>(maxPoolSize); this.activeSocketCount = new AtomicInteger(0); this.currentEndpointIndex = new AtomicInteger(0); this.maxPoolSize = maxPoolSize; this.endpoints = new Endpoint[masternodes.length]; for (int i = 0; i < masternodes.length; ++i) { String hostname = masternodes[i].split(":")[0]; int port = Integer.parseInt(masternodes[i].split(":")[1]); // May throws NumberFormatException if (!hostname.matches("[\\d\\w.]+")) { throw new IllegalArgumentException("hostname contains illegal character. " + hostname); } if (port < 0 || port > 65535) { throw new IllegalArgumentException("port number must in range 0 to 65535. " + port); } endpoints[i] = new Endpoint(InetAddress.getByName(hostname), port); } } @Deprecated public void setDumpStream(boolean b) { dumpFilterStreamFactory = new TextDumpFilterStreamFactory(); } public boolean isDumpStream() { return dumpFilterStreamFactory != null; } /** * * * * * @return * @throws IOException 1 */ public SocketStreams aquire() throws IOException { SocketStreams socket = queue.poll(); return (socket == null || !isAvailable(socket)) ? openSocket() : socket; } /** * * * * * * @param socket */ public void recycle(SocketStreams socket) { if (socket == null) return; if (socket.timestamp > timestampLatelyPooled || !isAvailable(socket) || !queue.offer(socket)) { closeSocket(socket); } } class OfflineManagementTask implements Runnable { private Endpoint endpoint; public OfflineManagementTask(Endpoint endpoint) { this.endpoint = endpoint; } @Override public void run() { int timeout = timeoutToConnectInMillis; int delay = delayToMarkOnlineInMillis; InetSocketAddress address = new InetSocketAddress(endpoint.address, endpoint.port); Socket socket = new Socket(); try { socket.connect(address, timeout); Thread.sleep(delay); endpoint.markEndpointOffline(false); } catch (IOException e) { } catch (InterruptedException e) { } finally { try { socket.close(); } catch (IOException e) { } } } } /** * * @return */ Endpoint getEndpointAt(int i) { return endpoints[i]; } /** * * 1 * @return 1 */ Endpoint nextEndpoint() { int count = endpoints.length; int index = currentEndpointIndex.getAndSet(currentEndpointIndex.incrementAndGet() % count); while (count if (index >= endpoints.length) index = 0; Endpoint endpoint = endpoints[index++]; if (endpoint == null) throw new IllegalStateException("No connection endpoint setting specified."); if (!endpoint.offline) { return endpoint; } } return endpoints[0]; } /** * * * @return * @throws IOException 1 */ @SuppressWarnings("resource") SocketStreams openSocket() throws IOException { int timeoutToConnect = timeoutToConnectInMillis; int timeoutToRead = timeoutToReadInMillis; Endpoint lastAttempt = null; for (int i=endpoints.length; i >= 0; --i) { Endpoint endpoint = nextEndpoint(); // nextEndpoint() never returns null. if (endpoint.equals(lastAttempt)) { break; } try { InetSocketAddress address = new InetSocketAddress (endpoint.address, endpoint.port); Socket socket = new Socket(); socket.setSoTimeout(timeoutToRead); socket.connect(address, timeoutToConnect); OutputStream os = new BufferedOutputStream(socket.getOutputStream()); InputStream is = new BufferedInputStream(socket.getInputStream()); if (dumpFilterStreamFactory != null) { is = dumpFilterStreamFactory.wrapInputStream(is); os = dumpFilterStreamFactory.wrapOutputStream(os); } SocketStreams s = new SocketStreams(socket, os, is); int c = activeSocketCount.incrementAndGet(); // recycle if (c <= maxPoolSize) { timestampLatelyPooled = s.timestamp; } if (c > maxCountOfCoucurrentSockets) { maxCountOfCoucurrentSockets = c; } if (logger.isInfoEnabled()) { logger.info("Socket opened - {}:{} count:{}", endpoint.address.getHostName(), endpoint.port, c); } if (endpoint.offline) { endpoint.markEndpointOffline(false); } return s; } catch (UnresolvedAddressException e) { logger.error("Hostname cannot be resolved. {}:{} {}", endpoint.address.getHostName(), endpoint.port, e.getMessage()); endpoint.markEndpointOffline(true); } catch (IOException e) { logger.error("Failed to open socket. {}:{} {}", endpoint.address.getHostName(), endpoint.port, e.getMessage()); endpoint.markEndpointOffline(true); } lastAttempt = endpoint; } logger.error("No available endpoint to connect"); throw new IOException("No available endpoint to connect"); } void closeSocket(SocketStreams socket) { try { socket.getOutputStream().close(); socket.getInputStream().close(); socket.getSocket().close(); int c = activeSocketCount.decrementAndGet(); if (logger.isInfoEnabled()) { Socket s = socket.getSocket(); logger.info("Socket closed - {}:{} count:{}", s.getInetAddress().getHostName(), s.getPort(), c); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } private boolean isAvailable(SocketStreams streams) { Socket s = streams.getSocket(); if (s.isInputShutdown() || s.isOutputShutdown() || s.isClosed()) { try { s.close(); } catch (IOException e) { } return false; } return true; } public void destroy(SocketStreams streams) { if (streams == null) return; Socket s = streams.getSocket(); logger.info("Destroy connection - {}:{}", s.getInetAddress().getHostName(), s.getPort()); try { streams.getOutputStream().close(); streams.getInputStream().close(); streams.getSocket().close(); } catch (IOException e) { } } public int getMaxPoolSize() { return maxPoolSize; } public int getMaxCoucurrentSockets() { return maxCountOfCoucurrentSockets; } public void setDumpFilterStreamFactory( DumpFilterStreamFactory dumpFilterStreamFactory) { this.dumpFilterStreamFactory = dumpFilterStreamFactory; } }
package net.intelie.disq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; public class PersistentQueue<T> implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(PersistentQueue.class); private static final long MAX_WAIT = 10_000_000_000L; private final ConcurrentLinkedQueue<WeakReference<Buffer>> pool; private final ArrayRawQueue fallback; private final RawQueue queue; private final Serializer<T> serializer; private final int initialBufferCapacity; private final int maxBufferCapacity; private final boolean compress; private final Lock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); private boolean popPaused, pushPaused; public PersistentQueue(RawQueue queue, Serializer<T> serializer, int initialBufferCapacity, int maxBufferCapacity, boolean compress) { this(queue, serializer, initialBufferCapacity, maxBufferCapacity, compress, 0); } public PersistentQueue(RawQueue queue, Serializer<T> serializer, int initialBufferCapacity, int maxBufferCapacity, boolean compress, int fallbackBufferCapacity) { this.fallback = new ArrayRawQueue(fallbackBufferCapacity, true); this.queue = queue; this.serializer = serializer; this.initialBufferCapacity = initialBufferCapacity; this.maxBufferCapacity = maxBufferCapacity; this.compress = compress; this.pool = new ConcurrentLinkedQueue<>(); } public RawQueue rawQueue() { return queue; } public ArrayRawQueue fallbackQueue() { return fallback; } public void setPopPaused(boolean popPaused) { lock.lock(); try { this.popPaused = popPaused; this.notFull.signalAll(); this.notEmpty.signalAll(); } finally { lock.unlock(); } } public void setPushPaused(boolean pushPaused) { lock.lock(); try { this.pushPaused = pushPaused; this.notFull.signalAll(); this.notEmpty.signalAll(); } finally { lock.unlock(); } } public void reopen() throws IOException { queue.reopen(); fallback.reopen(); } public long bytes() { return queue.bytes() + fallback.bytes(); } public long count() { return queue.count() + fallback.count(); } public long remainingBytes() { return queue.remainingBytes(); } public long remainingCount() { return queue.remainingCount(); } public void clear() throws IOException { queue.clear(); fallback.clear(); } public void flush() throws IOException { queue.flush(); fallback.flush(); } public T blockingPop(long amount, TimeUnit unit) throws InterruptedException, IOException { return this.<T, InterruptedException>doWithBuffer(buffer -> { lock.lockInterruptibly(); try { long target = System.nanoTime() + unit.toNanos(amount); while (!notifyingPop(buffer)) { long wait = Math.min(MAX_WAIT, target - System.nanoTime()); if (wait <= 0) return null; notEmpty.awaitNanos(wait); } } finally { lock.unlock(); } return deserialize(buffer); }); } public T blockingPop() throws InterruptedException, IOException { return this.<T, InterruptedException>doWithBuffer(buffer -> { lock.lockInterruptibly(); try { while (!notifyingPop(buffer)) notEmpty.awaitNanos(MAX_WAIT); } finally { lock.unlock(); } return deserialize(buffer); }); } public boolean blockingPush(T obj, long amount, TimeUnit unit) throws InterruptedException, IOException { return this.<Boolean, InterruptedException>doWithBuffer(buffer -> { serialize(obj, buffer); lock.lockInterruptibly(); try { long target = System.nanoTime() + unit.toNanos(amount); while (!notifyingPush(buffer)) { long wait = Math.min(MAX_WAIT, target - System.nanoTime()); if (wait <= 0) return false; notFull.awaitNanos(target - System.nanoTime()); } } finally { lock.unlock(); } return true; }); } public boolean blockingPush(T obj) throws InterruptedException, IOException { return this.<Boolean, InterruptedException>doWithBuffer(buffer -> { serialize(obj, buffer); lock.lockInterruptibly(); try { while (!notifyingPush(buffer)) notFull.awaitNanos(MAX_WAIT); } finally { lock.unlock(); } return true; }); } public T pop() throws IOException { return doWithBuffer(buffer -> { lock.lock(); try { if (!notifyingPop(buffer)) return null; } finally { lock.unlock(); } return deserialize(buffer); }); } public boolean push(T obj) throws IOException { return doWithBuffer(buffer -> { serialize(obj, buffer); lock.lock(); try { if (!notifyingPush(buffer)) return false; } finally { lock.unlock(); } return true; }); } private boolean notifyingPop(Buffer buffer) { if (popPaused) return false; if (!innerPop(buffer)) return false; else { notFull.signalAll(); return true; } } private boolean notifyingPush(Buffer buffer) { if (pushPaused) return false; if (!innerPush(buffer)) return false; else { notEmpty.signal(); return true; } } private T deserialize(Buffer buffer) throws IOException { InputStream read = buffer.read(); if (compress) read = new InflaterInputStream(read); return (T) serializer.deserialize(read); } private void serialize(T obj, Buffer buffer) throws IOException { if (obj == null) throw new NullPointerException("Null elements not allowed in persistent queue."); buffer.setCount(0, false); OutputStream write = buffer.write(); if (compress) write = new DeflaterOutputStream(write); try { serializer.serialize(write, obj); } finally { write.close(); } } public T peek() throws IOException { return doWithBuffer(buffer -> { if (!innerPeek(buffer)) return null; return deserialize(buffer); }); } private boolean innerPeek(Buffer buffer) { if (popPaused) return false; if (fallback.peek(buffer)) return true; try { return queue.peek(buffer); } catch (IOException e) { LOGGER.info("Error peeking", e); return false; } } private boolean innerPop(Buffer buffer) { if (fallback.pop(buffer)) return true; try { return queue.pop(buffer); } catch (IOException e) { LOGGER.info("Error popping", e); return false; } } private boolean innerPush(Buffer buffer) { try { return queue.push(buffer); } catch (IOException e) { LOGGER.info("Error pushing", e); return fallback.push(buffer); } } private <Q, E extends Throwable> Q doWithBuffer(BufferOp<Q, E> op) throws IOException, E { Buffer buffer = null; WeakReference<Buffer> ref = null; for (int i = 0; i < 5; i++) { ref = pool.poll(); if (ref == null) break; //empty pool buffer = ref.get(); if (buffer != null) break; //valid deref'd object } if (buffer == null) { buffer = new Buffer(initialBufferCapacity, maxBufferCapacity); ref = new WeakReference<>(buffer); } try { return op.call(buffer); } finally { pool.offer(ref); } } public void close() { queue.close(); } private interface BufferOp<Q, E extends Throwable> { Q call(Buffer buffer) throws E, IOException; } }
package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.RandomDataInput; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.pool.ClassAliasPool; import net.openhft.chronicle.core.pool.StringBuilderPool; import net.openhft.chronicle.core.pool.StringInterner; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.nio.BufferUnderflowException; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import static net.openhft.chronicle.wire.BinaryWire.toIntU30; public enum Wires { ; private static final int NOT_READY = 1 << 31; private static final int META_DATA = 1 << 30; private static final int UNKNOWN_LENGTH = 0x0; public static final int LENGTH_MASK = -1 >>> 2; public static final StringInterner INTERNER = new StringInterner(128); static final StringBuilderPool SBP = new StringBuilderPool(); static final StringBuilderPool ASBP = new StringBuilderPool(); static final StackTraceElement[] NO_STE = {}; private static final Field DETAILED_MESSAGE = Jvm.getField(Throwable.class, "detailMessage"); private static final Field STACK_TRACE = Jvm.getField(Throwable.class, "stackTrace"); static { ClassAliasPool.CLASS_ALIASES.addAlias(WireSerializedLambda.class, "SerializedLambda"); ClassAliasPool.CLASS_ALIASES.addAlias(WireType.class); } public static StringBuilder acquireStringBuilder() { return SBP.acquireStringBuilder(); } public static StringBuilder acquireAnotherStringBuilder(CharSequence cs) { StringBuilder sb = ASBP.acquireStringBuilder(); assert sb != cs; return sb; } public static void writeData(@NotNull WireOut wireOut, boolean metaData, boolean notReady, @NotNull Consumer<WireOut> writer) { Bytes bytes = wireOut.bytes(); long position = bytes.writePosition(); int metaDataBit = metaData ? META_DATA : 0; bytes.writeOrderedInt(metaDataBit | NOT_READY | UNKNOWN_LENGTH); writer.accept(wireOut); int length = metaDataBit | toIntU30(bytes.writePosition() - position - 4, "Document length %,d out of 30-bit int range."); bytes.writeOrderedInt(position, length | (notReady ? NOT_READY : 0)); } public static boolean readData(long offset, @NotNull WireIn wireIn, @Nullable Consumer<WireIn> metaDataConsumer, @Nullable Consumer<WireIn> dataConsumer) { final Bytes bytes = wireIn.bytes(); long position = bytes.readPosition(); long limit = bytes.readLimit(); try { bytes.readLimit(bytes.isElastic() ? bytes.capacity() : bytes.realCapacity()); bytes.readPosition(offset); return readData(wireIn, metaDataConsumer, dataConsumer); } finally { bytes.readLimit(limit); bytes.readPosition(position); } } public static boolean readData(@NotNull WireIn wireIn, @Nullable Consumer<WireIn> metaDataConsumer, @Nullable Consumer<WireIn> dataConsumer) { final Bytes<?> bytes = wireIn.bytes(); boolean read = false; while (bytes.readRemaining() >= 4) { long position = bytes.readPosition(); int header = bytes.readVolatileInt(position); if (!isKnownLength(header)) return read; bytes.readSkip(4); final boolean ready = isReady(header); final int len = lengthOf(header); if (isData(header)) { if (dataConsumer == null) { return false; } else { ((InternalWireIn) wireIn).setReady(ready); bytes.readWithLength(len, b -> dataConsumer.accept(wireIn)); return true; } } else { if (metaDataConsumer == null) { // skip the header bytes.readSkip(len); } else { // bytes.readWithLength(len, b -> metaDataConsumer.accept(wireIn)); // inlined to avoid garbage if ((long) len > bytes.readRemaining()) throw new BufferUnderflowException(); long limit0 = bytes.readLimit(); long limit = bytes.readPosition() + (long) len; try { bytes.readLimit(limit); metaDataConsumer.accept(wireIn); } finally { bytes.readLimit(limit0); bytes.readPosition(limit); } } if (dataConsumer == null) return true; read = true; } } return read; } public static void rawReadData(@NotNull WireIn wireIn, @NotNull Consumer<WireIn> dataConsumer) { final Bytes<?> bytes = wireIn.bytes(); int header = bytes.readInt(); assert isReady(header) && isData(header); final int len = lengthOf(header); long limit0 = bytes.readLimit(); long limit = bytes.readPosition() + (long) len; try { bytes.readLimit(limit); dataConsumer.accept(wireIn); } finally { bytes.readLimit(limit0); } } public static String fromSizePrefixedBlobs(@NotNull Bytes bytes) { long position = bytes.readPosition(); return fromSizePrefixedBlobs(bytes, position, bytes.readRemaining()); } public static String fromSizePrefixedBinaryToText(@NotNull Bytes bytes) { long position = bytes.readPosition(); return fromSizePrefixedBinaryToText(bytes, position, bytes.readRemaining()); } public static int lengthOf(long len) { return (int) (len & LENGTH_MASK); } public static boolean isReady(long len) { return (len & NOT_READY) == 0; } public static boolean isData(long len) { return (len & META_DATA) == 0; } @NotNull private static String fromSizePrefixedBlobs(@NotNull Bytes bytes, long position, long length) { StringBuilder sb = new StringBuilder(); final long limit0 = bytes.readLimit(); final long position0 = bytes.readPosition(); try { bytes.readPosition(position); long limit2 = Math.min(limit0, position + length); bytes.readLimit(limit2); long missing = position + length - limit2; while (bytes.readRemaining() >= 4) { long header = bytes.readUnsignedInt(); int len = lengthOf(header); String type = isData(header) ? isReady(header) ? "!!data" : "!!not-ready-data!" : isReady(header) ? "!!meta-data" : "!!not-ready-meta-data!"; boolean binary = bytes.readByte(bytes.readPosition()) < ' '; sb.append("--- ").append(type).append(binary ? " #binary" : ""); if (missing > 0) sb.append(" # missing: ").append(missing); if (len > bytes.readRemaining()) sb.append(" # len: ").append(len).append(", remaining: ").append(bytes.readRemaining()); sb.append("\n"); try { while (bytes.readRemaining() > 0) { int ch = bytes.readUnsignedByte(); if (binary) sb.append(RandomDataInput.charToString[ch]); else sb.append((char) ch); } } catch (Exception e) { sb.append(" ").append(e); } if (sb.charAt(sb.length() - 1) != '\n') sb.append('\n'); } return sb.toString(); } finally { bytes.readLimit(limit0); bytes.readPosition(position0); } } @NotNull private static String fromSizePrefixedBinaryToText(@NotNull Bytes bytes, long position, long length) { StringBuilder sb = new StringBuilder(); final long limit0 = bytes.readLimit(); final long position0 = bytes.readPosition(); try { bytes.readPosition(position); long limit2 = Math.min(limit0, position + length); bytes.readLimit(limit2); long missing = position + length - limit2; while (bytes.readRemaining() >= 4) { long header = bytes.readUnsignedInt(); int len = lengthOf(header); String type = isData(header) ? isReady(header) ? "!!data" : "!!not-ready-data!" : isReady(header) ? "!!meta-data" : "!!not-ready-meta-data!"; boolean binary = bytes.readByte(bytes.readPosition()) < ' '; sb.append("--- ").append(type).append(binary ? " #binary" : ""); if (missing > 0) sb.append(" # missing: ").append(missing); if (len > bytes.readRemaining()) sb.append(" # len: ").append(len).append(", remaining: ").append(bytes.readRemaining()); sb.append("\n"); Bytes textBytes = bytes; if (binary) { Bytes bytes2 = Bytes.elasticByteBuffer(); TextWire textWire = new TextWire(bytes2); long readLimit = bytes.readLimit(); try { bytes.readLimit(bytes.readPosition() + len); new BinaryWire(bytes).copyTo(textWire); } finally { bytes.readLimit(readLimit); } textBytes = bytes2; len = (int) textBytes.readRemaining(); } try { for (int i = 0; i < len; i++) { int ch = textBytes.readUnsignedByte(); // if (binary) // sb.append(RandomDataInput.charToString[ch]); // else sb.append((char) ch); } } catch (Exception e) { sb.append(" ").append(e); } if (sb.charAt(sb.length() - 1) != '\n') sb.append('\n'); } return sb.toString(); } finally { bytes.readLimit(limit0); bytes.readPosition(position0); } } private static boolean isKnownLength(long len) { return (len & (META_DATA | LENGTH_MASK)) != UNKNOWN_LENGTH; } public static Throwable throwable(@NotNull ValueIn valueIn, boolean appendCurrentStack) { StringBuilder type = Wires.acquireStringBuilder(); valueIn.type(type); String preMessage = null; Throwable throwable; try { //noinspection unchecked throwable = OS.memory().allocateInstance((Class<Throwable>) Class.forName(INTERNER.intern(type))); } catch (ClassNotFoundException e) { preMessage = type.toString(); throwable = new RuntimeException(); } final String finalPreMessage = preMessage; final Throwable finalThrowable = throwable; final List<StackTraceElement> stes = new ArrayList<>(); valueIn.marshallable(m -> { final String message = merge(finalPreMessage, m.read(() -> "message").text()); if (message != null) { try { DETAILED_MESSAGE.set(finalThrowable, message); } catch (IllegalAccessException e) { throw Jvm.rethrow(e); } } m.read(() -> "stackTrace").sequence(stackTrace -> { while (stackTrace.hasNextSequenceItem()) { stackTrace.marshallable(r -> { final String declaringClass = r.read(() -> "class").text(); final String methodName = r.read(() -> "method").text(); final String fileName = r.read(() -> "file").text(); final int lineNumber = r.read(() -> "line").int32(); stes.add(new StackTraceElement(declaringClass, methodName, fileName, lineNumber)); }); } }); }); if (appendCurrentStack) { stes.add(new StackTraceElement("~ remote", "tcp ~", "", 0)); StackTraceElement[] stes2 = Thread.currentThread().getStackTrace(); int first = 6; int last = Jvm.trimLast(first, stes2); //noinspection ManualArrayToCollectionCopy for (int i = first; i <= last; i++) stes.add(stes2[i]); } try { //noinspection ToArrayCallWithZeroLengthArrayArgument STACK_TRACE.set(finalThrowable, stes.toArray(NO_STE)); } catch (IllegalAccessException e) { throw Jvm.rethrow(e); } return throwable; } @Nullable static String merge(@Nullable String a, @Nullable String b) { return a == null ? b : b == null ? a : a + " " + b; } }
package optimizers; import algorithms.Algorithm; import algorithms.random.LocationRandomizer; import algorithms.random.RandomGenerator; import algorithms.random.TerrainGenerator; import algorithms.random.UniformRandomGenerator; import calculations.BasebandResource; import calculations.PlacerLocation; import calculations.RadioResource; import calculations.Terrain; import javafx.util.Pair; import views.map.BTS; import java.util.*; public class EvolutionaryOptimizer implements IBTSLocationOptimizer, Algorithm{ private Vector<LinkedList<BTS> > populations = new Vector<LinkedList<BTS>>(); int btsCount = 0; private Terrain terrain; PlacerLocation topLeft = PlacerLocation.getInstance(PlacerLocation.getWroclawLocation().getX(), PlacerLocation.getWroclawLocation().getY() + TerrainGenerator.maxYfromWroclaw); PlacerLocation bottomRight = PlacerLocation.getInstance(topLeft.getX() + TerrainGenerator.maxXfromWroclaw, topLeft.getY() - TerrainGenerator.maxYfromWroclaw); double step = TerrainGenerator.maxXfromWroclaw / 100; LocationRandomizer randomizer = new LocationRandomizer(new UniformRandomGenerator()); @Override public Terrain regenerateTerrain(Terrain currentTerrain) { relocate(currentTerrain); return currentTerrain; } @Override public void setBtsCount(int btsCount) { this.btsCount = btsCount; } @Override public void setSubscriberCenterCount(int subscriberCenterCount) { } private class ItSucksToCreateClassesJustToCompare implements Comparable<ItSucksToCreateClassesJustToCompare>{ public ItSucksToCreateClassesJustToCompare(int i, double g) { grade = g; id = i; } public double grade; public int id; @Override public int compareTo(ItSucksToCreateClassesJustToCompare o) { return (new Double(o.grade)).compareTo(new Double(grade)); } } @Override public void relocate(Terrain t) { terrain = t; LinkedList<BTS> first = (LinkedList<BTS>) t.getBtss(); double[][] requiredSignalLevel = t.getRequiredSignalLevelArray(topLeft, bottomRight, step); int populationSize = 15; initializePopulations(populationSize, first); int maxIterations = 10; LinkedList<BTS> currentBest = new LinkedList<BTS>(); double currentBestGrade = -9999999999999999.8; for(int i = 0; i < maxIterations; ++i) { System.out.println(String.format("Performing iteration %d of evolutionary algorithm", i+1)); Vector<ItSucksToCreateClassesJustToCompare> grades = new Vector<ItSucksToCreateClassesJustToCompare>(); for(int j = 0; j < populationSize; ++j) { grades.add(new ItSucksToCreateClassesJustToCompare(j, grade(requiredSignalLevel, populations.get(j)))); } Collections.sort(grades); if(grades.get(0).grade > currentBestGrade) { currentBest = populations.get(grades.get(0).id); currentBestGrade = grades.get(0).grade; } if(i == maxIterations - 1) break; Vector<Integer> chosen = new Vector<Integer>(); int sumOfValues = (int) ((1.0 - Math.pow(0.95, populationSize)) * 20.0); //szereg geometryczny for(int j = 0; j < populationSize; ++j) { chosen.add(grades.get(firstSmaller(produceSequence(populationSize), new Random().nextInt(sumOfValues))).id); } mix(chosen); mutate(); } terrain.setBtss(currentBest); } private void mutate() { for(int j = 0; j < populations.size(); ++j) { if(new Random().nextInt() % 1000 < 15) { populations.get(j).get((new Random().nextInt(populations.get(j).size()))).setLocation(randomizer.randomLocation(TerrainGenerator.maxXfromWroclaw, TerrainGenerator.maxYfromWroclaw)); } } } private void mix(Vector<Integer> chosen) { Vector<LinkedList<BTS> > oldPopulations = populations; populations = new Vector<LinkedList<BTS>>(); for(int j = 0; j < oldPopulations.size(); ++j) { populations.add(cross(oldPopulations.get(chosen.get(j)), oldPopulations.get(chosen.get(new Random().nextInt(chosen.size()))))); } } private LinkedList<BTS> cross(LinkedList<BTS> btses, LinkedList<BTS> btses1) { LinkedList<BTS> sum = new LinkedList<BTS>(); for(int i = 0; i < btses.size(); ++i) { BTS newBTS = copy(btses.get(i)); newBTS.setLocation(btses.get(i).getLocation().middle(btses1.get(i).getLocation())); sum.add(newBTS); } return sum; } int firstSmaller(Vector<Integer> ints, int i) { for(int j = 0; j < ints.size(); ++j) { if(ints.get(j) > i) return j; } return 0; } Vector<Integer> produceSequence(int size) { Vector<Integer> ints = new Vector<Integer>(); ints.add(10000); for(int i = 0; i < size; ++i) { ints.add((Integer) (int)(ints.lastElement().doubleValue() * 0.95)); } return ints; } double grade(double[][] requiredSignalLevel, List<BTS> receivedBTSs) { terrain.setBtss(receivedBTSs); SignalDiffCalculator diffCalculator = new SignalDiffCalculator(terrain, topLeft, step); double[][] diff = diffCalculator.calculateDiff(diffCalculator.getSignalLevelArray(bottomRight),requiredSignalLevel); terrain.setBtss(new LinkedList<BTS>()); double grade_ = 0; for(int i = 0; i < diff.length; ++i) { for(int j = 0; j < diff[i].length; ++j) { if(diff[i][j] > 0) grade_ += diff[i][j]; else grade_ -= diff[i][j]/3; } } return grade_; } private void initializePopulations(int populationSize, LinkedList<BTS> first) { for(int i = 0; i < populationSize; ++i) { LinkedList<BTS> btses = new LinkedList<BTS>(); for(int j = 0; j < btsCount; ++j) { BTS oneNew = copy(first.get(j)); oneNew.setLocation(randomizer.randomLocation(TerrainGenerator.maxXfromWroclaw, TerrainGenerator.maxYfromWroclaw)); btses.add(oneNew); } populations.add(btses); } } private BTS copy(BTS bts) { BTS newOne = new BTS(bts.getLocation()); for(RadioResource r: bts.getRadioResources()) { newOne.addRadioResource(new RadioResource(r.getRange())); } for(BasebandResource r: bts.getBasebandResources()) { newOne.addBBResource(new BasebandResource(r.getCapacity())); } return newOne; } private BTS defaultBTS(PlacerLocation placerLocation) { BTS newOne = new BTS(placerLocation); newOne.addBBResource(new BasebandResource(600)); newOne.addBBResource(new BasebandResource(600)); newOne.addBBResource(new BasebandResource(600)); newOne.addRadioResource(new RadioResource(0.2)); newOne.addRadioResource(new RadioResource(0.2)); return newOne; } }
package org.arabellan.tetris.domain; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.arabellan.common.Coord; import org.arabellan.tetris.Renderable; @Slf4j public class Well implements Renderable { private static final int SPACE = 0; private static final int OCCUPIED = 9; @Getter int[][] matrix = new int[][]{ // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, // {WALL, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, WALL}, {OCCUPIED, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, OCCUPIED}, {OCCUPIED, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, OCCUPIED}, {OCCUPIED, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, OCCUPIED}, {OCCUPIED, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, OCCUPIED}, {OCCUPIED, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, OCCUPIED}, {OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED, OCCUPIED} }; public Coord getPosition() { return Coord.builder().build(); } public int[][] getRenderable() { return matrix; } public Renderable.Type getTypeOfRenderable() { return Renderable.Type.WELL; } public void add(Tetrimino tetrimino) throws InvalidMoveException { log.debug("Adding " + tetrimino.getType()); int x = (int) tetrimino.getPosition().getX(); int y = (int) tetrimino.getPosition().getY(); if (isPositionAllowed(tetrimino)) { matrix[y][x] = OCCUPIED; } else { throw new InvalidMoveException(); } } public boolean isPositionAllowed(Tetrimino tetrimino) { int x = (int) tetrimino.getPosition().getX(); int y = (int) tetrimino.getPosition().getY(); return (matrix[y][x] == SPACE); } }
package org.asciidoctor.extension; import java.util.List; public interface Reader { /** * Get the 1-based offset of the current line. * @return 1-based offset. */ int getLineno(); /** * Check whether there are any lines left to read. * If a previous call to this method resulted in a value of false, * immediately returned the cached value. Otherwise, delegate to * peek_line to determine if there is a next line available. * @return True if there are more lines, False if there are not. */ boolean hasMoreLines(); /** * Peek at the next line and check if it's empty (i.e., whitespace only) * * This method Does not consume the line from the stack. * @return True if the there are no more lines or if the next line is empty */ boolean isNextLineEmpty(); /** * Get the remaining lines of source data joined as a String. * Delegates to Reader#read_lines, then joins the result. * @return the lines read joined as a String */ String read(); /** * Get the remaining lines of source data. * This method calls Reader#read_line repeatedly until all lines are consumed * and returns the lines as a String Array. This method differs from * Reader#lines in that it processes each line in turn, hence triggering * any preprocessors implemented in sub-classes. * @return the lines read as a String Array */ List<String> readLines(); List<String> lines(); /** * Advance to the next line by discarding the line at the front of the stack * * @return a Boolean indicating whether there was a line to discard. */ void advance(); /** * * Public: Advance to the end of the reader, consuming all remaining lines */ void terminate(); }
package org.broad.igv.sam; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.event.AlignmentTrackEvent; import org.broad.igv.event.IGVEventBus; import org.broad.igv.event.IGVEventObserver; import org.broad.igv.feature.FeatureUtils; import org.broad.igv.feature.Locus; import org.broad.igv.feature.Range; import org.broad.igv.feature.Strand; import org.broad.igv.feature.genome.ChromosomeNameComparator; import org.broad.igv.feature.genome.Genome; import org.broad.igv.lists.GeneList; import org.broad.igv.prefs.Constants; import org.broad.igv.prefs.IGVPreferences; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.renderer.GraphicUtils; import org.broad.igv.sashimi.SashimiPlot; import org.broad.igv.session.Persistable; import org.broad.igv.session.Session; import org.broad.igv.tools.PFMExporter; import org.broad.igv.track.*; import org.broad.igv.ui.FontManager; import org.broad.igv.ui.IGV; import org.broad.igv.ui.InsertSizeSettingsDialog; import org.broad.igv.ui.color.ColorTable; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.ui.color.PaletteColorTable; import org.broad.igv.ui.panel.DataPanel; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.panel.IGVPopupMenu; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.ui.util.UIUtilities; import org.broad.igv.util.Pair; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.StringUtils; import org.broad.igv.util.blat.BlatClient; import org.broad.igv.util.collections.CollUtils; import org.broad.igv.util.extview.ExtendViewClient; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.geom.Rectangle2D; import java.text.NumberFormat; import java.util.*; import java.util.List; import static org.broad.igv.prefs.Constants.*; /** * @author jrobinso */ public class AlignmentTrack extends AbstractTrack implements IGVEventObserver { private static Logger log = Logger.getLogger(AlignmentTrack.class); public static final int GROUP_LABEL_HEIGHT = 10; static final int GROUP_MARGIN = 5; static final int TOP_MARGIN = 20; static final int DS_MARGIN_0 = 2; static final int DOWNAMPLED_ROW_HEIGHT = 3; static final int INSERTION_ROW_HEIGHT = 9; static final int DS_MARGIN_2 = 5; private final Genome genome; private ExperimentType experimentType; private final AlignmentRenderer renderer; private boolean removed = false; private RenderRollback renderRollback; private boolean showGroupLine; private Map<ReferenceFrame, List<InsertionInterval>> insertionIntervalsMap; private SequenceTrack sequenceTrack; private CoverageTrack coverageTrack; private SpliceJunctionTrack spliceJunctionTrack; RenderOptions renderOptions; private int expandedHeight = 14; private int collapsedHeight = 9; private int maxSquishedHeight = 5; private int squishedHeight = maxSquishedHeight; private int minHeight = 50; private AlignmentDataManager dataManager; public Rectangle alignmentsRect; private Rectangle downsampleRect; private Rectangle insertionRect; private ColorTable readNamePalette; // Dynamic fields // The "DataPanel" containing the track. This field might be null at any given time. It is updated each repaint. private JComponent dataPanel; private HashMap<String, Color> selectedReadNames = new HashMap(); private HashMap<Rectangle, String> groupNames = new HashMap<>(); public enum ShadeBasesOption { NONE, QUALITY } enum ColorOption { INSERT_SIZE, READ_STRAND, FIRST_OF_PAIR_STRAND, PAIR_ORIENTATION, SAMPLE, READ_GROUP, LIBRARY, MOVIE, ZMW, BISULFITE, NOMESEQ, TAG, NONE, UNEXPECTED_PAIR, MAPPED_SIZE, LINK_STRAND, YC_TAG } public enum SortOption { START, STRAND, NUCLEOTIDE, QUALITY, SAMPLE, READ_GROUP, INSERT_SIZE, FIRST_OF_PAIR_STRAND, MATE_CHR, TAG, SUPPLEMENTARY, NONE, HAPLOTYPE, READ_ORDER; } public enum GroupOption { STRAND, SAMPLE, READ_GROUP, LIBRARY, FIRST_OF_PAIR_STRAND, TAG, PAIR_ORIENTATION, MATE_CHROMOSOME, NONE, SUPPLEMENTARY, BASE_AT_POS, MOVIE, ZMW, HAPLOTYPE, READ_ORDER } public enum BisulfiteContext { CG, CHH, CHG, HCG, GCH, WCG, NONE } enum OrientationType { RR, LL, RL, LR, UNKNOWN } protected static final Map<BisulfiteContext, String> bisulfiteContextToPubString = new HashMap<BisulfiteContext, String>(); static { bisulfiteContextToPubString.put(BisulfiteContext.CG, "CG"); bisulfiteContextToPubString.put(BisulfiteContext.CHH, "CHH"); bisulfiteContextToPubString.put(BisulfiteContext.CHG, "CHG"); bisulfiteContextToPubString.put(BisulfiteContext.HCG, "HCG"); bisulfiteContextToPubString.put(BisulfiteContext.GCH, "GCH"); bisulfiteContextToPubString.put(BisulfiteContext.WCG, "WCG"); bisulfiteContextToPubString.put(BisulfiteContext.NONE, "None"); } protected static final Map<BisulfiteContext, Pair<byte[], byte[]>> bisulfiteContextToContextString = new HashMap<BisulfiteContext, Pair<byte[], byte[]>>(); static { bisulfiteContextToContextString.put(BisulfiteContext.CG, new Pair<byte[], byte[]>(new byte[]{}, new byte[]{'G'})); bisulfiteContextToContextString.put(BisulfiteContext.CHH, new Pair<byte[], byte[]>(new byte[]{}, new byte[]{'H', 'H'})); bisulfiteContextToContextString.put(BisulfiteContext.CHG, new Pair<byte[], byte[]>(new byte[]{}, new byte[]{'H', 'G'})); bisulfiteContextToContextString.put(BisulfiteContext.HCG, new Pair<byte[], byte[]>(new byte[]{'H'}, new byte[]{'G'})); bisulfiteContextToContextString.put(BisulfiteContext.GCH, new Pair<byte[], byte[]>(new byte[]{'G'}, new byte[]{'H'})); bisulfiteContextToContextString.put(BisulfiteContext.WCG, new Pair<byte[], byte[]>(new byte[]{'W'}, new byte[]{'G'})); } static final BisulfiteContext DEFAULT_BISULFITE_CONTEXT = BisulfiteContext.CG; public static void sortAlignmentTracks(SortOption option, String tag) { IGV.getInstance().sortAlignmentTracks(option, tag); Collection<IGVPreferences> allPrefs = PreferencesManager.getAllPreferences(); for (IGVPreferences prefs : allPrefs) { prefs.put(SAM_SORT_OPTION, option.toString()); prefs.put(SAM_SORT_BY_TAG, tag); } refresh(); } /** * Create a new alignment track * * @param locator * @param dataManager * @param genome */ public AlignmentTrack(ResourceLocator locator, AlignmentDataManager dataManager, Genome genome) { super(locator); this.dataManager = dataManager; this.dataManager.subscribe(this); this.genome = genome; setRenderOptions(new RenderOptions()); minimumHeight = 50; maximumHeight = Integer.MAX_VALUE; IGVPreferences prefs = getPreferences(); renderer = new AlignmentRenderer(this); showGroupLine = getPreferences().getAsBoolean(SAM_SHOW_GROUP_SEPARATOR); try { setDisplayMode(DisplayMode.valueOf(prefs.get(SAM_DISPLAY_MODE).toUpperCase())); } catch(Exception e) { setDisplayMode(DisplayMode.EXPANDED); } if (prefs.getAsBoolean(SAM_SHOW_REF_SEQ)) { sequenceTrack = new SequenceTrack("Reference sequence"); sequenceTrack.setHeight(14); } if (renderOptions.colorOption == ColorOption.BISULFITE) { setExperimentType(ExperimentType.BISULFITE); } readNamePalette = new PaletteColorTable(ColorUtilities.getDefaultPalette()); this.insertionIntervalsMap = Collections.synchronizedMap(new HashMap<>()); IGVEventBus.getInstance().subscribe(FrameManager.ChangeEvent.class, this); IGVEventBus.getInstance().subscribe(ExperimentTypeChangeEvent.class, this); IGVEventBus.getInstance().subscribe(AlignmentTrackEvent.class, this); } @Override public void receiveEvent(Object event) { if (event instanceof FrameManager.ChangeEvent) { // Trim insertionInterval map to current frames Map<ReferenceFrame, List<InsertionInterval>> newMap = Collections.synchronizedMap(new HashMap<>()); for (ReferenceFrame frame : ((FrameManager.ChangeEvent) event).getFrames()) { if (insertionIntervalsMap.containsKey(frame)) { newMap.put(frame, insertionIntervalsMap.get(frame)); } } insertionIntervalsMap = newMap; } else if (event instanceof ExperimentTypeChangeEvent) { if (experimentType == null) { log.info("Experiment type = " + ((ExperimentTypeChangeEvent) event).type); setExperimentType(((ExperimentTypeChangeEvent) event).type); } } else if (event instanceof AlignmentTrackEvent) { AlignmentTrackEvent e = (AlignmentTrackEvent) event; AlignmentTrackEvent.Type eventType = e.getType(); switch (eventType) { case ALLELE_THRESHOLD: dataManager.alleleThresholdChanged(); break; case RELOAD: clearCaches(); case REFRESH: renderOptions.refreshDefaults(getExperimentType()); refresh(); break; } } } private void setExperimentType(ExperimentType type) { if (type != experimentType) { experimentType = type; renderOptions.refreshDefaults(type); boolean showJunction = getPreferences(type).getAsBoolean(Constants.SAM_SHOW_JUNCTION_TRACK); if (showJunction != spliceJunctionTrack.isVisible()) { spliceJunctionTrack.setVisible(showJunction); IGV.getInstance().revalidateTrackPanels(); } boolean showCoverage = getPreferences(type).getAsBoolean(SAM_SHOW_COV_TRACK); if (showCoverage != coverageTrack.isVisible()) { coverageTrack.setVisible(showCoverage); IGV.getInstance().revalidateTrackPanels(); } boolean showAlignments = getPreferences(type).getAsBoolean(SAM_SHOW_ALIGNMENT_TRACK); if (showAlignments != isVisible()) { setVisible(showAlignments); IGV.getInstance().revalidateTrackPanels(); } } } private ExperimentType getExperimentType() { return experimentType; } public void setCoverageTrack(CoverageTrack coverageTrack) { this.coverageTrack = coverageTrack; } @Override public void setVisible(boolean visible) { if (visible != this.isVisible()) { super.setVisible(visible); if (IGV.hasInstance()) IGV.getInstance().getMainPanel().revalidate(); } } private void setRenderOptions(RenderOptions renderOptions) { this.renderOptions = renderOptions; } RenderOptions getRenderOptions() { return this.renderOptions; } public CoverageTrack getCoverageTrack() { return coverageTrack; } public void setSpliceJunctionTrack(SpliceJunctionTrack spliceJunctionTrack) { this.spliceJunctionTrack = spliceJunctionTrack; } public SpliceJunctionTrack getSpliceJunctionTrack() { return spliceJunctionTrack; } @Override public IGVPopupMenu getPopupMenu(TrackClickEvent te) { // Alignment alignment = getAlignment(te); // if (alignment != null && alignment.getInsertions() != null) { // for (AlignmentBlock block : alignment.getInsertions()) { // if (block.containsPixel(te.getMouseEvent().getX())) { // return new InsertionMenu(block); return new PopupMenu(te); } @Override public void setHeight(int preferredHeight) { super.setHeight(preferredHeight); minimumHeight = preferredHeight; } @Override public int getHeight() { if (dataPanel != null && (dataPanel instanceof DataPanel && ((DataPanel) dataPanel).getFrame().getScale() > dataManager.getMinVisibleScale())) { return minimumHeight; } int nGroups = dataManager.getMaxGroupCount(); int h = Math.max(minHeight, getNLevels() * getRowHeight() + nGroups * GROUP_MARGIN + TOP_MARGIN + DS_MARGIN_0 + DOWNAMPLED_ROW_HEIGHT + DS_MARGIN_2); //if (insertionRect != null) { // TODO - replace with expand insertions preference h += INSERTION_ROW_HEIGHT + DS_MARGIN_0; h = Math.min(maximumHeight, h); return h; } private int getRowHeight() { if (getDisplayMode() == DisplayMode.EXPANDED) { return expandedHeight; } else if (getDisplayMode() == DisplayMode.COLLAPSED) { return collapsedHeight; } else { return squishedHeight; } } private int getNLevels() { return dataManager.getNLevels(); } @Override public boolean isReadyToPaint(ReferenceFrame frame) { if (frame.getChrName().equals(Globals.CHR_ALL) || frame.getScale() > dataManager.getMinVisibleScale()) { return true; // Nothing to paint } else { List<InsertionInterval> insertionIntervals = getInsertionIntervals(frame); insertionIntervals.clear(); return dataManager.isLoaded(frame); } } @Override public void load(ReferenceFrame referenceFrame) { dataManager.load(referenceFrame, renderOptions, true); } public void render(RenderContext context, Rectangle rect) { Graphics2D g = context.getGraphics2D("LABEL"); g.setFont(FontManager.getFont(GROUP_LABEL_HEIGHT)); dataPanel = context.getPanel(); // Split track rectangle into sections. int seqHeight = sequenceTrack == null ? 0 : sequenceTrack.getHeight(); if (seqHeight > 0) { Rectangle seqRect = new Rectangle(rect); seqRect.height = seqHeight; sequenceTrack.render(context, seqRect); } // Top gap. rect.y += DS_MARGIN_0; if (context.getScale() > dataManager.getMinVisibleScale()) { Rectangle visibleRect = context.getVisibleRect().intersection(rect); Graphics2D g2 = context.getGraphic2DForColor(Color.gray); GraphicUtils.drawCenteredText("Zoom in to see alignments.", visibleRect, g2); return; } downsampleRect = new Rectangle(rect); downsampleRect.height = DOWNAMPLED_ROW_HEIGHT; renderDownsampledIntervals(context, downsampleRect); if (renderOptions.isDrawInsertionIntervals()) { insertionRect = new Rectangle(rect); insertionRect.y += DOWNAMPLED_ROW_HEIGHT + DS_MARGIN_0; insertionRect.height = INSERTION_ROW_HEIGHT; renderInsertionIntervals(context, insertionRect); rect.y = insertionRect.y + insertionRect.height; } alignmentsRect = new Rectangle(rect); alignmentsRect.y += 2; alignmentsRect.height -= (alignmentsRect.y - rect.y); renderAlignments(context, alignmentsRect); } private void renderDownsampledIntervals(RenderContext context, Rectangle downsampleRect) { // Might be offscreen if (!context.getVisibleRect().intersects(downsampleRect)) return; final AlignmentInterval loadedInterval = dataManager.getLoadedInterval(context.getReferenceFrame()); if (loadedInterval == null) return; Graphics2D g = context.getGraphic2DForColor(Color.black); List<DownsampledInterval> intervals = loadedInterval.getDownsampledIntervals(); for (DownsampledInterval interval : intervals) { final double scale = context.getScale(); final double origin = context.getOrigin(); int x0 = (int) ((interval.getStart() - origin) / scale); int x1 = (int) ((interval.getEnd() - origin) / scale); int w = Math.max(1, x1 - x0); // If there is room, leave a gap on one side if (w > 5) w // Greyscale from 0 -> 100 downsampled //int gray = 200 - interval.getCount(); //Color color = (gray <= 0 ? Color.black : ColorUtilities.getGrayscaleColor(gray)); g.fillRect(x0, downsampleRect.y, w, downsampleRect.height); } } private List<InsertionInterval> getInsertionIntervals(ReferenceFrame frame) { List<InsertionInterval> insertionIntervals = insertionIntervalsMap.get(frame); if (insertionIntervals == null) { insertionIntervals = new ArrayList<>(); insertionIntervalsMap.put(frame, insertionIntervals); } return insertionIntervals; } private void renderInsertionIntervals(RenderContext context, Rectangle rect) { // Might be offscreen if (!context.getVisibleRect().intersects(rect)) return; List<InsertionMarker> intervals = context.getInsertionMarkers(); if (intervals == null) return; InsertionMarker selected = InsertionManager.getInstance().getSelectedInsertion(context.getChr()); int w = (int) ((1.41 * rect.height) / 2); boolean hideSmallIndex = getPreferences().getAsBoolean(SAM_HIDE_SMALL_INDEL); int smallIndelThreshold = getPreferences().getAsInt(SAM_SMALL_INDEL_BP_THRESHOLD); List<InsertionInterval> insertionIntervals = getInsertionIntervals(context.getReferenceFrame()); insertionIntervals.clear(); for (InsertionMarker insertionMarker : intervals) { if (hideSmallIndex && insertionMarker.size < smallIndelThreshold) continue; final double scale = context.getScale(); final double origin = context.getOrigin(); int midpoint = (int) ((insertionMarker.position - origin) / scale); int x0 = midpoint - w; int x1 = midpoint + w; Rectangle iRect = new Rectangle(x0 + context.translateX, rect.y, 2 * w, rect.height); insertionIntervals.add(new InsertionInterval(iRect, insertionMarker)); Color c = (selected != null && selected.position == insertionMarker.position) ? new Color(200, 0, 0, 80) : AlignmentRenderer.purple; Graphics2D g = context.getGraphic2DForColor(c); g.fillPolygon(new Polygon(new int[]{x0, x1, midpoint}, new int[]{rect.y, rect.y, rect.y + rect.height}, 3)); } } private void renderAlignments(RenderContext context, Rectangle inputRect) { groupNames.clear(); RenderOptions renderOptions = PreferencesManager.forceDefaults ? new RenderOptions() : this.renderOptions; //log.debug("Render features"); PackedAlignments groups = dataManager.getGroups(context, renderOptions); if (groups == null) { //Assume we are still loading. //This might not always be true return; } // Check for YC tag if (renderOptions.colorOption == null && dataManager.hasYCTags()) { renderOptions.colorOption = ColorOption.YC_TAG; } Map<String, PEStats> peStats = dataManager.getPEStats(); if (peStats != null) { renderOptions.peStats = peStats; } Rectangle visibleRect = context.getVisibleRect(); final boolean leaveMargin = (getDisplayMode() != DisplayMode.SQUISHED); maximumHeight = Integer.MAX_VALUE; // Divide rectangle into equal height levels double y = inputRect.getY(); double h; if (getDisplayMode() == DisplayMode.EXPANDED) { h = expandedHeight; } else if (getDisplayMode() == DisplayMode.COLLAPSED) { h = collapsedHeight; } else { int visHeight = visibleRect.height; int depth = dataManager.getNLevels(); if (depth == 0) { squishedHeight = Math.min(maxSquishedHeight, Math.max(1, expandedHeight)); } else { squishedHeight = Math.min(maxSquishedHeight, Math.max(1, Math.min(expandedHeight, visHeight / depth))); } h = squishedHeight; } // Loop through groups Graphics2D groupBorderGraphics = context.getGraphic2DForColor(AlignmentRenderer.GROUP_DIVIDER_COLOR); int nGroups = groups.size(); int groupNumber = 0; GroupOption groupOption = renderOptions.getGroupByOption(); for (Map.Entry<String, List<Row>> entry : groups.entrySet()) { groupNumber++; double yGroup = y; // Remember this for label // Loop through the alignment rows for this group List<Row> rows = entry.getValue(); for (Row row : rows) { if ((visibleRect != null && y > visibleRect.getMaxY())) { return; } if (y + h > visibleRect.getY()) { Rectangle rowRectangle = new Rectangle(inputRect.x, (int) y, inputRect.width, (int) h); AlignmentCounts alignmentCounts = dataManager.getLoadedInterval(context.getReferenceFrame()).getCounts(); renderer.renderAlignments(row.alignments, context, rowRectangle, inputRect, renderOptions, leaveMargin, selectedReadNames, alignmentCounts, getPreferences()); row.y = y; row.h = h; } y += h; } if (groupOption != GroupOption.NONE) { // Draw a subtle divider line between groups if (showGroupLine) { if (groupNumber < nGroups) { int borderY = (int) y + GROUP_MARGIN / 2; GraphicUtils.drawDottedDashLine(groupBorderGraphics, inputRect.x, borderY, inputRect.width, borderY); } } // Label the group, if there is room double groupHeight = rows.size() * h; if (groupHeight > GROUP_LABEL_HEIGHT + 2) { String groupName = entry.getKey(); Graphics2D g = context.getGraphics2D("LABEL"); FontMetrics fm = g.getFontMetrics(); Rectangle2D stringBouds = fm.getStringBounds(groupName, g); Rectangle rect = new Rectangle(inputRect.x, (int) yGroup, (int) stringBouds.getWidth() + 10, (int) stringBouds.getHeight()); GraphicUtils.drawVerticallyCenteredText( groupName, 5, rect, context.getGraphics2D("LABEL"), false, true); groupNames.put(new Rectangle(inputRect.x, (int) yGroup, inputRect.width, (int) (y - yGroup)), groupName); } } y += GROUP_MARGIN; } final int bottom = inputRect.y + inputRect.height; groupBorderGraphics.drawLine(inputRect.x, bottom, inputRect.width, bottom); } public void renderExpandedInsertion(InsertionMarker insertionMarker, RenderContext context, Rectangle inputRect) { boolean leaveMargin = getDisplayMode() != DisplayMode.COLLAPSED.SQUISHED; // Insertion interval Graphics2D g = context.getGraphic2DForColor(Color.red); Rectangle iRect = new Rectangle(inputRect.x, insertionRect.y, inputRect.width, insertionRect.height); g.fill(iRect); List<InsertionInterval> insertionIntervals = getInsertionIntervals(context.getReferenceFrame()); iRect.x += context.translateX; insertionIntervals.add(new InsertionInterval(iRect, insertionMarker)); inputRect.y += DS_MARGIN_0 + DOWNAMPLED_ROW_HEIGHT + DS_MARGIN_0 + INSERTION_ROW_HEIGHT + DS_MARGIN_2; //log.debug("Render features"); PackedAlignments groups = dataManager.getGroups(context, renderOptions); if (groups == null) { //Assume we are still loading. //This might not always be true return; } Rectangle visibleRect = context.getVisibleRect(); maximumHeight = Integer.MAX_VALUE; // Divide rectangle into equal height levels double y = inputRect.getY() - 3; double h; if (getDisplayMode() == DisplayMode.EXPANDED) { h = expandedHeight; } else if (getDisplayMode() == DisplayMode.COLLAPSED) { h = collapsedHeight; } else { int visHeight = visibleRect.height; int depth = dataManager.getNLevels(); if (depth == 0) { squishedHeight = Math.min(maxSquishedHeight, Math.max(1, expandedHeight)); } else { squishedHeight = Math.min(maxSquishedHeight, Math.max(1, Math.min(expandedHeight, visHeight / depth))); } h = squishedHeight; } for (Map.Entry<String, List<Row>> entry : groups.entrySet()) { // Loop through the alignment rows for this group List<Row> rows = entry.getValue(); for (Row row : rows) { if ((visibleRect != null && y > visibleRect.getMaxY())) { return; } if (y + h > visibleRect.getY()) { Rectangle rowRectangle = new Rectangle(inputRect.x, (int) y, inputRect.width, (int) h); renderer.renderExpandedInsertion(insertionMarker, row.alignments, context, rowRectangle, leaveMargin); row.y = y; row.h = h; } y += h; } y += GROUP_MARGIN; } } // public void renderExpandedInsertions(RenderContext context, Rectangle inputRect) { // boolean leaveMargin = getDisplayMode() != DisplayMode.COLLAPSED.SQUISHED; // inputRect.y += DOWNAMPLED_ROW_HEIGHT + DS_MARGIN_2; // //log.debug("Render features"); // PackedAlignments groups = dataManager.getGroups(context, renderOptions); // if (groups == null) { // //Assume we are still loading. // //This might not always be true // return; // Rectangle visibleRect = context.getVisibleRect(); // maximumHeight = Integer.MAX_VALUE; // // Divide rectangle into equal height levels // double y = inputRect.getY(); // double h; // if (getDisplayMode() == DisplayMode.EXPANDED) { // h = expandedHeight; // } else { // int visHeight = visibleRect.height; // int depth = dataManager.getNLevels(); // if (depth == 0) { // squishedHeight = Math.min(maxSquishedHeight, Math.max(1, expandedHeight)); // } else { // squishedHeight = Math.min(maxSquishedHeight, Math.max(1, Math.min(expandedHeight, visHeight / depth))); // h = squishedHeight; // for (Map.Entry<String, List<Row>> entry : groups.entrySet()) { // // Loop through the alignment rows for this group // List<Row> rows = entry.getValue(); // for (Row row : rows) { // if ((visibleRect != null && y > visibleRect.getMaxY())) { // return; // if (y + h > visibleRect.getY()) { // Rectangle rowRectangle = new Rectangle(inputRect.x, (int) y, inputRect.width, (int) h); // renderer.renderExpandedInsertions(row.alignments, context, rowRectangle, leaveMargin); // row.y = y; // row.h = h; // y += h; // y += GROUP_MARGIN; /** * Sort alignment rows based on alignments that intersect location * * @return Whether sorting was performed. If data is still loading, this will return false */ public boolean sortRows(SortOption option, ReferenceFrame referenceFrame, double location, String tag) { return dataManager.sortRows(option, referenceFrame, location, tag); } /** * Visually regroup alignments by the provided {@code GroupOption}. * * @param option * @see AlignmentDataManager#packAlignments */ public void groupAlignments(GroupOption option, String tag, Range pos) { if (option == GroupOption.TAG && tag != null) { renderOptions.setGroupByTag(tag); } if (option == GroupOption.BASE_AT_POS && pos != null) { renderOptions.setGroupByPos(pos); } renderOptions.setGroupByOption(option); dataManager.packAlignments(renderOptions); } public void packAlignments() { dataManager.packAlignments(renderOptions); } /** * Copy the contents of the popup text to the system clipboard. */ public void copyToClipboard(final TrackClickEvent e, Alignment alignment, double location, int mouseX) { if (alignment != null) { StringBuffer buf = new StringBuffer(); buf.append(alignment.getValueString(location, mouseX, null).replace("<br>", "\n")); buf.append("\n"); buf.append("Alignment start position = " + alignment.getChr() + ":" + (alignment.getAlignmentStart() + 1)); buf.append("\n"); buf.append(alignment.getReadSequence()); StringSelection stringSelection = new StringSelection(buf.toString()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); } } /** * Jump to the mate region */ public void gotoMate(final TrackClickEvent te, Alignment alignment) { if (alignment != null) { ReadMate mate = alignment.getMate(); if (mate != null && mate.isMapped()) { setSelected(alignment); String chr = mate.getChr(); int start = mate.start - 1; // Don't change scale double range = te.getFrame().getEnd() - te.getFrame().getOrigin(); int newStart = (int) Math.max(0, (start + (alignment.getEnd() - alignment.getStart()) / 2 - range / 2)); int newEnd = newStart + (int) range; te.getFrame().jumpTo(chr, newStart, newEnd); te.getFrame().recordHistory(); } else { MessageUtils.showMessage("Alignment does not have mate, or it is not mapped."); } } } /** * Split the screen so the current view and mate region are side by side. * Need a better name for this method. */ public void splitScreenMate(final TrackClickEvent te, Alignment alignment) { if (alignment != null) { ReadMate mate = alignment.getMate(); if (mate != null && mate.isMapped()) { setSelected(alignment); String mateChr = mate.getChr(); int mateStart = mate.start - 1; ReferenceFrame frame = te.getFrame(); String locus1 = frame.getFormattedLocusString(); // Generate a locus string for the read mate. Keep the window width (in base pairs) == to the current range Range range = frame.getCurrentRange(); int length = range.getLength(); int s2 = Math.max(0, mateStart - length / 2); int e2 = s2 + length; String startStr = NumberFormat.getInstance().format(s2); String endStr = NumberFormat.getInstance().format(e2); String mateLocus = mateChr + ":" + startStr + "-" + endStr; Session currentSession = IGV.getInstance().getSession(); List<String> loci = null; if (FrameManager.isGeneListMode()) { loci = new ArrayList<>(FrameManager.getFrames().size()); for (ReferenceFrame ref : FrameManager.getFrames()) { //If the frame-name is a locus, we use it unaltered //Don't want to reprocess, easy to get off-by-one String name = ref.getName(); if (Locus.fromString(name) != null) { loci.add(name); } else { loci.add(ref.getFormattedLocusString()); } } loci.add(mateLocus); } else { loci = Arrays.asList(locus1, mateLocus); } StringBuffer listName = new StringBuffer(); for (String s : loci) { listName.append(s + " "); } GeneList geneList = new GeneList(listName.toString(), loci, false); currentSession.setCurrentGeneList(geneList); Comparator<String> geneListComparator = new Comparator<String>() { @Override public int compare(String n0, String n1) { ReferenceFrame f0 = FrameManager.getFrame(n0); ReferenceFrame f1 = FrameManager.getFrame(n1); String chr0 = f0 == null ? "" : f0.getChrName(); String chr1 = f1 == null ? "" : f1.getChrName(); int s0 = f0 == null ? 0 : f0.getCurrentRange().getStart(); int s1 = f1 == null ? 0 : f1.getCurrentRange().getStart(); int chrComp = ChromosomeNameComparator.get().compare(chr0, chr1); if (chrComp != 0) return chrComp; return s0 - s1; } }; //Need to sort the frames by position currentSession.sortGeneList(geneListComparator); IGV.getInstance().resetFrames(); } else { MessageUtils.showMessage("Alignment does not have mate, or it is not mapped."); } } } public boolean isLogNormalized() { return false; } public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType type, String frameName) { return 0.0f; } public AlignmentDataManager getDataManager() { return dataManager; } public String getValueStringAt(String chr, double position, int mouseX, int mouseY, ReferenceFrame frame) { if (downsampleRect != null && mouseY > downsampleRect.y && mouseY <= downsampleRect.y + downsampleRect.height) { AlignmentInterval loadedInterval = dataManager.getLoadedInterval(frame); if (loadedInterval == null) { return null; } else { List<DownsampledInterval> intervals = loadedInterval.getDownsampledIntervals(); DownsampledInterval interval = (DownsampledInterval) FeatureUtils.getFeatureAt(position, 0, intervals); if (interval != null) { return interval.getValueString(); } return null; } } else { InsertionInterval insertionInterval = getInsertionInterval(frame, mouseX, mouseY); if (insertionInterval != null) { return "Insertions (" + insertionInterval.insertionMarker.size + " bases)"; } else { Alignment feature = getAlignmentAt(position, mouseY, frame); if (feature != null) { return feature.getValueString(position, mouseX, getWindowFunction()); } else { for (Map.Entry<Rectangle, String> groupNameEntry : groupNames.entrySet()) { Rectangle r = groupNameEntry.getKey(); if (mouseY >= r.y && mouseY < r.y + r.height) { return groupNameEntry.getValue(); } } } } } return null; } private Alignment getAlignment(final TrackClickEvent te) { MouseEvent e = te.getMouseEvent(); final ReferenceFrame frame = te.getFrame(); if (frame == null) { return null; } final double location = frame.getChromosomePosition(e.getX()); return getAlignmentAt(location, e.getY(), frame); } private Alignment getAlignmentAt(double position, int y, ReferenceFrame frame) { if (alignmentsRect == null || dataManager == null) { return null; // <= not loaded yet } PackedAlignments groups = dataManager.getGroupedAlignmentsContaining(position, frame); if (groups == null || groups.isEmpty()) { return null; } for (List<Row> rows : groups.values()) { for (Row row : rows) { if (y >= row.y && y <= row.y + row.h) { List<Alignment> features = row.alignments; // No buffer for alignments, you must zoom in far enough for them to be visible int buffer = 0; return FeatureUtils.getFeatureAt(position, buffer, features); } } } return null; } /** * Get the most "specific" alignment at the specified location. Specificity refers to the smallest alignemnt * in a group that contains the location (i.e. if a group of linked alignments overlap take the smallest one). * * @param te * @return */ private Alignment getSpecficAlignment(TrackClickEvent te) { Alignment alignment = getAlignment(te); if (alignment != null) { final ReferenceFrame frame = te.getFrame(); MouseEvent e = te.getMouseEvent(); final double location = frame.getChromosomePosition(e.getX()); if (alignment instanceof LinkedAlignment) { Alignment sa = null; for (Alignment a : ((LinkedAlignment) alignment).alignments) { if (a.contains(location)) { if (sa == null || (a.getAlignmentEnd() - a.getAlignmentStart() < sa.getAlignmentEnd() - sa.getAlignmentStart())) { sa = a; } } } alignment = sa; } else if (alignment instanceof PairedAlignment) { Alignment sa = null; if (((PairedAlignment) alignment).firstAlignment.contains(location)) { sa = ((PairedAlignment) alignment).firstAlignment; } else if (((PairedAlignment) alignment).secondAlignment.contains(location)) { sa = ((PairedAlignment) alignment).secondAlignment; } alignment = sa; } } return alignment; } @Override public boolean handleDataClick(TrackClickEvent te) { MouseEvent e = te.getMouseEvent(); if (Globals.IS_MAC && e.isMetaDown() || (!Globals.IS_MAC && e.isControlDown())) { // Selection final ReferenceFrame frame = te.getFrame(); if (frame != null) { selectAlignment(e, frame); if (dataPanel != null) { dataPanel.repaint(); } return true; } } InsertionInterval insertionInterval = getInsertionInterval(te.getFrame(), te.getMouseEvent().getX(), te.getMouseEvent().getY()); if (insertionInterval != null) { final String chrName = te.getFrame().getChrName(); InsertionMarker currentSelection = InsertionManager.getInstance().getSelectedInsertion(chrName); if (currentSelection != null && currentSelection.position == insertionInterval.insertionMarker.position) { InsertionManager.getInstance().clearSelected(); } else { InsertionManager.getInstance().setSelected(chrName, insertionInterval.insertionMarker.position); } IGVEventBus.getInstance().post(new InsertionSelectionEvent(insertionInterval.insertionMarker)); return true; } if (IGV.getInstance().isShowDetailsOnClick()) { openTooltipWindow(te); return true; } return false; } private void selectAlignment(MouseEvent e, ReferenceFrame frame) { double location = frame.getChromosomePosition(e.getX()); Alignment alignment = this.getAlignmentAt(location, e.getY(), frame); if (alignment != null) { if (selectedReadNames.containsKey(alignment.getReadName())) { selectedReadNames.remove(alignment.getReadName()); } else { setSelected(alignment); } } } private InsertionInterval getInsertionInterval(ReferenceFrame frame, int x, int y) { List<InsertionInterval> insertionIntervals = getInsertionIntervals(frame); for (InsertionInterval i : insertionIntervals) { if (i.rect.contains(x, y)) return i; } return null; } private void setSelected(Alignment alignment) { Color c = readNamePalette.get(alignment.getReadName()); selectedReadNames.put(alignment.getReadName(), c); } public void clearCaches() { if (dataManager != null) dataManager.clear(); if (spliceJunctionTrack != null) spliceJunctionTrack.clear(); } public static void refresh() { IGV.getInstance().getContentPane().getMainPanel().invalidate(); IGV.getInstance().revalidateTrackPanels(); } public static boolean isBisulfiteColorType(ColorOption o) { return (o.equals(ColorOption.BISULFITE) || o.equals(ColorOption.NOMESEQ)); } public static String getBisulfiteContextPubStr(BisulfiteContext item) { return bisulfiteContextToPubString.get(item); } public static byte[] getBisulfiteContextPreContext(BisulfiteContext item) { Pair<byte[], byte[]> pair = AlignmentTrack.bisulfiteContextToContextString.get(item); return pair.getFirst(); } public static byte[] getBisulfiteContextPostContext(BisulfiteContext item) { Pair<byte[], byte[]> pair = AlignmentTrack.bisulfiteContextToContextString.get(item); return pair.getSecond(); } public void setViewAsPairs(boolean vAP) { // TODO -- generalize this test to all incompatible pairings if (vAP && renderOptions.groupByOption == GroupOption.STRAND) { boolean ungroup = MessageUtils.confirm("\"View as pairs\" is incompatible with \"Group by strand\". Ungroup?"); if (ungroup) { renderOptions.setGroupByOption(null); } else { return; } } dataManager.setViewAsPairs(vAP, renderOptions); refresh(); } public enum ExperimentType {OTHER, RNA, BISULFITE, THIRD_GEN} class RenderRollback { ColorOption colorOption; GroupOption groupByOption; String groupByTag; String colorByTag; String linkByTag; DisplayMode displayMode; int expandedHeight; boolean showGroupLine; RenderRollback(RenderOptions renderOptions, DisplayMode displayMode) { this.colorOption = renderOptions.colorOption; this.groupByOption = renderOptions.groupByOption; this.colorByTag = renderOptions.colorByTag; this.groupByTag = renderOptions.groupByTag; this.displayMode = displayMode; this.expandedHeight = AlignmentTrack.this.expandedHeight; this.showGroupLine = AlignmentTrack.this.showGroupLine; this.linkByTag = renderOptions.linkByTag; } void restore(RenderOptions renderOptions) { renderOptions.colorOption = this.colorOption; renderOptions.groupByOption = this.groupByOption; renderOptions.colorByTag = this.colorByTag; renderOptions.groupByTag = this.groupByTag; renderOptions.linkByTag = this.linkByTag; AlignmentTrack.this.expandedHeight = this.expandedHeight; AlignmentTrack.this.showGroupLine = this.showGroupLine; AlignmentTrack.this.setDisplayMode(this.displayMode); } } public boolean isRemoved() { return removed; } IGVPreferences getPreferences() { return getPreferences(experimentType); } private static IGVPreferences getPreferences(ExperimentType type) { try { // Disable experimentType preferences for 2.4 if (Globals.VERSION.contains("2.4")) { return PreferencesManager.getPreferences(NULL_CATEGORY); } else { String prefKey = Constants.NULL_CATEGORY; if (type == ExperimentType.THIRD_GEN) { prefKey = Constants.THIRD_GEN; } else if (type == ExperimentType.RNA) { prefKey = Constants.RNA; } return PreferencesManager.getPreferences(prefKey); } } catch (NullPointerException e) { String prefKey = Constants.NULL_CATEGORY; if (type == ExperimentType.THIRD_GEN) { prefKey = Constants.THIRD_GEN; } else if (type == ExperimentType.RNA) { prefKey = Constants.RNA; } return PreferencesManager.getPreferences(prefKey); } } @Override public void dispose() { super.dispose(); clearCaches(); if (dataManager != null) { dataManager.unsubscribe(this); } dataManager = null; removed = true; setVisible(false); } public boolean isLinkedReads() { return renderOptions.isLinkedReads(); } public void setLinkedReads(boolean linkedReads, String tag) { renderOptions.setLinkedReads(linkedReads); if (linkedReads == true) { if (renderRollback == null) renderRollback = new RenderRollback(renderOptions, getDisplayMode()); renderOptions.setLinkByTag(tag); if ("READNAME".equals(tag)) { renderOptions.setColorOption(ColorOption.LINK_STRAND); } else { // TenX -- ditto renderOptions.setColorOption(ColorOption.TAG); renderOptions.setColorByTag(tag); if (dataManager.isPhased()) { renderOptions.setGroupByOption(GroupOption.TAG); renderOptions.setGroupByTag("HP"); } expandedHeight = 10; showGroupLine = false; setDisplayMode(DisplayMode.SQUISHED); } } else { if (this.renderRollback != null) { this.renderRollback.restore(renderOptions); this.renderRollback = null; } } dataManager.packAlignments(renderOptions); refresh(); } /** * Listener for deselecting one component when another is selected */ private static class Deselector implements ActionListener { private JMenuItem toDeselect; private JMenuItem parent; Deselector(JMenuItem parent, JMenuItem toDeselect) { this.parent = parent; this.toDeselect = toDeselect; } @Override public void actionPerformed(ActionEvent e) { if (this.parent.isSelected()) { this.toDeselect.setSelected(false); } } } private static class InsertionInterval { Rectangle rect; InsertionMarker insertionMarker; public InsertionInterval(Rectangle rect, InsertionMarker insertionMarker) { this.rect = rect; this.insertionMarker = insertionMarker; } } static int nClusters = 2; class PopupMenu extends IGVPopupMenu { PopupMenu(final TrackClickEvent e) { final MouseEvent me = e.getMouseEvent(); ReferenceFrame frame = e.getFrame(); Alignment clickedAlignment = null; if (frame != null) { double location = frame.getChromosomePosition(me.getX()); clickedAlignment = frame == null ? null : getAlignmentAt(location, me.getY(), frame); } Collection<Track> tracks = new ArrayList(); tracks.add(AlignmentTrack.this); JLabel popupTitle = new JLabel(" " + AlignmentTrack.this.getName(), JLabel.CENTER); Font newFont = getFont().deriveFont(Font.BOLD, 12); popupTitle.setFont(newFont); if (popupTitle != null) { add(popupTitle); } addSeparator(); add(TrackMenuUtils.getTrackRenameItem(tracks)); addCopyToClipboardItem(e, clickedAlignment); // addSeparator(); // addExpandInsertions(); if (dataManager.inferredExperimentType == ExperimentType.THIRD_GEN) { addHaplotype(e); } if (dataManager.isTenX()) { addTenXItems(); } else { addSupplItems(); // Are SA tags mutually exlcusive with 10X? } addSeparator(); addGroupMenuItem(e); addSortMenuItem(); addColorByMenuItem(); addPackMenuItem(); addSeparator(); addShadeBaseByMenuItem(); JMenuItem misMatchesItem = addShowMismatchesMenuItem(); JMenuItem showAllItem = addShowAllBasesMenuItem(); misMatchesItem.addActionListener(new Deselector(misMatchesItem, showAllItem)); showAllItem.addActionListener(new Deselector(showAllItem, misMatchesItem)); addQuickConsensusModeItem(); addSeparator(); addViewAsPairsMenuItem(); if (clickedAlignment != null) { addGoToMate(e, clickedAlignment); showMateRegion(e, clickedAlignment); } addInsertSizeMenuItem(); addSeparator(); TrackMenuUtils.addDisplayModeItems(tracks, this); addSeparator(); addSelectByNameItem(); addClearSelectionsMenuItem(); addSeparator(); addCopySequenceItem(e); addBlatItem(e); addConsensusSequence(e); AlignmentBlock insertion = getInsertion(clickedAlignment, e.getMouseEvent().getX()); if (insertion != null) { addSeparator(); addInsertionItems(insertion); } boolean showSashimi = true;//Globals.isDevelopment(); if (showSashimi) { addSeparator(); JMenuItem sashimi = new JMenuItem("Sashimi Plot"); sashimi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SashimiPlot.getSashimiPlot(null); } }); add(sashimi); } addSeparator(); addShowItems(); if (getPreferences().get(Constants.EXTVIEW_URL) != null) { addSeparator(); addExtViewItem(e); } } /** * Item for exporting "consensus" sequence of region, based * on loaded alignments. * * @param e */ private void addHaplotype(TrackClickEvent e) { //Export consensus sequence JMenuItem item = new JMenuItem("Cluster (phase) alignments"); final ReferenceFrame frame; if (e.getFrame() == null && FrameManager.getFrames().size() == 1) { frame = FrameManager.getFrames().get(0); } else { frame = e.getFrame(); } item.setEnabled(frame != null); add(item); item.addActionListener(ae -> { //This shouldn't ever be true, but just in case it's more user-friendly if (frame == null) { MessageUtils.showMessage("Unknown region bounds"); return; } String nString = MessageUtils.showInputDialog("Enter the number of clusters", String.valueOf(AlignmentTrack.nClusters)); if (nString == null) { return; } try { AlignmentTrack.nClusters = Integer.parseInt(nString); } catch (NumberFormatException e1) { MessageUtils.showMessage("Clusters size must be an integer"); return; } final int start = (int) frame.getOrigin(); final int end = (int) frame.getEnd(); AlignmentInterval interval = dataManager.getLoadedInterval(frame); HaplotypeUtils haplotypeUtils = new HaplotypeUtils(interval, AlignmentTrack.this.genome); haplotypeUtils.clusterAlignments(frame.getChrName(), start, end, AlignmentTrack.nClusters); AlignmentTrack.this.groupAlignments(GroupOption.HAPLOTYPE, null, null); AlignmentTrack.refresh(); //dataManager.sortRows(SortOption.HAPLOTYPE, frame, (end + start) / 2, null); //AlignmentTrack.refresh(); }); } public JMenuItem addExpandInsertions() { final JMenuItem item = new JCheckBoxMenuItem("Expand insertions"); final Session session = IGV.getInstance().getSession(); item.setSelected(session.expandInsertions); item.addActionListener(aEvt -> { session.expandInsertions = !session.expandInsertions; refresh(); }); add(item); return item; } /** * Item for exporting "consensus" sequence of region, based * on loaded alignments. * * @param e */ private void addConsensusSequence(TrackClickEvent e) { //Export consensus sequence JMenuItem item = new JMenuItem("Copy consensus sequence"); final ReferenceFrame frame; if (e.getFrame() == null && FrameManager.getFrames().size() == 1) { frame = FrameManager.getFrames().get(0); } else { frame = e.getFrame(); } item.setEnabled(frame != null); add(item); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //This shouldn't ever be true, but just in case it's more user-friendly if (frame == null) { MessageUtils.showMessage("Unknown region bounds, cannot export consensus"); return; } final int start = (int) frame.getOrigin(); final int end = (int) frame.getEnd(); if ((end - start) > 1000000) { MessageUtils.showMessage("Cannot export region more than 1 Megabase"); return; } AlignmentInterval interval = dataManager.getLoadedInterval(frame); AlignmentCounts counts = interval.getCounts(); String text = PFMExporter.createPFMText(counts, frame.getChrName(), start, end); StringUtils.copyTextToClipboard(text); } }); } private JMenu getBisulfiteContextMenuItem(ButtonGroup group) { // Change track height by attribute //JMenu bisulfiteContextMenu = new JMenu("Bisulfite Contexts"); JMenu bisulfiteContextMenu = new JMenu("bisulfite mode"); JRadioButtonMenuItem nomeESeqOption = null; boolean showNomeESeq = getPreferences().getAsBoolean(SAM_NOMESEQ_ENABLED); if (showNomeESeq) { nomeESeqOption = new JRadioButtonMenuItem("NOMe-seq bisulfite mode"); nomeESeqOption.setSelected(renderOptions.getColorOption() == ColorOption.NOMESEQ); nomeESeqOption.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { setColorOption(ColorOption.NOMESEQ); refresh(); } }); group.add(nomeESeqOption); } for (final BisulfiteContext item : BisulfiteContext.values()) { String optionStr = getBisulfiteContextPubStr(item); JRadioButtonMenuItem m1 = new JRadioButtonMenuItem(optionStr); m1.setSelected(renderOptions.bisulfiteContext == item); m1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { setColorOption(ColorOption.BISULFITE); setBisulfiteContext(item); refresh(); } }); bisulfiteContextMenu.add(m1); group.add(m1); } if (nomeESeqOption != null) { bisulfiteContextMenu.add(nomeESeqOption); } return bisulfiteContextMenu; } public void addSelectByNameItem() { // Change track height by attribute JMenuItem item = new JMenuItem("Select by name..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { String val = MessageUtils.showInputDialog("Enter read name: "); if (val != null && val.trim().length() > 0) { selectedReadNames.put(val, readNamePalette.get(val)); refresh(); } } }); add(item); } private JCheckBoxMenuItem getGroupMenuItem(String label, final GroupOption option) { JCheckBoxMenuItem mi = new JCheckBoxMenuItem(label); mi.setSelected(renderOptions.getGroupByOption() == option); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { IGV.getInstance().groupAlignmentTracks(option, null, null); refresh(); } }); return mi; } public void addGroupMenuItem(final TrackClickEvent te) {//ReferenceFrame frame) { final MouseEvent me = te.getMouseEvent(); ReferenceFrame frame = te.getFrame(); if (frame == null) { frame = FrameManager.getDefaultFrame(); // Clicked over name panel, not a specific frame } final Range range = frame.getCurrentRange(); final String chrom = range.getChr(); final int chromStart = (int) frame.getChromosomePosition(me.getX()); // Change track height by attribute JMenu groupMenu = new JMenu("Group alignments by"); ButtonGroup group = new ButtonGroup(); Map<String, GroupOption> mappings = new LinkedHashMap<String, GroupOption>(); mappings.put("none", GroupOption.NONE); mappings.put("read strand", GroupOption.STRAND); mappings.put("first-in-pair strand", GroupOption.FIRST_OF_PAIR_STRAND); mappings.put("sample", GroupOption.SAMPLE); mappings.put("library", GroupOption.LIBRARY); mappings.put("read group", GroupOption.READ_GROUP); mappings.put("chromosome of mate", GroupOption.MATE_CHROMOSOME); mappings.put("pair orientation", GroupOption.PAIR_ORIENTATION); mappings.put("supplementary flag", GroupOption.SUPPLEMENTARY); mappings.put("movie", GroupOption.MOVIE); mappings.put("ZMW", GroupOption.ZMW); mappings.put("read order", GroupOption.READ_ORDER); for (Map.Entry<String, GroupOption> el : mappings.entrySet()) { JCheckBoxMenuItem mi = getGroupMenuItem(el.getKey(), el.getValue()); groupMenu.add(mi); group.add(mi); } JCheckBoxMenuItem tagOption = new JCheckBoxMenuItem("tag"); tagOption.addActionListener(aEvt -> { String tag = MessageUtils.showInputDialog("Enter tag", renderOptions.getGroupByTag()); if (tag != null && tag.trim().length() > 0) { IGV.getInstance().groupAlignmentTracks(GroupOption.TAG, tag, null); refresh(); } }); tagOption.setSelected(renderOptions.getGroupByOption() == GroupOption.TAG); groupMenu.add(tagOption); group.add(tagOption); Range oldGroupByPos = renderOptions.getGroupByPos(); if (renderOptions.getGroupByOption() == GroupOption.BASE_AT_POS) { // already sorted by the base at a position JCheckBoxMenuItem oldGroupByPosOption = new JCheckBoxMenuItem("base at " + oldGroupByPos.getChr() + ":" + Globals.DECIMAL_FORMAT.format(1 + oldGroupByPos.getStart())); groupMenu.add(oldGroupByPosOption); oldGroupByPosOption.setSelected(true); } if (renderOptions.getGroupByOption() != GroupOption.BASE_AT_POS || oldGroupByPos == null || !oldGroupByPos.getChr().equals(chrom) || oldGroupByPos.getStart() != chromStart) { // not already sorted by this position JCheckBoxMenuItem newGroupByPosOption = new JCheckBoxMenuItem("base at " + chrom + ":" + Globals.DECIMAL_FORMAT.format(1 + chromStart)); newGroupByPosOption.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { Range groupByPos = new Range(chrom, chromStart, chromStart + 1); IGV.getInstance().groupAlignmentTracks(GroupOption.BASE_AT_POS, null, groupByPos); refresh(); } }); groupMenu.add(newGroupByPosOption); group.add(newGroupByPosOption); } add(groupMenu); } private JMenuItem getSortMenuItem(String label, final SortOption option) { JMenuItem mi = new JMenuItem(label); mi.addActionListener(aEvt -> sortAlignmentTracks(option, null)); return mi; } /** * Sort menu */ public void addSortMenuItem() { JMenu sortMenu = new JMenu("Sort alignments by"); //LinkedHashMap is supposed to preserve order of insertion for iteration Map<String, SortOption> mappings = new LinkedHashMap<String, SortOption>(); mappings.put("start location", SortOption.START); mappings.put("read strand", SortOption.STRAND); mappings.put("first-of-pair strand", SortOption.FIRST_OF_PAIR_STRAND); mappings.put("base", SortOption.NUCLEOTIDE); mappings.put("mapping quality", SortOption.QUALITY); mappings.put("sample", SortOption.SAMPLE); mappings.put("read group", SortOption.READ_GROUP); mappings.put("read order", SortOption.READ_ORDER); if (dataManager.isPairedEnd()) { mappings.put("insert size", SortOption.INSERT_SIZE); mappings.put("chromosome of mate", SortOption.MATE_CHR); } // mappings.put("supplementary flag", SortOption.SUPPLEMENTARY); for (Map.Entry<String, SortOption> el : mappings.entrySet()) { sortMenu.add(getSortMenuItem(el.getKey(), el.getValue())); } JMenuItem tagOption = new JMenuItem("tag"); tagOption.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { String tag = MessageUtils.showInputDialog("Enter tag", renderOptions.getSortByTag()); if (tag != null && tag.trim().length() > 0) { renderOptions.setSortByTag(tag); sortAlignmentTracks(SortOption.TAG, tag); } } }); sortMenu.add(tagOption); add(sortMenu); } private void setBisulfiteContext(BisulfiteContext option) { renderOptions.bisulfiteContext = option; getPreferences().put(SAM_BISULFITE_CONTEXT, option.toString()); } private void setColorOption(ColorOption option) { renderOptions.setColorOption(option); getPreferences().put(SAM_COLOR_BY, option.toString()); } private JRadioButtonMenuItem getColorMenuItem(String label, final ColorOption option) { JRadioButtonMenuItem mi = new JRadioButtonMenuItem(label); mi.setSelected(renderOptions.getColorOption() == option); mi.addActionListener(aEvt -> { setColorOption(option); refresh(); }); return mi; } public void addColorByMenuItem() { // Change track height by attribute JMenu colorMenu = new JMenu("Color alignments by"); ButtonGroup group = new ButtonGroup(); Map<String, ColorOption> mappings = new LinkedHashMap<String, ColorOption>(); mappings.put("no color", ColorOption.NONE); if (dataManager.hasYCTags()) { mappings.put("YC tag", ColorOption.YC_TAG); } if (dataManager.isPairedEnd()) { mappings.put("insert size", ColorOption.INSERT_SIZE); mappings.put("pair orientation", ColorOption.PAIR_ORIENTATION); mappings.put("insert size and pair orientation", ColorOption.UNEXPECTED_PAIR); } mappings.put("read strand", ColorOption.READ_STRAND); if (dataManager.isPairedEnd()) { mappings.put("first-of-pair strand", ColorOption.FIRST_OF_PAIR_STRAND); } mappings.put("read group", ColorOption.READ_GROUP); mappings.put("sample", ColorOption.SAMPLE); mappings.put("library", ColorOption.LIBRARY); mappings.put("movie", ColorOption.MOVIE); mappings.put("ZMW", ColorOption.ZMW); for (Map.Entry<String, ColorOption> el : mappings.entrySet()) { JRadioButtonMenuItem mi = getColorMenuItem(el.getKey(), el.getValue()); colorMenu.add(mi); group.add(mi); } JRadioButtonMenuItem tagOption = new JRadioButtonMenuItem("tag"); tagOption.setSelected(renderOptions.getColorOption() == ColorOption.TAG); tagOption.addActionListener(aEvt -> { setColorOption(ColorOption.TAG); String tag = MessageUtils.showInputDialog("Enter tag", renderOptions.getColorByTag()); if (tag != null && tag.trim().length() > 0) { renderOptions.setColorByTag(tag); getPreferences(experimentType).put(SAM_COLOR_BY_TAG, tag); refresh(); } }); colorMenu.add(tagOption); group.add(tagOption); colorMenu.add(getBisulfiteContextMenuItem(group)); add(colorMenu); } public void addPackMenuItem() { // Change track height by attribute JMenuItem item = new JMenuItem("Re-pack alignments"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { UIUtilities.invokeOnEventThread(new Runnable() { public void run() { IGV.getInstance().packAlignmentTracks(); refresh(); } }); } }); add(item); } public void addCopyToClipboardItem(final TrackClickEvent te, Alignment alignment) { final MouseEvent me = te.getMouseEvent(); JMenuItem item = new JMenuItem("Copy read details to clipboard"); final ReferenceFrame frame = te.getFrame(); if (frame == null) { item.setEnabled(false); } else { final double location = frame.getChromosomePosition(me.getX()); // Change track height by attribute item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { copyToClipboard(te, alignment, location, me.getX()); } }); if (alignment == null) { item.setEnabled(false); } } add(item); } public void addViewAsPairsMenuItem() { final JMenuItem item = new JCheckBoxMenuItem("View as pairs"); item.setSelected(renderOptions.isViewPairs()); item.addActionListener(aEvt -> { boolean viewAsPairs = item.isSelected(); setViewAsPairs(viewAsPairs); }); item.setEnabled(dataManager.isPairedEnd()); add(item); } public void addGoToMate(final TrackClickEvent te, Alignment alignment) { // Change track height by attribute JMenuItem item = new JMenuItem("Go to mate"); MouseEvent e = te.getMouseEvent(); final ReferenceFrame frame = te.getFrame(); if (frame == null) { item.setEnabled(false); } else { item.addActionListener(aEvt -> gotoMate(te, alignment)); if (alignment == null || !alignment.isPaired() || !alignment.getMate().isMapped()) { item.setEnabled(false); } } add(item); } public void showMateRegion(final TrackClickEvent te, Alignment clickedAlignment) { // Change track height by attribute JMenuItem item = new JMenuItem("View mate region in split screen"); MouseEvent e = te.getMouseEvent(); final ReferenceFrame frame = te.getFrame(); if (frame == null) { item.setEnabled(false); } else { double location = frame.getChromosomePosition(e.getX()); if (clickedAlignment instanceof PairedAlignment) { Alignment first = ((PairedAlignment) clickedAlignment).getFirstAlignment(); Alignment second = ((PairedAlignment) clickedAlignment).getSecondAlignment(); if (first.contains(location)) { clickedAlignment = first; } else if (second.contains(location)) { clickedAlignment = second; } else { clickedAlignment = null; } } final Alignment alignment = clickedAlignment; item.addActionListener(aEvt -> splitScreenMate(te, alignment)); if (alignment == null || !alignment.isPaired() || !alignment.getMate().isMapped()) { item.setEnabled(false); } } add(item); } public void addClearSelectionsMenuItem() { // Change track height by attribute JMenuItem item = new JMenuItem("Clear selections"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { selectedReadNames.clear(); refresh(); } }); add(item); } public JMenuItem addShowAllBasesMenuItem() { // Change track height by attribute final JMenuItem item = new JCheckBoxMenuItem("Show all bases"); if (renderOptions.getColorOption() == ColorOption.BISULFITE || renderOptions.getColorOption() == ColorOption.NOMESEQ) { // item.setEnabled(false); } else { item.setSelected(renderOptions.isShowAllBases()); } item.addActionListener(aEvt -> { renderOptions.setShowAllBases(item.isSelected()); refresh(); }); add(item); return item; } public JMenuItem addQuickConsensusModeItem() { // Change track height by attribute final JMenuItem item = new JCheckBoxMenuItem("Quick consensus mode"); item.setSelected(renderOptions.isQuickConsensusMode()); item.addActionListener(aEvt -> { renderOptions.setQuickConsensusMode(item.isSelected()); refresh(); }); add(item); return item; } public JMenuItem addShowMismatchesMenuItem() { // Change track height by attribute final JMenuItem item = new JCheckBoxMenuItem("Show mismatched bases"); item.setSelected(renderOptions.isShowMismatches()); item.addActionListener(aEvt -> { renderOptions.setShowMismatches(item.isSelected()); refresh(); }); add(item); return item; } public void addInsertSizeMenuItem() { // Change track height by attribute final JMenuItem item = new JCheckBoxMenuItem("Set insert size options ..."); item.addActionListener(aEvt -> { InsertSizeSettingsDialog dlg = new InsertSizeSettingsDialog(IGV.getMainFrame(), renderOptions); dlg.setModal(true); dlg.setVisible(true); if (!dlg.isCanceled()) { renderOptions.setComputeIsizes(dlg.isComputeIsize()); renderOptions.setMinInsertSizePercentile(dlg.getMinPercentile()); renderOptions.setMaxInsertSizePercentile(dlg.getMaxPercentile()); if (renderOptions.computeIsizes) { dataManager.updatePEStats(renderOptions); } renderOptions.setMinInsertSize(dlg.getMinThreshold()); renderOptions.setMaxInsertSize(dlg.getMaxThreshold()); refresh(); } }); item.setEnabled(dataManager.isPairedEnd()); add(item); } public void addShadeBaseByMenuItem() { final JMenuItem item = new JCheckBoxMenuItem("Shade base by quality"); item.setSelected(renderOptions.getShadeBasesOption() == ShadeBasesOption.QUALITY); item.addActionListener(aEvt -> UIUtilities.invokeOnEventThread(() -> { if (item.isSelected()) { renderOptions.setShadeBasesOption(ShadeBasesOption.QUALITY); } else { renderOptions.setShadeBasesOption(ShadeBasesOption.NONE); } refresh(); })); add(item); } public void addShowItems() { if (AlignmentTrack.this.coverageTrack != null) { final JMenuItem item = new JCheckBoxMenuItem("Show Coverage Track"); item.setSelected(AlignmentTrack.this.coverageTrack.isVisible()); item.setEnabled(!AlignmentTrack.this.coverageTrack.isRemoved()); item.addActionListener(aEvt -> UIUtilities.invokeOnEventThread(() -> { if (getCoverageTrack() != null) { getCoverageTrack().setVisible(item.isSelected()); IGV.getInstance().getMainPanel().revalidate(); } })); add(item); } if (AlignmentTrack.this.spliceJunctionTrack != null) { final JMenuItem item = new JCheckBoxMenuItem("Show Splice Junction Track"); item.setSelected(AlignmentTrack.this.spliceJunctionTrack.isVisible()); item.setEnabled(!AlignmentTrack.this.spliceJunctionTrack.isRemoved()); item.addActionListener(aEvt -> UIUtilities.invokeOnEventThread(() -> { if (AlignmentTrack.this.spliceJunctionTrack != null) { AlignmentTrack.this.spliceJunctionTrack.setVisible(item.isSelected()); } })); add(item); } final JMenuItem alignmentItem = new JMenuItem("Hide Alignment Track"); alignmentItem.setEnabled(!AlignmentTrack.this.isRemoved()); alignmentItem.addActionListener(e -> AlignmentTrack.this.setVisible(false)); add(alignmentItem); } public void addCopySequenceItem(final TrackClickEvent te) { // Change track height by attribute final JMenuItem item = new JMenuItem("Copy read sequence"); add(item); final Alignment alignment = getSpecficAlignment(te); if (alignment == null) { item.setEnabled(false); return; } final String seq = alignment.getReadSequence(); if (seq == null) { item.setEnabled(false); return; } item.addActionListener(aEvt -> StringUtils.copyTextToClipboard(seq)); } public void addBlatItem(final TrackClickEvent te) { // Change track height by attribute final JMenuItem item = new JMenuItem("Blat read sequence"); add(item); final Alignment alignment = getSpecficAlignment(te); if (alignment == null) { item.setEnabled(false); return; } final String seq = alignment.getReadSequence(); if (seq == null) { item.setEnabled(false); return; } item.addActionListener(aEvt -> { String blatSeq = alignment.getReadStrand() == Strand.NEGATIVE ? SequenceTrack.getReverseComplement(seq) : seq; BlatClient.doBlatQuery(blatSeq); }); } public void addExtViewItem(final TrackClickEvent te) { // Change track height by attribute final JMenuItem item = new JMenuItem("ExtView"); add(item); final Alignment alignment = getAlignment(te); if (alignment == null) { item.setEnabled(false); return; } final String seq = alignment.getReadSequence(); if (seq == null) { item.setEnabled(false); return; } item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { ExtendViewClient.postExtendView(alignment); } }); } public void addTenXItems() { addSeparator(); final JMenuItem bxItem = new JCheckBoxMenuItem("View linked reads (BX)"); final JMenuItem miItem = new JCheckBoxMenuItem("View linked reads (MI)"); if (isLinkedReads()) { bxItem.setSelected("BX".equals(renderOptions.getLinkByTag())); miItem.setSelected("MI".equals(renderOptions.getLinkByTag())); } else { bxItem.setSelected(false); miItem.setSelected(false); } bxItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { boolean linkedReads = bxItem.isSelected(); setLinkedReads(linkedReads, "BX"); } }); add(bxItem); miItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { boolean linkedReads = miItem.isSelected(); setLinkedReads(linkedReads, "MI"); } }); add(miItem); } public void addSupplItems() { addSeparator(); final JMenuItem bxItem = new JCheckBoxMenuItem("Link supplementary alignments"); if (isLinkedReads()) { bxItem.setSelected("READNAME".equals(renderOptions.getLinkByTag())); } else { bxItem.setSelected(false); } bxItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt) { boolean linkedReads = bxItem.isSelected(); setLinkedReads(linkedReads, "READNAME"); } }); add(bxItem); } private void addInsertionItems(AlignmentBlock insertion) { final JMenuItem item = new JMenuItem("Copy insert sequence"); add(item); item.addActionListener(aEvt -> StringUtils.copyTextToClipboard(new String(insertion.getBases()))); if (insertion.getBases() != null && insertion.getBases().length > 10) { final JMenuItem blatItem = new JMenuItem("Blat insert sequence"); add(blatItem); blatItem.addActionListener(aEvt -> { String blatSeq = new String(insertion.getBases()); BlatClient.doBlatQuery(blatSeq); }); } } } private AlignmentBlock getInsertion(Alignment alignment, int pixelX) { if (alignment != null && alignment.getInsertions() != null) { for (AlignmentBlock block : alignment.getInsertions()) { if (block.containsPixel(pixelX)) { return block; } } } return null; } static class InsertionMenu extends IGVPopupMenu { AlignmentBlock insertion; InsertionMenu(AlignmentBlock insertion) { this.insertion = insertion; addCopySequenceItem(); if (insertion.getBases() != null && insertion.getBases().length > 10) { addBlatItem(); } } public void addCopySequenceItem() { // Change track height by attribute final JMenuItem item = new JMenuItem("Copy insert sequence"); add(item); item.addActionListener(aEvt -> StringUtils.copyTextToClipboard(new String(insertion.getBases()))); } public void addBlatItem() { // Change track height by attribute final JMenuItem item = new JMenuItem("Blat insert sequence"); add(item); item.addActionListener(aEvt -> { String blatSeq = new String(insertion.getBases()); BlatClient.doBlatQuery(blatSeq); }); } @Override public boolean includeStandardItems() { return false; } } public static class RenderOptions implements Cloneable, Persistable { public static final String NAME = "RenderOptions"; private AlignmentTrack.ShadeBasesOption shadeBasesOption; private Boolean shadeCenters; private Boolean flagUnmappedPairs; private Boolean showAllBases; private Integer minInsertSize; private Integer maxInsertSize; private AlignmentTrack.ColorOption colorOption; private AlignmentTrack.GroupOption groupByOption; private Boolean viewPairs; private String colorByTag; private String groupByTag; private String sortByTag; private String linkByTag; private Boolean linkedReads; private Boolean quickConsensusMode; private Boolean showMismatches; private Boolean computeIsizes; private Double minInsertSizePercentile; private Double maxInsertSizePercentile; private Boolean pairedArcView; private Boolean flagZeroQualityAlignments; private Range groupByPos; private Boolean drawInsertionIntervals; AlignmentTrack.BisulfiteContext bisulfiteContext = BisulfiteContext.CG; Map<String, PEStats> peStats; DefaultValues defaultValues; public RenderOptions() { this(ExperimentType.OTHER); } RenderOptions(ExperimentType experimentType) { IGVPreferences prefs = getPreferences(experimentType); //updateColorScale(); peStats = new HashMap<String, PEStats>(); defaultValues = new DefaultValues(prefs); } private <T extends Enum<T>> T getFromMap(Map<String, String> attributes, String key, Class<T> clazz, T defaultValue) { String value = attributes.get(key); if (value == null) { return defaultValue; } return CollUtils.<T>valueOf(clazz, value, defaultValue); } private String getFromMap(Map<String, String> attributes, String key, String defaultValue) { String value = attributes.get(key); if (value == null) { return defaultValue; } return value; } public void setShowAllBases(boolean showAllBases) { this.showAllBases = showAllBases; } public void setShowMismatches(boolean showMismatches) { this.showMismatches = showMismatches; } public void setMinInsertSize(int minInsertSize) { this.minInsertSize = minInsertSize; //updateColorScale(); } public void setViewPairs(boolean viewPairs) { this.viewPairs = viewPairs; } public void setComputeIsizes(boolean computeIsizes) { this.computeIsizes = computeIsizes; } public void setMaxInsertSizePercentile(double maxInsertSizePercentile) { this.maxInsertSizePercentile = maxInsertSizePercentile; } public void setMaxInsertSize(int maxInsertSize) { this.maxInsertSize = maxInsertSize; } public void setMinInsertSizePercentile(double minInsertSizePercentile) { this.minInsertSizePercentile = minInsertSizePercentile; } public void setColorByTag(String colorByTag) { this.colorByTag = colorByTag; } public void setColorOption(AlignmentTrack.ColorOption colorOption) { this.colorOption = colorOption; } public void setSortByTag(String sortByTag) { this.sortByTag = sortByTag; } public void setGroupByTag(String groupByTag) { this.groupByTag = groupByTag; } public void setGroupByPos(Range groupByPos) { this.groupByPos = groupByPos; } public void setLinkByTag(String linkByTag) { this.linkByTag = linkByTag; } public void setQuickConsensusMode(boolean quickConsensusMode) { this.quickConsensusMode = quickConsensusMode; } public void setGroupByOption(AlignmentTrack.GroupOption groupByOption) { this.groupByOption = (groupByOption == null) ? AlignmentTrack.GroupOption.NONE : groupByOption; } public void setShadeBasesOption(AlignmentTrack.ShadeBasesOption shadeBasesOption) { this.shadeBasesOption = shadeBasesOption; } public void setLinkedReads(boolean linkedReads) { this.linkedReads = linkedReads; } public void setDrawInsertionIntervals(boolean drawInsertionIntervals) { this.drawInsertionIntervals = drawInsertionIntervals; } // getters public int getMinInsertSize() { return minInsertSize == null ? defaultValues.minInsertSize : minInsertSize; } public int getMaxInsertSize() { return maxInsertSize == null ? defaultValues.maxInsertSize : maxInsertSize; } public boolean isFlagUnmappedPairs() { return flagUnmappedPairs == null ? defaultValues.flagUnmappedPairs : flagUnmappedPairs; } public AlignmentTrack.ShadeBasesOption getShadeBasesOption() { return shadeBasesOption == null ? defaultValues.shadeBasesOption : shadeBasesOption; } public boolean isShowMismatches() { return showMismatches == null ? defaultValues.showMismatches : showMismatches; } public boolean isShowAllBases() { return showAllBases == null ? defaultValues.showAllBases : showAllBases; } public boolean isShadeCenters() { return shadeCenters == null ? defaultValues.shadeCenters : shadeCenters; } public boolean isDrawInsertionIntervals() { return drawInsertionIntervals == null ? defaultValues.drawInsertionIntervals : drawInsertionIntervals; } public boolean isFlagZeroQualityAlignments() { return flagZeroQualityAlignments == null ? defaultValues.flagZeroQualityAlignments : flagZeroQualityAlignments; } public boolean isViewPairs() { return viewPairs == null ? defaultValues.viewPairs : viewPairs; } public boolean isComputeIsizes() { return computeIsizes == null ? defaultValues.computeIsizes : computeIsizes; } public double getMinInsertSizePercentile() { return minInsertSizePercentile == null ? defaultValues.minInsertSizePercentile : minInsertSizePercentile; } public double getMaxInsertSizePercentile() { return maxInsertSizePercentile == null ? defaultValues.maxInsertSizePercentile : maxInsertSizePercentile; } public AlignmentTrack.ColorOption getColorOption() { return colorOption == null ? defaultValues.colorOption : colorOption; } public String getColorByTag() { return colorByTag == null ? defaultValues.colorByTag : colorByTag; } public String getSortByTag() { return sortByTag == null ? defaultValues.sortByTag : sortByTag; } public String getGroupByTag() { return groupByTag == null ? defaultValues.groupByTag : groupByTag; } public Range getGroupByPos() { return groupByPos == null ? defaultValues.groupByPos : groupByPos; } public String getLinkByTag() { return linkByTag == null ? defaultValues.linkByTag : linkByTag; } public AlignmentTrack.GroupOption getGroupByOption() { AlignmentTrack.GroupOption gbo = groupByOption; // Interpret null as the default option. gbo = (gbo == null) ? defaultValues.groupByOption : gbo; // Add a second check for null in case defaultValues.groupByOption == null gbo = (gbo == null) ? AlignmentTrack.GroupOption.NONE : gbo; return gbo; } public boolean isLinkedReads() { return linkedReads == null ? defaultValues.linkedReads : linkedReads; } public boolean isQuickConsensusMode() { return quickConsensusMode == null ? defaultValues.quickConsensusMode : quickConsensusMode; } public void refreshDefaults(ExperimentType experimentType) { IGVPreferences prefs = getPreferences(experimentType); defaultValues = new DefaultValues(prefs); } @Override public void marshalXML(Document document, Element element) { if (shadeBasesOption != null) { element.setAttribute("shadeBasesOption", shadeBasesOption.toString()); } if (shadeCenters != null) { element.setAttribute("shadeCenters", shadeCenters.toString()); } if (flagUnmappedPairs != null) { element.setAttribute("flagUnmappedPairs", flagUnmappedPairs.toString()); } if (showAllBases != null) { element.setAttribute("showAllBases", showAllBases.toString()); } if (minInsertSize != null) { element.setAttribute("minInsertSize", minInsertSize.toString()); } if (maxInsertSize != null) { element.setAttribute("maxInsertSize", maxInsertSize.toString()); } if (colorOption != null) { element.setAttribute("colorOption", colorOption.toString()); } if (groupByOption != null) { element.setAttribute("groupByOption", groupByOption.toString()); } if (viewPairs != null) { element.setAttribute("viewPairs", viewPairs.toString()); } if (colorByTag != null) { element.setAttribute("colorByTag", colorByTag); } if (groupByTag != null) { element.setAttribute("groupByTag", groupByTag); } if (sortByTag != null) { element.setAttribute("sortByTag", sortByTag); } if (linkByTag != null) { element.setAttribute("linkByTag", linkByTag); } if (linkedReads != null) { element.setAttribute("linkedReads", linkedReads.toString()); } if (quickConsensusMode != null) { element.setAttribute("quickConsensusMode", quickConsensusMode.toString()); } if (showMismatches != null) { element.setAttribute("showMismatches", showMismatches.toString()); } if (computeIsizes != null) { element.setAttribute("computeIsizes", computeIsizes.toString()); } if (minInsertSizePercentile != null) { element.setAttribute("minInsertSizePercentile", minInsertSizePercentile.toString()); } if (maxInsertSizePercentile != null) { element.setAttribute("maxInsertSizePercentile", maxInsertSizePercentile.toString()); } if (pairedArcView != null) { element.setAttribute("pairedArcView", pairedArcView.toString()); } if (flagZeroQualityAlignments != null) { element.setAttribute("flagZeroQualityAlignments", flagZeroQualityAlignments.toString()); } if (groupByPos != null) { element.setAttribute("groupByPos", groupByPos.toString()); } } @Override public void unmarshalXML(Element element, Integer version) { if (element.hasAttribute("shadeBasesOption")) { shadeBasesOption = ShadeBasesOption.valueOf(element.getAttribute("shadeBasesOption")); } if (element.hasAttribute("shadeCenters")) { shadeCenters = Boolean.parseBoolean(element.getAttribute("shadeCenters")); } if (element.hasAttribute("showAllBases")) { showAllBases = Boolean.parseBoolean(element.getAttribute("showAllBases")); } if (element.hasAttribute("flagUnmappedPairs")) { flagUnmappedPairs = Boolean.parseBoolean(element.getAttribute("flagUnmappedPairs")); } if (element.hasAttribute("minInsertSize")) { minInsertSize = Integer.parseInt(element.getAttribute("minInsertSize")); } if (element.hasAttribute("maxInsertSize")) { maxInsertSize = Integer.parseInt(element.getAttribute("maxInsertSize")); } if (element.hasAttribute("colorOption")) { colorOption = ColorOption.valueOf(element.getAttribute("colorOption")); } if (element.hasAttribute("groupByOption")) { groupByOption = GroupOption.valueOf(element.getAttribute("groupByOption")); } if (element.hasAttribute("viewPairs")) { viewPairs = Boolean.parseBoolean(element.getAttribute("viewPairs")); } if (element.hasAttribute("colorByTag")) { colorByTag = element.getAttribute("colorByTag"); } if (element.hasAttribute("groupByTag")) { groupByTag = element.getAttribute("groupByTag"); } if (element.hasAttribute("sortByTag")) { sortByTag = element.getAttribute("sortByTag"); } if (element.hasAttribute("linkByTag")) { linkByTag = element.getAttribute("linkByTag"); } if (element.hasAttribute("linkedReads")) { linkedReads = Boolean.parseBoolean(element.getAttribute("linkedReads")); } if (element.hasAttribute("quickConsensusMode")) { quickConsensusMode = Boolean.parseBoolean(element.getAttribute("quickConsensusMode")); } if (element.hasAttribute("showMismatches")) { showMismatches = Boolean.parseBoolean(element.getAttribute("showMismatches")); } if (element.hasAttribute("computeIsizes")) { computeIsizes = Boolean.parseBoolean(element.getAttribute("computeIsizes")); } if (element.hasAttribute("minInsertSizePercentile")) { minInsertSizePercentile = Double.parseDouble(element.getAttribute("minInsertSizePercentile")); } if (element.hasAttribute("maxInsertSizePercentile")) { maxInsertSizePercentile = Double.parseDouble(element.getAttribute("maxInsertSizePercentile")); } if (element.hasAttribute("pairedArcView")) { pairedArcView = Boolean.parseBoolean(element.getAttribute("pairedArcView")); } if (element.hasAttribute("flagZeroQualityAlignments")) { flagZeroQualityAlignments = Boolean.parseBoolean(element.getAttribute("flagZeroQualityAlignments")); } if (element.hasAttribute("groupByPos")) { groupByPos = Range.fromString(element.getAttribute("groupByPos")); } } static class DefaultValues { public AlignmentTrack.ShadeBasesOption shadeBasesOption; public boolean shadeCenters; public boolean flagUnmappedPairs; public boolean showAllBases; public int minInsertSize; public int maxInsertSize; public AlignmentTrack.ColorOption colorOption; public AlignmentTrack.GroupOption groupByOption; //ContinuousColorScale insertSizeColorScale; public boolean viewPairs; public String colorByTag; public String groupByTag; public String sortByTag; public String linkByTag; public boolean linkedReads; public boolean quickConsensusMode; public boolean showMismatches; public boolean computeIsizes; public double minInsertSizePercentile; public double maxInsertSizePercentile; public boolean pairedArcView; public boolean flagZeroQualityAlignments; public Range groupByPos; public boolean drawInsertionIntervals; DefaultValues(IGVPreferences prefs) { String shadeOptionString = prefs.get(SAM_SHADE_BASES); if (shadeOptionString.equals("false")) { shadeBasesOption = AlignmentTrack.ShadeBasesOption.NONE; } else if (shadeOptionString.equals("true")) { shadeBasesOption = AlignmentTrack.ShadeBasesOption.QUALITY; } else { shadeBasesOption = AlignmentTrack.ShadeBasesOption.valueOf(shadeOptionString); } shadeCenters = prefs.getAsBoolean(SAM_SHADE_CENTER); flagUnmappedPairs = prefs.getAsBoolean(SAM_FLAG_UNMAPPED_PAIR); computeIsizes = prefs.getAsBoolean(SAM_COMPUTE_ISIZES); minInsertSize = prefs.getAsInt(SAM_MIN_INSERT_SIZE_THRESHOLD); maxInsertSize = prefs.getAsInt(SAM_MAX_INSERT_SIZE_THRESHOLD); minInsertSizePercentile = prefs.getAsFloat(SAM_MIN_INSERT_SIZE_PERCENTILE); maxInsertSizePercentile = prefs.getAsFloat(SAM_MAX_INSERT_SIZE_PERCENTILE); showAllBases = prefs.getAsBoolean(SAM_SHOW_ALL_BASES); quickConsensusMode = prefs.getAsBoolean(SAM_QUICK_CONSENSUS_MODE); colorOption = CollUtils.valueOf(AlignmentTrack.ColorOption.class, prefs.get(SAM_COLOR_BY), AlignmentTrack.ColorOption.NONE); groupByOption = CollUtils.valueOf(AlignmentTrack.GroupOption.class, prefs.get(SAM_GROUP_OPTION), AlignmentTrack.GroupOption.NONE); flagZeroQualityAlignments = prefs.getAsBoolean(SAM_FLAG_ZERO_QUALITY); showMismatches = prefs.getAsBoolean(SAM_SHOW_MISMATCHES); viewPairs = false; pairedArcView = false; colorByTag = prefs.get(SAM_COLOR_BY_TAG); sortByTag = prefs.get(SAM_SORT_BY_TAG); groupByTag = prefs.get(SAM_GROUP_BY_TAG); linkedReads = prefs.getAsBoolean(SAM_LINK_READS); linkByTag = prefs.get(SAM_LINK_TAG); String pos = prefs.get(SAM_GROUP_BY_POS); if (pos != null) { String[] posParts = pos.split(" "); if (posParts.length != 2) { this.groupByPos = null; } else { int posChromStart = Integer.valueOf(posParts[1]); this.groupByPos = new Range(posParts[0], posChromStart, posChromStart + 1); } } drawInsertionIntervals = prefs.getAsBoolean(SAM_SHOW_INSERTION_MARKERS); } } } @Override public void unmarshalXML(Element element, Integer version) { super.unmarshalXML(element, version); if (element.hasAttribute("experimentType")) { experimentType = ExperimentType.valueOf(element.getAttribute("experimentType")); } NodeList tmp = element.getElementsByTagName("RenderOptions"); if (tmp.getLength() > 0) { Element renderElement = (Element) tmp.item(0); renderOptions = new RenderOptions(); renderOptions.unmarshalXML(renderElement, version); } } @Override public void marshalXML(Document document, Element element) { super.marshalXML(document, element); if (experimentType != null) { element.setAttribute("experimentType", experimentType.toString()); } Element sourceElement = document.createElement("RenderOptions"); renderOptions.marshalXML(document, sourceElement); element.appendChild(sourceElement); } }
package nak.nakloidGUI.actions.files; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import nak.nakloidGUI.NakloidGUI; import nak.nakloidGUI.actions.AbstractAction; import nak.nakloidGUI.coredata.CoreData; import nak.nakloidGUI.coredata.CoreData.CoreDataSubscriber; import nak.nakloidGUI.coredata.NakloidIni; import nak.nakloidGUI.coredata.NakloidIni.ScoreMode; import nak.nakloidGUI.gui.MainWindow; public class ImportScoreAction extends AbstractAction implements CoreDataSubscriber { final private static String[] scoreExt = {"*.nak;*.ust;*.smf;*.mid","*.nak","*.ust","*.smf;*.mid"}; final private static String[] lyricsExt = {"*.txt"}; final private static String [] scoreFilterNames = {" (*.nak, *.ust, *.smf, *.mid)", "Nakloid Score File (*.nak)", "UTAU Sequence Text (*.ust)", "Standard MIDI File (*.smf, *.mid)"}; final private static String [] lyricsFilterNames = {" (*.txt)"}; public ImportScoreAction(MainWindow mainWindow, CoreData coreData) { super(mainWindow, coreData); setText(""); } @Override public void run() { FileDialog openScoreDialog = new FileDialog(mainWindow.getShell(), SWT.OPEN); openScoreDialog.setFilterExtensions(scoreExt); openScoreDialog.setFilterNames(scoreFilterNames); String strScorePath = openScoreDialog.open(); if (strScorePath==null || strScorePath.isEmpty()) { return; } Path pathImportScore = Paths.get(strScorePath); if (!strScorePath.endsWith(".nak")) { try { CoreData tmpCoreData = new CoreData.Builder() .loadOtoIni(coreData.getVocalPath()) .build(); tmpCoreData.addSubscribers(this); tmpCoreData.nakloidIni.input.path_input_score = pathImportScore; if (strScorePath.endsWith(".ust")) { tmpCoreData.nakloidIni.input.score_mode = ScoreMode.score_mode_ust; } else { tmpCoreData.nakloidIni.input.score_mode = ScoreMode.score_mode_smf; FileDialog openSmfDialog = new FileDialog(mainWindow.getShell(), SWT.OPEN); openSmfDialog.setFilterExtensions(lyricsExt); openSmfDialog.setFilterNames(lyricsFilterNames); String strLyricsPath = openSmfDialog.open(); if (strLyricsPath==null || strLyricsPath.isEmpty()) { return; } tmpCoreData.nakloidIni.input.path_lyrics = Paths.get(strLyricsPath); } tmpCoreData.nakloidIni.input.path_input_pitches = null; tmpCoreData.nakloidIni.input.pitches_mode = NakloidIni.PitchesMode.pitches_mode_none; tmpCoreData.nakloidIni.output.path_output_score = Paths.get(NakloidGUI.preferenceStore.getString("ini.input.path_input_score")); tmpCoreData.nakloidIni.output.path_output_pitches = Paths.get(NakloidGUI.preferenceStore.getString("ini.input.path_input_pitches")); Files.deleteIfExists(coreData.nakloidIni.input.path_input_pitches); tmpCoreData.synthesize(); } catch (IOException e1) { MessageDialog.openError(mainWindow.getShell(), "NakloidGUI", "\n"+e1.getMessage()); } catch (InterruptedException e2) { MessageDialog.openError(mainWindow.getShell(), "NakloidGUI", "Nakloid\n"+e2.getMessage()); } } else { try { Files.copy(pathImportScore, coreData.getScorePath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { MessageDialog.openError(mainWindow.getShell(), "NakloidGUI", "\n"+e.getMessage()); } } } @Override public void updateScore() {} @Override public void updatePitches() {} @Override public void updateVocal() {} @Override public void updateSongWaveform() { try { coreData.reloadScoreAndPitches(); } catch (IOException e) { MessageDialog.openError(mainWindow.getShell(), "NakloidGUI", "\n"+e.getMessage()); } coreData.reloadSongWaveform(); } }
package org.digidoc4j.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.europa.esig.dss.MimeType; public final class MimeTypeUtil { private static final Logger log = LoggerFactory.getLogger(MimeTypeUtil.class); private MimeTypeUtil() { } /** * When DD4J discovers mimeType which is in wrong format, then we try to fix it. * @param mimeType Given mimetype string * @return */ public static MimeType mimeTypeOf(String mimeType) { switch (mimeType) { case "txt.html": log.warn("Incorrect Mime-Type <{}> detected, fixing ...", mimeType); mimeType = "text/html"; break; case "file": log.warn("Incorrect Mime-Type <{}> detected, fixing ...", mimeType); mimeType = "application/octet-stream"; break; } if (mimeType.indexOf('\\') > 0) { log.warn("Incorrect Mime-Type <{}> detected, fixing ...", mimeType); mimeType = mimeType.replace("\\", "/"); } return MimeType.fromMimeTypeString(mimeType); } }
package org.geometrycommands; import com.vividsolutions.jts.awt.PointShapeFactory; import com.vividsolutions.jts.awt.PointTransformation; import com.vividsolutions.jts.awt.ShapeWriter; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Lineal; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import javax.imageio.ImageIO; import org.geometrycommands.DrawCommand.DrawOptions; import org.kohsuke.args4j.Option; /** * A Command to draw the input Geometry to an image File * @author Jared Erickson */ public class DrawCommand extends GeometryCommand<DrawOptions> { /** * Get the command name * @return The command name */ @Override public String getName() { return "draw"; } /** * Get a new DrawOptions * @return A new DrawOptions */ @Override public DrawOptions getOptions() { return new DrawOptions(); } /** * Get a java.awt.Color from a String * @param value A String value * @return The java.awt.Color */ private Color getColor(String value) { String[] parts = value.split(","); int r = Integer.parseInt(parts[0]); int g = Integer.parseInt(parts[1]); int b = Integer.parseInt(parts[2]); int a = 255; if (parts.length > 3) { a = Integer.parseInt(parts[3]); } return new Color(r, g, b, a); } /** * Draw the input Geometry to an image File * @param geometry The input Geometry * @param options The DrawOptions * @param reader The java.io.Reader * @param writer The java.io.Writer */ @Override protected void processGeometry(Geometry geometry, DrawOptions options, Reader reader, Writer writer) throws Exception { final int imageWidth = options.getWidth(); final int imageHeight = options.getHeight(); BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = image.createGraphics(); g2d.setColor(getColor(options.getBackgroundColor())); g2d.fillRect(0, 0, imageWidth, imageHeight); // Draw background image if (options.getBackgroundImage() != null && options.getBackgroundImage().trim().length() > 0) { String backgroundImagePath = options.getBackgroundImage().trim(); BufferedImage backgroundImage; if (backgroundImagePath.startsWith("http")) { URL url = new URL(backgroundImagePath); backgroundImage = ImageIO.read(url); } else { File file = new File(backgroundImagePath); backgroundImage = ImageIO.read(file); } g2d.drawImage(backgroundImage, 0, 0, null); } final Envelope env = getEnvelope(geometry, options); Color strokeColor = getColor(options.getStrokeColor()); Color fillColor = getColor(options.getFillColor()); String shape = options.getShape(); double markerSize = options.getMarkerSize(); PointShapeFactory pointShapeFactory; if (shape.equalsIgnoreCase("circle")) { pointShapeFactory = new PointShapeFactory.Circle(markerSize); } else if (shape.equalsIgnoreCase("cross")) { pointShapeFactory = new PointShapeFactory.Cross(markerSize); } else if (shape.equalsIgnoreCase("star")) { pointShapeFactory = new PointShapeFactory.Star(markerSize); } else if (shape.equalsIgnoreCase("Triangle")) { pointShapeFactory = new PointShapeFactory.Triangle(markerSize); } else if (shape.equalsIgnoreCase("X")) { pointShapeFactory = new PointShapeFactory.X(markerSize); } else { pointShapeFactory = new PointShapeFactory.Square(markerSize); } float opacity = 0.75f; float strokeWidth = 1.0f; ShapeWriter shapeWriter = new ShapeWriter(new PointTransformation() { @Override public void transform(Coordinate coord, Point2D point) { double imageX = (1 - (env.getMaxX() - coord.x) / env.getWidth()) * imageWidth; double imageY = ((env.getMaxY() - coord.y) / env.getHeight()) * imageHeight; point.setLocation(imageX, imageY); } }, pointShapeFactory); Composite strokeComposite = g2d.getComposite(); Composite fillComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity); Shape shp = shapeWriter.toShape(geometry); g2d.setComposite(fillComposite); // Fill if (!(geometry instanceof Lineal)) { g2d.setComposite(fillComposite); g2d.setColor(fillColor); g2d.fill(shp); } // Stroke g2d.setComposite(strokeComposite); g2d.setStroke(new BasicStroke(strokeWidth)); g2d.setColor(strokeColor); g2d.draw(shp); if (options.isDrawingCoordinates()) { g2d.setStroke(new BasicStroke(strokeWidth)); Coordinate[] coords = geometry.getCoordinates(); for (Coordinate c : coords) { Shape coordinateShp = shapeWriter.toShape(geometry.getFactory().createPoint(c)); // Fill g2d.setComposite(fillComposite); g2d.setColor(fillColor); g2d.fill(coordinateShp); // Stroke g2d.setComposite(strokeComposite); g2d.setColor(strokeColor); g2d.draw(coordinateShp); } } g2d.dispose(); String fileName = options.getFile().getName(); String imageFormat = fileName.substring(fileName.lastIndexOf(".") + 1); FileOutputStream out = new FileOutputStream(options.getFile()); ImageIO.write(image, imageFormat, out); out.close(); } /** * Get an Envelope either from the Geometry or from the DrawOptions bounds property * @param geometry The input Geometry * @param options The DrawOptions * @return An Envelope */ private Envelope getEnvelope(Geometry geometry, DrawOptions options) { Envelope env; String bounds = options.getBounds(); if (bounds != null && bounds.split(",").length == 4) { String[] parts = bounds.split(","); double minX = Double.parseDouble(parts[0].trim()); double minY = Double.parseDouble(parts[1].trim()); double maxX = Double.parseDouble(parts[2].trim()); double maxY = Double.parseDouble(parts[3].trim()); env = new Envelope(minX, maxX, minY, maxY); } else { env = geometry.getEnvelopeInternal(); env.expandBy(env.getWidth() * 0.1); } return env; } /** * The DrawOptions */ public static class DrawOptions extends GeometryOptions { /** * The image width */ @Option(name = "-w", usage = "The image width", required = false) private int width = 400; /** * The image height */ @Option(name = "-h", usage = "The image height", required = false) private int height = 400; /** * The output File */ @Option(name = "-file", usage = "The output File", required = false) private File file = new File("image.png"); /** * The background Color */ @Option(name = "-background", usage = "The background color", required = false) private String backgroundColor = "255,255,255"; /** * The background image url or file */ @Option(name = "-backgroundImage", usage = "The background image url or file", required = false) private String backgroundImage; /** * The stroke Color */ @Option(name = "-stroke", usage = "The stroke Color", required = false) private String strokeColor = "99,99,99"; /** * The fill Color */ @Option(name = "-fill", usage = "The fill Color", required = false) private String fillColor = "206,206,206,100"; /** * The marker shape */ @Option(name = "-shape", usage = "The marker shape (circle, square, ect..)", required = false) private String shape = "circle"; /** * The marker size */ @Option(name = "-markerSize", usage = "The marker size", required = false) private double markerSize = 8; /** * The flag for drawing coordinates or not */ @Option(name = "-drawCoords", usage = "The flag for drawing coordinates or not", required = false) private boolean drawingCoordinates; /** * The geographical bounds (minx, miny, maxx, maxy) */ @Option(name = "-bounds", usage = "The geographical bounds (minx, miny, maxx, maxy)", required = false) private String bounds; /** * Get the geographical bounds (minx, miny, maxx, maxy) * @return The geographical bounds (minx, miny, maxx, maxy) */ public String getBounds() { return bounds; } /** * Set the geographical bounds (minx, miny, maxx, maxy) * @param bounds The geographical bounds (minx, miny, maxx, maxy) */ public void setBounds(String bounds) { this.bounds = bounds; } public String getBackgroundImage() { return backgroundImage; } public void setBackgroundImage(String backgroundImage) { this.backgroundImage = backgroundImage; } /** * Get the flag for drawing coordinates or not * @return The flag for drawing coordinates or not */ public boolean isDrawingCoordinates() { return drawingCoordinates; } /** * Set the flag for drawing coordinates or not * @param drawingCoordinates The flag for drawing coordinates or not */ public void setDrawingCoordinates(boolean drawingCoordinates) { this.drawingCoordinates = drawingCoordinates; } /** * Get the output File * @return The output File */ public File getFile() { return file; } /** * Set the output File * @param file The output File */ public void setFile(File file) { this.file = file; } /** * Get the marker size * @return The marker size */ public double getMarkerSize() { return markerSize; } /** * Set the marker size * @param markerSize The marker size */ public void setMarkerSize(double markerSize) { this.markerSize = markerSize; } /** * Get the image height * @return The image height */ public int getHeight() { return height; } /** * Set the image height * @param height The image height */ public void setHeight(int height) { this.height = height; } /** * Get the image width * @return The image width */ public int getWidth() { return width; } /** * Set the image width * @param width The image width */ public void setWidth(int width) { this.width = width; } /** * Get the background Color * @return The background Color */ public String getBackgroundColor() { return backgroundColor; } /** * Set the background Color * @param backgroundColor The background Color */ public void setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; } /** * Get the fill Color * @return The fill Color */ public String getFillColor() { return fillColor; } /** * Set the fill Color * @param fillColor The fill Color */ public void setFillColor(String fillColor) { this.fillColor = fillColor; } /** * Get the stroke Color * @return The stroke Color */ public String getStrokeColor() { return strokeColor; } /** * Set the stroke Color * @param strokeColor The stroke Color */ public void setStrokeColor(String strokeColor) { this.strokeColor = strokeColor; } /** * Get the marker shape * @return The marker shape */ public String getShape() { return shape; } /** * Set the marker shape * @param shape The marker shape */ public void setShape(String shape) { this.shape = shape; } } }
package org.hcjf.io.net.http; import com.google.gson.*; import org.hcjf.encoding.MimeType; import org.hcjf.errors.HCJFRuntimeException; import org.hcjf.io.net.http.datasources.DataSourceService; import org.hcjf.io.net.http.datasources.DataSourceServiceConsumer; import org.hcjf.layers.Layers; import org.hcjf.layers.crud.CreateLayerInterface; import org.hcjf.layers.crud.DeleteLayerInterface; import org.hcjf.layers.crud.ReadLayerInterface; import org.hcjf.layers.crud.UpdateLayerInterface; import org.hcjf.layers.query.*; import org.hcjf.properties.SystemProperties; import org.hcjf.service.Service; import org.hcjf.utils.JsonUtils; import org.hcjf.utils.Strings; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.*; import java.util.regex.Pattern; /** * This class provides an abstraction to implements a simple rest end point that * join any rest rule with some layer implementation. * @author javaito */ public class RestContext extends Context { private static class Fields { private static final String VALUE_FIELD = "value"; private static final String PARAMS_FIELD = "params"; private static final String ID_URL_FIELD = "id"; private static final String POINTER_PREFIX = "$"; private static final String REQUEST_CONFIG = "__request_config"; private static final String DATE_FORMAT_CONFIG = "dateFormat"; private static class Throwable { private static final String MESSAGE = "message"; private static final String EXCEPTION = "exception"; private static final String BODY = "body"; private static final String TAGS = "tags"; } } private static final String REGEX_TEMPLATE = "\\/%s(\\/(?<resource>[A-Za-z0-9\\-\\_]{0,})){0,}"; private static final String DEFAULT_QUERY_PARAMETER = "q"; private final List<Pattern> idRegexList; public RestContext(String baseContext) { this(baseContext, List.of(SystemProperties.getPattern(SystemProperties.HCJF_UUID_REGEX))); } public RestContext(String baseContext, List<Pattern> idRegexList) { super(String.format(REGEX_TEMPLATE, Strings.trim(baseContext, Strings.SLASH))); this.idRegexList = idRegexList; } /** * This method receive the http request and delegate each request for the different method depends of the * http method and the request body. * @param request All the request information. * @return Returns the response object. */ @Override public HttpResponse onContext(HttpRequest request) { HttpMethod method = request.getMethod(); Gson gson = new GsonBuilder().setDateFormat(SystemProperties.get(SystemProperties.HCJF_DEFAULT_DATE_FORMAT)).create(); JsonElement jsonElement; Collection<HttpHeader> headers = new ArrayList<>(); String lastPart = request.getPathParts().get(request.getPathParts().size() -1); Object id = null; for(Pattern idRegex : idRegexList) { if(idRegex.matcher(lastPart).matches()) { id = Strings.deductInstance(lastPart); break; } } String resourceName = Strings.join(request.getPathParts().stream().skip(1).limit(request.getPathParts().size() - (id == null ? 0 : 2)), Strings.CLASS_SEPARATOR); if(method.equals(HttpMethod.GET)) { if(id == null) { if (request.hasParameter(DEFAULT_QUERY_PARAMETER)) { Queryable queryable = Query.compile(request.getParameter(DEFAULT_QUERY_PARAMETER)); Collection<JoinableMap> queryResult = queryable.evaluate(getDataSource()); if(queryResult instanceof ResultSet) { ResultSet<JoinableMap> resultSet = (ResultSet<JoinableMap>) queryResult; headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_TOTAL_TIME, resultSet.getTotalTime().toString())); headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_TIME_COMPILING, resultSet.getTimeCompilingQuery().toString())); headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_TIME_COLLECTING_DATA, resultSet.getTimeCollectingData().toString())); headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_TIME_EVALUATING_CONDITIONS, resultSet.getTimeEvaluatingConditions().toString())); headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_AVERAGE_TIME_EVALUATING_CONDITIONS, resultSet.getAverageTimeFormattingDataByRow().toString())); headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_TIME_FORMATTING_DATA, resultSet.getTimeFormattingData().toString())); headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_AVERAGE_TIME_FORMATTING_DATA, resultSet.getAverageTimeFormattingDataByRow().toString())); headers.add(new HttpHeader(HttpHeader.X_HCJF_QUERY_PRESENT_FIELDS, Strings.join(resultSet.getPresentFields(), Strings.ARGUMENT_SEPARATOR))); } jsonElement = gson.toJsonTree(queryResult); } else { ReadLayerInterface readLayerInterface = Layers.get(ReadLayerInterface.class, resourceName); jsonElement = gson.toJsonTree(readLayerInterface.read()); } } else { ReadLayerInterface readLayerInterface = Layers.get(ReadLayerInterface.class, resourceName); jsonElement = gson.toJsonTree(readLayerInterface.read(id)); } } else if(method.equals(HttpMethod.POST)) { JsonElement body = JsonParser.parseString(new String(request.getBody())); RequestModel requestModel; if (body.isJsonObject()) { requestModel = new RequestModel((JsonObject) body); } else { requestModel = new RequestModel((JsonArray) body); } if(requestModel.getBody() == null) { // If the method is post and the body object is null then the request attempt to create a parameterized // query instance or a group of queryable instances. Queryable.DataSource dataSource = requestModel.getDataSource(); if(requestModel.getQueryable() != null) { jsonElement = gson.toJsonTree(requestModel.getQueryable().evaluate(verifyDataSource(dataSource))); } else if(requestModel.getQueryables() != null){ JsonObject queriesResult = new JsonObject(); for(String key : requestModel.getQueryables().keySet()) { try { queriesResult.add(key, gson.toJsonTree(requestModel.getQueryables().get(key).evaluate(verifyDataSource(dataSource)))); } catch (Throwable throwable){ queriesResult.add(key, createJsonFromThrowable(throwable)); } } for(String key : requestModel.getPointers().keySet()) { String value = requestModel.getPointers().get(key); queriesResult.add(key, gson.toJsonTree(requestModel.getDataSourcesMap().get(value))); } jsonElement = queriesResult; } else { throw new HCJFRuntimeException("Unsupported POST method configuration"); } } else { // This method call by default to create layer interface implementation. CreateLayerInterface createLayerInterface = Layers.get(CreateLayerInterface.class, resourceName); if(requestModel.getBody() instanceof Collection) { jsonElement = gson.toJsonTree(createLayerInterface.create((Collection) requestModel.getBody())); } else { jsonElement = gson.toJsonTree(createLayerInterface.create(requestModel.getBody())); } } } else if(method.equals(HttpMethod.PUT)) { // This method call to update layer interface implementation. UpdateLayerInterface updateLayerInterface = Layers.get(UpdateLayerInterface.class, resourceName); RequestModel requestModel = new RequestModel(JsonParser.parseString(new String(request.getBody())).getAsJsonObject()); if(requestModel.getQueryable() == null) { if(id != null) { ((Map<String, Object>) requestModel.getBody()).put(Fields.ID_URL_FIELD, id); } if(requestModel.getBody() instanceof Collection) { jsonElement = gson.toJsonTree(updateLayerInterface.update((Collection) requestModel.getBody())); } else { jsonElement = gson.toJsonTree(updateLayerInterface.update(requestModel.getBody())); } } else { jsonElement = gson.toJsonTree(updateLayerInterface.update(requestModel.queryable, requestModel.getBody())); } } else if(method.equals(HttpMethod.DELETE)) { // This method call to delete layer interface implementation. DeleteLayerInterface deleteLayerInterface = Layers.get(DeleteLayerInterface.class, resourceName); if(id != null && (request.getBody() == null || request.getBody().length == 0)) { jsonElement = gson.toJsonTree(deleteLayerInterface.delete(id)); } else { RequestModel requestModel = new RequestModel(JsonParser.parseString(new String(request.getBody())).getAsJsonObject()); if(requestModel.getQueryable() != null) { jsonElement = gson.toJsonTree(deleteLayerInterface.delete(requestModel.getQueryable())); } else { jsonElement = gson.toJsonTree(deleteLayerInterface.delete(requestModel.getBody())); } } } else { throw new HCJFRuntimeException("Unsupported http method: %s", method.toString()); } HttpResponse response = new HttpResponse(); response.addHeader(new HttpHeader(HttpHeader.CONTENT_TYPE, MimeType.APPLICATION_JSON.toString())); byte[] body = jsonElement.toString().getBytes(); response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length))); for(HttpHeader header : headers) { response.addHeader(header); } response.setBody(body); return response; } /** * This method generate error response all the times that the request generates an throwable instance. * @param request All the request information. * @param throwable Throwable object, could be null. * @return Returns http response instance. */ @Override protected HttpResponse onError(HttpRequest request, Throwable throwable) { HttpResponse response = new HttpResponse(); response.setResponseCode(HttpResponseCode.BAD_REQUEST); response.addHeader(new HttpHeader(HttpHeader.CONTENT_TYPE, MimeType.APPLICATION_JSON.toString())); byte[] body = createJsonFromThrowable(throwable).toString().getBytes(); response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length))); response.setBody(body); return response; } /** * This method create a json object from a throwable. * @param throwable throwable instance. * @return Json object. */ private JsonObject createJsonFromThrowable(Throwable throwable) { JsonObject jsonObject = new JsonObject(); if(throwable.getMessage() != null) { jsonObject.addProperty(Fields.Throwable.MESSAGE, throwable.getMessage()); } Map<String,String> tags = getTags(throwable, new HashMap<>()); if(!tags.isEmpty()) { JsonObject jsonTags = new JsonObject(); for(String tag : tags.keySet()) { jsonTags.addProperty(tag, tags.get(tag)); } jsonObject.add(Fields.Throwable.TAGS, jsonTags); } jsonObject.addProperty(Fields.Throwable.EXCEPTION, throwable.getClass().getName()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(byteArrayOutputStream); throwable.printStackTrace(printStream); jsonObject.addProperty(Fields.Throwable.BODY, byteArrayOutputStream.toString()); return jsonObject; } /** * Find all the tags into the throwable instances and his causes. * @param throwable Throwable instance. * @param tag Map to store the tags founded. * @return Return the same map sending as parameter. */ private Map<String,String> getTags(Throwable throwable, Map<String,String> tag) { if(throwable.getMessage() != null) { tag.putAll(Strings.getTagsFromMessage(throwable.getMessage())); } if(throwable.getCause() != null) { tag = getTags(throwable.getCause(), tag); } return tag; } private Queryable.DataSource verifyDataSource(Queryable.DataSource dataSource){ return dataSource == null ? getDataSource() : dataSource; } protected Queryable.DataSource<JoinableMap> getDataSource(){ return new Queryable.ReadableDataSource(); } /** * This inner class contains the necessary methods to parse the request body in order to call * the specific layer implementation. */ private static class RequestModel { private Object body; private Queryable queryable; private Map<String,Queryable> queryables; private Map<String,String> pointers; private Map<String,Object> requestConfig; private Map<String,Object> dataSourcesMap; private Queryable.DataSource<Object> dataSource; public RequestModel(JsonArray jsonArray) { body = JsonUtils.createList(jsonArray); } public RequestModel(JsonObject jsonObject) { if(!jsonObject.has(SystemProperties.get(SystemProperties.Net.Rest.BODY_FIELD)) && !jsonObject.has(SystemProperties.get(SystemProperties.Net.Rest.QUERY_FIELD)) && !jsonObject.has(SystemProperties.get(SystemProperties.Net.Rest.QUERIES_FIELD))) { body = JsonUtils.createBody(jsonObject); } else { if (jsonObject.has(SystemProperties.get(SystemProperties.Net.Rest.BODY_FIELD))) { body = JsonUtils.createBody(jsonObject.getAsJsonObject(SystemProperties.get(SystemProperties.Net.Rest.BODY_FIELD))); } if (jsonObject.has(SystemProperties.get(SystemProperties.Net.Rest.QUERY_FIELD))) { queryable = (Queryable) createQuery(jsonObject.get(SystemProperties.get(SystemProperties.Net.Rest.QUERY_FIELD))); } if (jsonObject.has(SystemProperties.get(SystemProperties.Net.Rest.QUERIES_FIELD))) { pointers = new HashMap<>(); queryables = new HashMap<>(); JsonObject queryablesObject = jsonObject.getAsJsonObject(SystemProperties.get(SystemProperties.Net.Rest.QUERIES_FIELD)); for (String key : queryablesObject.keySet()) { Object query = createQuery(queryablesObject.get(key)); if(query instanceof Queryable) { queryables.put(key, (Queryable) query); } else { pointers.put(key, (String) query); } } } if (jsonObject.has(SystemProperties.get(SystemProperties.Net.Rest.DATA_SOURCE_FIELD))) { Map<String, Object> rawDataSources = (Map<String, Object>) JsonUtils.createObject(jsonObject.get( SystemProperties.get(SystemProperties.Net.Rest.DATA_SOURCE_FIELD))); DataSourceServiceConsumer consumer = new DataSourceServiceConsumer(rawDataSources); DataSourceService.getInstance().registerConsumer(consumer); dataSourcesMap = consumer.getResult(); dataSource = queryable -> { if(dataSourcesMap.containsKey(queryable.getResourceName())) { return (Collection<Object>) dataSourcesMap.get(queryable.getResourceName()); } else { throw new HCJFRuntimeException("Data source not found: %s", queryable.getResourceName()); } }; } } } /** * Creates the queryable instance from a json element. * @param element Json element instance. * @return Returns the queriable instance. */ private Object createQuery(JsonElement element) { Object result; if(element instanceof JsonObject) { JsonObject queryJsonObject = element.getAsJsonObject(); ParameterizedQuery parameterizedQuery = Query.compile(queryJsonObject.get(Fields.VALUE_FIELD).getAsString()).getParameterizedQuery(); if(queryJsonObject.has(Fields.PARAMS_FIELD)) { for (Object parameter : JsonUtils.createList(queryJsonObject.get(Fields.PARAMS_FIELD).getAsJsonArray())) { parameterizedQuery.add(parameter); } } result = parameterizedQuery; } else { String value = element.getAsString(); if(value.startsWith(Fields.POINTER_PREFIX)) { result = value.substring(Fields.POINTER_PREFIX.length()); } else { result = Query.compile(element.getAsString()); } } return result; } /** * Returns the body of the request. * @return Body of the request. */ public Object getBody() { return body; } /** * Returns the queryable instance of the request. * @return Queriable instace. */ public Queryable getQueryable() { return queryable; } /** * Returns a map of the queryable instances of the request. * @return Queryable instances of the request. */ public Map<String, Queryable> getQueryables() { return queryables; } public Map<String, String> getPointers() { return pointers; } public Map<String, Object> getDataSourcesMap() { return dataSourcesMap; } public Queryable.DataSource<Object> getDataSource() { return dataSource; } } }
package org.highj.data.collection; import java.util.Arrays; /** * * @author clintonselke */ public class IntMap<A> { private static final int NUM_BRANCHING_BITS = 5; private static final int NUM_BRANCHES = 1 << NUM_BRANCHING_BITS; private static final int MASK = (1 << NUM_BRANCHING_BITS) - 1; private final Node<A> root; private IntMap(Node<A> root) { this.root = root; } private static final IntMap<?> EMPTY = new IntMap<>(Empty.empty()); public static <A> IntMap<A> empty() { return (IntMap<A>)EMPTY; } public IntMap<A> insert(int key, A value) { return new IntMap<>(root.insert(key, value)); } public Maybe<A> lookup(int key) { return root.lookup(key); } public IntMap<A> delete(int key) { Node<A> root2 = root.delete(key); return root2 == root ? this : new IntMap<>(root2); } @Override public String toString() { return root.toString(); } private static abstract class Node<A> { public abstract boolean isEmpty(); public abstract Node<A> insert(int key, A value); public abstract Maybe<A> lookup(int key); public abstract Node<A> delete(int key); } private static class Empty<A> extends Node<A> { private static final Empty<?> EMPTY = new Empty<>(); public static <A> Empty<A> empty() { return (Empty<A>)EMPTY; } @Override public boolean isEmpty() { return true; } @Override public Node<A> insert(int key, A value) { if (key == 0) { return new Leaf<>(value); } else { int key2 = key >>> NUM_BRANCHING_BITS; int idx = key & MASK; Node<A>[] nodes = new Node[NUM_BRANCHES]; if (key2 == 0) { nodes[idx] = new Leaf<>(value); } else { nodes[idx] = Empty.<A>empty().insert(key2, value); } return new Branch<>(nodes); } } @Override public Maybe<A> lookup(int key) { return Maybe.newNothing(); } @Override public String toString() { return "Empty"; } @Override public Node<A> delete(int key) { return this; } } private static class Leaf<A> extends Node<A> { private final A value; public Leaf(A value) { this.value = value; } @Override public boolean isEmpty() { return false; } @Override public Node<A> insert(int key, A value2) { if (key == 0) { return new Leaf<>(value2); } else { int key2 = key >>> NUM_BRANCHING_BITS; int idx = key & MASK; Node<A>[] nodes = new Node[NUM_BRANCHES]; if (key2 == 0) { nodes[0] = this; nodes[idx] = new Leaf<>(value2); } else { if (idx == 0) { nodes[0] = Empty.<A>empty().insert(0, value).insert(key2, value2); } else { nodes[0] = this; nodes[idx] = Empty.<A>empty().insert(key2, value2); } } return new Branch<>(nodes); } } @Override public Maybe<A> lookup(int key) { return key == 0 ? Maybe.newJust(value) : Maybe.newNothing(); } @Override public String toString() { return "(Leaf " + value.toString() + ")"; } @Override public Node<A> delete(int key) { return key == 0 ? Empty.empty() : this; } } private static class Branch<A> extends Node<A> { private final Node<A>[] nodes; public Branch(Node<A>[] nodes) { this.nodes = nodes; } @Override public boolean isEmpty() { for (int i = 0; i < NUM_BRANCHES; ++i) { Node<A> node = nodes[i]; if (node == null) { continue; } if (!node.isEmpty()) { return false; } } return true; } @Override public Node<A> insert(int key, A value) { int key2 = key >>> NUM_BRANCHING_BITS; int idx = key & MASK; Node<A>[] nodes2 = Arrays.copyOf(nodes, nodes.length); if (key2 == 0) { nodes2[idx] = new Leaf<>(value); } else { nodes2[idx] = (nodes[idx] == null) ? Empty.<A>empty().insert(key2, value) : nodes[idx].insert(key2, value); } return new Branch<>(nodes2); } public Branch<A> set(int idx, Node<A> node) { Node<A>[] nodes2 = Arrays.copyOf(nodes, nodes.length); nodes2[idx] = node; return new Branch<>(nodes2); } @Override public Maybe<A> lookup(int key) { int key2 = key >>> NUM_BRANCHING_BITS; int idx = key & MASK; Node node = nodes[idx]; return node == null ? Maybe.newNothing() : node.lookup(key2); } @Override public Node<A> delete(int key) { int key2 = key >>> NUM_BRANCHING_BITS; int idx = key & MASK; Node<A> node = nodes[idx]; if (node == null) { return this; } else { Node<A> node2 = node.delete(key2); if (node2 == node) { return this; } else { Node<A>[] nodes2 = Arrays.copyOf(nodes, nodes.length); nodes2[idx] = node2; Node<A> r = new Branch<>(nodes2); return r.isEmpty() ? Empty.<A>empty() : r; } } } @Override public String toString() { StringBuilder sb = new StringBuilder("(Branch"); for (int i = 0; i < nodes.length; ++i) { sb.append(" "); Node node = nodes[i]; sb.append((node == null ? Empty.<A>empty() : node).toString()); } sb.append(")"); return sb.toString(); } } }
package org.jbake.launcher; import java.io.File; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; class LaunchOptions { @Argument(index = 0, usage = "source folder of site content (with templates and assets) defaults to current working directory", metaVar = "source_folder") private File source = new File("."); @Argument(index = 1, usage = "destination folder for baked output, defaults to a folder called \"baked\" in the current working directory", metaVar = "destination_folder") private File destination = null; @Option(name = "-h", aliases = {"--help"}, usage="prints this message") private boolean isHelpNeeded; File getSource() { return source; } File getDestination() { return destination; } boolean isHelpNeeded() { return isHelpNeeded; } }
package org.jbake.launcher; import java.io.File; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; public class LaunchOptions { @Argument(index = 0, usage = "source folder of site content (with templates and assets), if not supplied will default to current working directory", metaVar = "source_folder") private File source = new File("."); @Argument(index = 1, usage = "destination folder for output, if not supplied will default to a folder called \"output\" in the current working directory", metaVar = "destination_folder") private File destination = null; @Option(name = "-i", aliases = {"--init"}, usage="initialises required folder structure with default templates") private boolean init; @Option(name = "-s", aliases = {"--server"}, usage="runs HTTP server to serve out destination folder") private boolean runServer; @Option(name = "-h", aliases = {"--help"}, usage="prints this message") private boolean helpNeeded; public File getSource() { return source; } public File getDestination() { return destination; } public boolean isHelpNeeded() { return helpNeeded; } public boolean isRunServer() { return runServer; } public boolean isInit() { return init; } }
package org.lightmare.deploy; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import org.apache.log4j.Logger; import org.lightmare.cache.ArchiveData; import org.lightmare.cache.DeployData; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.deploy.fs.Watcher; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.remote.rpc.RpcListener; import org.lightmare.rest.providers.RestProvider; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.AbstractIOUtils; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.fs.WatchUtils; import org.lightmare.utils.shutdown.ShutDown; /** * Determines and saves in cache EJB beans {@link org.lightmare.cache.MetaData} * on startup * * @author Levan * */ public class MetaCreator { private static AnnotationDB annotationDB; // Cached temporal resources for clean after deployment private TmpResources tmpResources; private boolean await; // Blocker for deployments connections or beans private CountDownLatch blocker; // Data for cache at deploy time private Map<String, AbstractIOUtils> aggregateds = new HashMap<String, AbstractIOUtils>(); private Map<URL, ArchiveData> archivesURLs; private Map<String, URL> classOwnersURL; private Map<URL, DeployData> realURL; private ClassLoader current; // Configuration for appropriate archives URLs private Configuration configuration; // Lock for deployment and directory scanning private final Lock scannerLock = new ReentrantLock(); // Lock for MetaCreator initialization private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(MetaCreator.class); private MetaCreator() { tmpResources = new TmpResources(); ShutDown.setHook(tmpResources); } private static MetaCreator get() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { LOCK.lock(); try { if (creator == null) { creator = new MetaCreator(); MetaContainer.setCreator(creator); } } finally { LOCK.unlock(); } } return creator; } private void configure(URL[] archives) { if (configuration == null && CollectionUtils.available(archives)) { configuration = MetaContainer.getConfig(archives); } } public AnnotationDB getAnnotationDB() { return annotationDB; } public Map<String, AbstractIOUtils> getAggregateds() { return aggregateds; } /** * Caches each archive by it's {@link URL} for deployment * * @param ejbURLs * @param archiveData */ private void fillArchiveURLs(Collection<URL> ejbURLs, ArchiveData archiveData, DeployData deployData) { for (URL ejbURL : ejbURLs) { archivesURLs.put(ejbURL, archiveData); realURL.put(ejbURL, deployData); } } /** * Caches each archive by it's {@link URL} for deployment and creates fill * {@link URL} array for scanning and finding {@link javax.ejb.Stateless} * annotated classes * * @param archive * @param modifiedArchives * @throws IOException */ private void fillArchiveURLs(URL archive, List<URL> modifiedArchives) throws IOException { AbstractIOUtils ioUtils = AbstractIOUtils.getAppropriatedType(archive); if (ObjectUtils.notNull(ioUtils)) { ioUtils.scan(configuration.isPersXmlFromJar()); List<URL> ejbURLs = ioUtils.getEjbURLs(); modifiedArchives.addAll(ejbURLs); ArchiveData archiveData = new ArchiveData(); archiveData.setIoUtils(ioUtils); DeployData deployData = new DeployData(); deployData.setType(ioUtils.getType()); deployData.setUrl(archive); if (ejbURLs.isEmpty()) { archivesURLs.put(archive, archiveData); realURL.put(archive, deployData); } else { fillArchiveURLs(ejbURLs, archiveData, deployData); } } } /** * Gets {@link URL} array for all classes and jar libraries within archive * file for class loading policy * * @param archives * @return {@link URL}[] * @throws IOException */ private URL[] getFullArchives(URL[] archives) throws IOException { List<URL> modifiedArchives = new ArrayList<URL>(); for (URL archive : archives) { fillArchiveURLs(archive, modifiedArchives); } return CollectionUtils.toArray(modifiedArchives, URL.class); } /** * Awaits for {@link Future} tasks if it set so by configuration * * @param future */ private void awaitDeployment(Future<String> future) { if (await) { try { String nameFromFuture = future.get(); LogUtils.info(LOG, "Deploy processing of %s finished", nameFromFuture); } catch (InterruptedException ex) { LOG.error(ex.getMessage(), ex); } catch (ExecutionException ex) { LOG.error(ex.getMessage(), ex); } } } /** * Awaits for {@link CountDownLatch} of deployments */ private void awaitDeployments() { try { blocker.await(); } catch (InterruptedException ex) { LOG.error(ex); } } /** * Starts bean deployment process for bean name * * @param beanName * @throws IOException */ private void deployBean(String beanName) throws IOException { URL currentURL = classOwnersURL.get(beanName); ArchiveData archiveData = archivesURLs.get(currentURL); if (archiveData == null) { archiveData = new ArchiveData(); } AbstractIOUtils ioUtils = archiveData.getIoUtils(); if (ioUtils == null) { ioUtils = AbstractIOUtils.getAppropriatedType(currentURL); archiveData.setIoUtils(ioUtils); } ClassLoader loader = archiveData.getLoader(); // Finds appropriated ClassLoader if needed and or creates new one List<File> tmpFiles = null; if (ObjectUtils.notNull(ioUtils)) { if (loader == null) { if (ioUtils.notExecuted()) { ioUtils.scan(configuration.isPersXmlFromJar()); } URL[] libURLs = ioUtils.getURLs(); loader = LibraryLoader.initializeLoader(libURLs); archiveData.setLoader(loader); } tmpFiles = ioUtils.getTmpFiles(); aggregateds.put(beanName, ioUtils); } // Archive file url which contains this bean DeployData deployData; if (CollectionUtils.available(realURL)) { deployData = realURL.get(currentURL); } else { deployData = null; } // Initializes and fills BeanLoader.BeanParameters class to deploy // stateless EJB bean BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters(); parameters.creator = this; parameters.className = beanName; parameters.loader = loader; parameters.tmpFiles = tmpFiles; parameters.blocker = blocker; parameters.deployData = deployData; parameters.configuration = configuration; Future<String> future = BeanLoader.loadBean(parameters); awaitDeployment(future); if (CollectionUtils.available(tmpFiles)) { tmpResources.addFile(tmpFiles); } } /** * Deploys single bean by class name * * @param beanNames */ private void deployBeans(Set<String> beanNames) { blocker = new CountDownLatch(beanNames.size()); for (String beanName : beanNames) { LogUtils.info(LOG, "Deploing bean %s", beanName); try { deployBean(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not deploy bean %s cause", beanName, ex.getMessage()); } } awaitDeployments(); if (RestContainer.hasRest()) { RestProvider.reload(); } boolean hotDeployment = configuration.isHotDeployment(); boolean watchStatus = configuration.isWatchStatus(); if (hotDeployment && ObjectUtils.notTrue(watchStatus)) { Watcher.startWatch(); watchStatus = Boolean.TRUE; } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @param archives * @throws IOException * @throws ClassNotFoundException */ public void scanForBeans(URL[] archives) throws IOException { scannerLock.lock(); try { configure(archives); // starts RPC server if configured as remote and server if (configuration.isRemote() && Configuration.isServer()) { RpcListener.startServer(configuration); } else if (configuration.isRemote()) { RPCall.configure(configuration); } String[] libraryPaths = configuration.getLibraryPaths(); // Loads libraries from specified path if (ObjectUtils.notNull(libraryPaths)) { LibraryLoader.loadLibraries(libraryPaths); } // Gets and caches class loader current = LibraryLoader.getContextClassLoader(); archivesURLs = new HashMap<URL, ArchiveData>(); if (CollectionUtils.available(archives)) { realURL = new HashMap<URL, DeployData>(); } URL[] fullArchives = getFullArchives(archives); annotationDB = new AnnotationDB(); annotationDB.setScanFieldAnnotations(Boolean.FALSE); annotationDB.setScanParameterAnnotations(Boolean.FALSE); annotationDB.setScanMethodAnnotations(Boolean.FALSE); annotationDB.scanArchives(fullArchives); Set<String> beanNames = annotationDB.getAnnotationIndex().get( Stateless.class.getName()); classOwnersURL = annotationDB.getClassOwnersURLs(); Initializer.initializeDataSources(configuration); if (CollectionUtils.available(beanNames)) { deployBeans(beanNames); } } finally { // Caches configuration MetaContainer.putConfig(archives, configuration); // clears cached resources clear(); // gets rid from all created temporary files tmpResources.removeTempFiles(); scannerLock.unlock(); } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(File[] jars) throws IOException { List<URL> urlList = new ArrayList<URL>(); URL url; for (File file : jars) { url = file.toURI().toURL(); urlList.add(url); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(String... paths) throws IOException { if (CollectionUtils.notAvailable(paths) && CollectionUtils.available(configuration.getDeploymentPath())) { Set<DeploymentDirectory> deployments = configuration .getDeploymentPath(); List<String> pathList = new ArrayList<String>(); File deployFile; for (DeploymentDirectory deployment : deployments) { deployFile = new File(deployment.getPath()); if (deployment.isScan()) { String[] subDeployments = deployFile.list(); if (CollectionUtils.available(subDeployments)) { pathList.addAll(Arrays.asList(subDeployments)); } } } paths = CollectionUtils.toArray(pathList, String.class); } List<URL> urlList = new ArrayList<URL>(); List<URL> archive; for (String path : paths) { archive = FileUtils.toURLWithClasspath(path); urlList.addAll(archive); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } public ClassLoader getCurrent() { return current; } /** * Clears all locally cached data */ public void clear() { boolean locked = scannerLock.tryLock(); while (ObjectUtils.notTrue(locked)) { locked = scannerLock.tryLock(); } if (locked) { try { if (CollectionUtils.available(realURL)) { realURL.clear(); realURL = null; } if (CollectionUtils.available(aggregateds)) { aggregateds.clear(); } if (CollectionUtils.available(archivesURLs)) { archivesURLs.clear(); archivesURLs = null; } if (CollectionUtils.available(classOwnersURL)) { classOwnersURL.clear(); classOwnersURL = null; } configuration = null; } finally { scannerLock.unlock(); } } } /** * Closes all connections clears all caches * * @throws IOException */ public static void close() throws IOException { ShutDown.clearAll(); } /** * Builder class to provide properties for lightmare application and * initialize {@link MetaCreator} instance * * @author levan * */ public static class Builder { private MetaCreator creator; public Builder(boolean cloneConfiguration) throws IOException { creator = MetaCreator.get(); Configuration config = creator.configuration; if (cloneConfiguration && ObjectUtils.notNull(config)) { try { creator.configuration = (Configuration) config.clone(); } catch (CloneNotSupportedException ex) { throw new IOException(ex); } } else { creator.configuration = new Configuration(); } } public Builder() throws IOException { this(Boolean.FALSE); } public Builder(Map<Object, Object> configuration) throws IOException { this(); creator.configuration.configure(configuration); } public Builder(String path) throws IOException { this(); creator.configuration.configure(path); } private Map<Object, Object> initPersistenceProperties() { Map<Object, Object> persistenceProperties = creator.configuration .getPersistenceProperties(); if (persistenceProperties == null) { persistenceProperties = new HashMap<Object, Object>(); creator.configuration .setPersistenceProperties(persistenceProperties); } return persistenceProperties; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setPersistenceProperties(Map<String, String> properties) { if (ObjectUtils.available(properties)) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.putAll(properties); } return this; } /** * Adds instant persistence property * * @param key * @param property * @return {@link Builder} */ public Builder addPersistenceProperty(String key, String property) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.put(key, property); return this; } /** * Adds property to scan for {@link javax.persistence.Entity} annotated * classes from deployed archives * * @param scanForEnt * @return {@link Builder} */ public Builder setScanForEntities(boolean scanForEnt) { creator.configuration.setScanForEntities(scanForEnt); return this; } /** * Adds property to use only {@link org.lightmare.annotations.UnitName} * annotated entities for which * {@link org.lightmare.annotations.UnitName#value()} matches passed * unit name * * @param unitName * @return {@link Builder} */ public Builder setUnitName(String unitName) { creator.configuration.setAnnotatedUnitName(unitName); return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPersXmlPath(String path) { creator.configuration.setPersXmlPath(path); creator.configuration.setScanArchives(Boolean.FALSE); return this; } /** * Adds path for additional libraries to load at start time * * @param libPaths * @return {@link Builder} */ public Builder setLibraryPath(String... libPaths) { creator.configuration.setLibraryPaths(libPaths); return this; } /** * Sets boolean checker to scan persistence.xml files from appropriated * jar files * * @param xmlFromJar * @return {@link Builder} */ public Builder setXmlFromJar(boolean xmlFromJar) { creator.configuration.setPersXmlFromJar(xmlFromJar); return this; } /** * Sets boolean checker to swap jta data source value with non jta data * source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { creator.configuration.setSwapDataSource(swapDataSource); return this; } /** * Adds path for data source file * * @param dataSourcePath * @return {@link Builder} */ public Builder addDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * This method is deprecated should use * {@link MetaCreator.Builder#addDataSourcePath(String)} instead * * @param dataSourcePath * @return {@link MetaCreator.Builder} */ @Deprecated public Builder setDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * Sets boolean checker to scan {@link javax.persistence.Entity} * annotated classes from appropriated deployed archive files * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { creator.configuration.setScanArchives(scanArchives); return this; } /** * Sets boolean checker to block deployment processes * * @param await * @return {@link Builder} */ public Builder setAwaitDeploiment(boolean await) { creator.await = await; return this; } /** * Sets property is server or not in embedded mode * * @param remote * @return {@link Builder} */ public Builder setRemote(boolean remote) { creator.configuration.setRemote(remote); return this; } /** * Sets property is application server or just client for other remote * server * * @param server * @return {@link Builder} */ public Builder setServer(boolean server) { Configuration.setServer(server); creator.configuration.setClient(ObjectUtils.notTrue(server)); return this; } /** * Sets boolean check is application in just client mode or not * * @param client * @return {@link Builder} */ public Builder setClient(boolean client) { creator.configuration.setClient(client); Configuration.setServer(ObjectUtils.notTrue(client)); return this; } /** * To add any additional property * * @param key * @param property * @return {@link Builder} */ public Builder setProperty(String key, String property) { creator.configuration.putValue(key, property); return this; } /** * File path for administrator user name and password * * @param property * @return {@link Builder} */ public Builder setAdminUsersPth(String property) { Configuration.setAdminUsersPath(property); return this; } /** * Sets specific IP address in case when application is in remote server * mode * * @param property * @return {@link Builder} */ public Builder setIpAddress(String property) { creator.configuration.putValue(ConfigKeys.IP_ADDRESS.key, property); return this; } /** * Sets specific port in case when application is in remote server mode * * @param property * @return {@link Builder} */ public Builder setPort(String property) { creator.configuration.putValue(ConfigKeys.PORT.key, property); return this; } /** * Sets amount for network master threads in case when application is in * remote server mode * * @param property * @return {@link Builder} */ public Builder setMasterThreads(String property) { creator.configuration.putValue(ConfigKeys.BOSS_POOL.key, property); return this; } /** * Sets amount of worker threads in case when application is in remote * server mode * * @param property * @return {@link Builder} */ public Builder setWorkerThreads(String property) { creator.configuration .putValue(ConfigKeys.WORKER_POOL.key, property); return this; } /** * Adds deploy file path to application with boolean checker if file is * directory to scan this directory for deployment files list * * @param deploymentPath * @param scan * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath, boolean scan) { String clearPath = WatchUtils.clearPath(deploymentPath); creator.configuration.addDeploymentPath(clearPath, scan); return this; } /** * Adds deploy file path to application * * @param deploymentPath * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath) { addDeploymentPath(deploymentPath, Boolean.FALSE); return this; } /** * Adds timeout for connection in case when application is in remote * server or client mode * * @param property * @return {@link Builder} */ public Builder setTimeout(String property) { creator.configuration.putValue(ConfigKeys.CONNECTION_TIMEOUT.key, property); return this; } /** * Adds boolean check if application is using pooled data source * * @param dsPooledType * @return {@link Builder} */ public Builder setDataSourcePooledType(boolean dsPooledType) { creator.configuration.setDataSourcePooledType(dsPooledType); return this; } /** * Sets which data source pool provider should use application by * {@link PoolProviderType} parameter * * @param poolProviderType * @return {@link Builder} */ public Builder setPoolProviderType(PoolProviderType poolProviderType) { creator.configuration.setPoolProviderType(poolProviderType); return this; } /** * Sets path for data source pool additional properties * * @param path * @return {@link Builder} */ public Builder setPoolPropertiesPath(String path) { creator.configuration.setPoolPropertiesPath(path); return this; } /** * Sets data source pool additional properties * * @param properties * @return {@link Builder} */ public Builder setPoolProperties( Map<? extends Object, ? extends Object> properties) { creator.configuration.setPoolProperties(properties); return this; } /** * Adds instance property for pooled data source * * @param key * @param value * @return {@link Builder} */ public Builder addPoolProperty(Object key, Object value) { creator.configuration.addPoolProperty(key, value); return this; } /** * Sets boolean check is application in hot deployment (with watch * service on deployment directories) or not * * @param hotDeployment * @return {@link Builder} */ public Builder setHotDeployment(boolean hotDeployment) { creator.configuration.setHotDeployment(hotDeployment); return this; } /** * Adds additional parameters from passed {@link Map} to existing * configuration * * @param configuration * @return */ public Builder addConfiguration(Map<Object, Object> configuration) { creator.configuration.configure(configuration); return this; } public MetaCreator build() throws IOException { creator.configuration.configure(); LOG.info("Lightmare application starts working"); return creator; } } }