lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 87933103fae6e2850326b1ba62eed1c6bc4228d1 | 0 | ivoryworks/PGMA | package com.ivoryworks.pgma;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import static com.ivoryworks.pgma.R.color.fab_red;
public class CanvasCustomView extends View {
private Paint mPaint = new Paint();
public CanvasCustomView(Context context) {
super(context);
}
public CanvasCustomView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = canvas.getWidth() / 2;
int centerY = canvas.getHeight() / 2;
// Background
canvas.drawColor(Color.parseColor("#330000cc"));
// Text
mPaint.setTextSize(48);
canvas.drawText("Canvas draw", 50, 50, mPaint);
// Rect
mPaint.setColor(Color.DKGRAY);
canvas.drawRect(centerX - 100, centerY - 100, centerX + 100, centerY + 100, mPaint);
// Circle
mPaint.setColor(Color.argb(192, 255, 64, 64));
mPaint.setAntiAlias(true);
canvas.drawCircle(50.5f, 30.5f, 50.0f, mPaint);
// Oval
mPaint.setColor(Color.argb(192, 255, 64, 255));
RectF ovalF = new RectF(centerX - 200, centerY - 100, centerX + 200, centerY + 100);
canvas.drawOval(ovalF, mPaint);
}
}
| com.ivoryworks.pgma/app/src/main/java/com/ivoryworks/pgma/CanvasCustomView.java | package com.ivoryworks.pgma;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import static com.ivoryworks.pgma.R.color.fab_red;
public class CanvasCustomView extends View {
private Paint mPaint = new Paint();
public CanvasCustomView(Context context) {
super(context);
}
public CanvasCustomView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = canvas.getWidth() / 2;
int centerY = canvas.getHeight() / 2;
// Background
canvas.drawColor(Color.parseColor("#330000cc"));
// Text
mPaint.setTextSize(48);
canvas.drawText("Canvas draw", 50, 50, mPaint);
// Rect
mPaint.setColor(Color.DKGRAY);
canvas.drawRect(centerX-100, centerY-100, centerX+100, centerY+100, mPaint);
// Circle
mPaint.setColor(Color.argb(192, 255, 64, 64));
mPaint.setAntiAlias(true);
canvas.drawCircle(50.5f, 30.5f, 50.0f, mPaint);
}
}
| [modify]Canvas:add Oval
楕円の描画
| com.ivoryworks.pgma/app/src/main/java/com/ivoryworks/pgma/CanvasCustomView.java | [modify]Canvas:add Oval | <ide><path>om.ivoryworks.pgma/app/src/main/java/com/ivoryworks/pgma/CanvasCustomView.java
<ide> import android.graphics.Canvas;
<ide> import android.graphics.Color;
<ide> import android.graphics.Paint;
<add>import android.graphics.RectF;
<ide> import android.graphics.drawable.Drawable;
<ide> import android.text.TextPaint;
<ide> import android.util.AttributeSet;
<ide>
<ide> // Rect
<ide> mPaint.setColor(Color.DKGRAY);
<del> canvas.drawRect(centerX-100, centerY-100, centerX+100, centerY+100, mPaint);
<add> canvas.drawRect(centerX - 100, centerY - 100, centerX + 100, centerY + 100, mPaint);
<ide>
<ide> // Circle
<ide> mPaint.setColor(Color.argb(192, 255, 64, 64));
<ide> mPaint.setAntiAlias(true);
<ide> canvas.drawCircle(50.5f, 30.5f, 50.0f, mPaint);
<add>
<add> // Oval
<add> mPaint.setColor(Color.argb(192, 255, 64, 255));
<add> RectF ovalF = new RectF(centerX - 200, centerY - 100, centerX + 200, centerY + 100);
<add> canvas.drawOval(ovalF, mPaint);
<ide> }
<ide> } |
|
Java | mit | dc12a508a6d2add87b41c316c4d027dd81b85a10 | 0 | sake/bouncycastle-java | package org.bouncycastle.jce.provider.test;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.DEREnumerated;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cms.SignedData;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.CRLReason;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.X509KeyUsage;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.interfaces.ECPointEncoder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.jce.spec.GOST3410ParameterSpec;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.SimpleTest;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.bouncycastle.x509.X509V2CRLGenerator;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure;
import org.bouncycastle.x509.extension.X509ExtensionUtil;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.cert.CRL;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509CRL;
import java.security.cert.X509CRLEntry;
import java.security.cert.X509Certificate;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
public class CertTest
extends SimpleTest
{
//
// server.crt
//
byte[] cert1 = Base64.decode(
"MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx"
+ "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY"
+ "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB"
+ "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ"
+ "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU2MjFaFw0wMTA2"
+ "MDIwNzU2MjFaMIG4MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW"
+ "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM"
+ "dGQxFzAVBgNVBAsTDldlYnNlcnZlciBUZWFtMR0wGwYDVQQDExR3d3cyLmNvbm5l"
+ "Y3Q0LmNvbS5hdTEoMCYGCSqGSIb3DQEJARYZd2VibWFzdGVyQGNvbm5lY3Q0LmNv"
+ "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArvDxclKAhyv7Q/Wmr2re"
+ "Gw4XL9Cnh9e+6VgWy2AWNy/MVeXdlxzd7QAuc1eOWQkGQEiLPy5XQtTY+sBUJ3AO"
+ "Rvd2fEVJIcjf29ey7bYua9J/vz5MG2KYo9/WCHIwqD9mmG9g0xLcfwq/s8ZJBswE"
+ "7sb85VU+h94PTvsWOsWuKaECAwEAAaN3MHUwJAYDVR0RBB0wG4EZd2VibWFzdGVy"
+ "QGNvbm5lY3Q0LmNvbS5hdTA6BglghkgBhvhCAQ0ELRYrbW9kX3NzbCBnZW5lcmF0"
+ "ZWQgY3VzdG9tIHNlcnZlciBjZXJ0aWZpY2F0ZTARBglghkgBhvhCAQEEBAMCBkAw"
+ "DQYJKoZIhvcNAQEEBQADgYEAotccfKpwSsIxM1Hae8DR7M/Rw8dg/RqOWx45HNVL"
+ "iBS4/3N/TO195yeQKbfmzbAA2jbPVvIvGgTxPgO1MP4ZgvgRhasaa0qCJCkWvpM4"
+ "yQf33vOiYQbpv4rTwzU8AmRlBG45WdjyNIigGV+oRc61aKCTnLq7zB8N3z1TF/bF"
+ "5/8=");
//
// ca.crt
//
byte[] cert2 = Base64.decode(
"MIIDbDCCAtWgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx"
+ "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY"
+ "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB"
+ "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ"
+ "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU1MzNaFw0wMTA2"
+ "MDIwNzU1MzNaMIG3MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW"
+ "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM"
+ "dGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEVMBMGA1UEAxMMQ29u"
+ "bmVjdCA0IENBMSgwJgYJKoZIhvcNAQkBFhl3ZWJtYXN0ZXJAY29ubmVjdDQuY29t"
+ "LmF1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgs5ptNG6Qv1ZpCDuUNGmv"
+ "rhjqMDPd3ri8JzZNRiiFlBA4e6/ReaO1U8ASewDeQMH6i9R6degFdQRLngbuJP0s"
+ "xcEE+SksEWNvygfzLwV9J/q+TQDyJYK52utb++lS0b48A1KPLwEsyL6kOAgelbur"
+ "ukwxowprKUIV7Knf1ajetQIDAQABo4GFMIGCMCQGA1UdEQQdMBuBGXdlYm1hc3Rl"
+ "ckBjb25uZWN0NC5jb20uYXUwDwYDVR0TBAgwBgEB/wIBADA2BglghkgBhvhCAQ0E"
+ "KRYnbW9kX3NzbCBnZW5lcmF0ZWQgY3VzdG9tIENBIGNlcnRpZmljYXRlMBEGCWCG"
+ "SAGG+EIBAQQEAwICBDANBgkqhkiG9w0BAQQFAAOBgQCsGvfdghH8pPhlwm1r3pQk"
+ "msnLAVIBb01EhbXm2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz"
+ "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ"
+ "DhkaJ8VqOMajkQFma2r9iA==");
//
// testx509.pem
//
byte[] cert3 = Base64.decode(
"MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV"
+ "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz"
+ "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM"
+ "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF"
+ "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO"
+ "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE"
+ "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ"
+ "zl9HYIMxATFyqSiD9jsx");
//
// v3-cert1.pem
//
byte[] cert4 = Base64.decode(
"MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx"
+ "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz"
+ "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw"
+ "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu"
+ "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2"
+ "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp"
+ "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C"
+ "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK"
+ "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x"
+ "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR"
+ "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB"
+ "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21"
+ "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3"
+ "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO");
//
// v3-cert2.pem
//
byte[] cert5 = Base64.decode(
"MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD"
+ "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0"
+ "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu"
+ "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1"
+ "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV"
+ "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx"
+ "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA"
+ "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT"
+ "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ"
+ "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm"
+ "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc"
+ "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz"
+ "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap"
+ "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU=");
//
// pem encoded pkcs7
//
byte[] cert6 = Base64.decode(
"MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIJbzCCAj0w"
+ "ggGmAhEAzbp/VvDf5LxU/iKss3KqVTANBgkqhkiG9w0BAQIFADBfMQswCQYDVQQGEwJVUzEXMBUG"
+ "A1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGljIFByaW1hcnkgQ2Vy"
+ "dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTYwMTI5MDAwMDAwWhcNMjgwODAxMjM1OTU5WjBfMQsw"
+ "CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVi"
+ "bGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0A"
+ "MIGJAoGBAOUZv22jVmEtmUhx9mfeuY3rt56GgAqRDvo4Ja9GiILlc6igmyRdDR/MZW4MsNBWhBiH"
+ "mgabEKFz37RYOWtuwfYV1aioP6oSBo0xrH+wNNePNGeICc0UEeJORVZpH3gCgNrcR5EpuzbJY1zF"
+ "4Ncth3uhtzKwezC6Ki8xqu6jZ9rbAgMBAAEwDQYJKoZIhvcNAQECBQADgYEATD+4i8Zo3+5DMw5d"
+ "6abLB4RNejP/khv0Nq3YlSI2aBFsfELM85wuxAc/FLAPT/+Qknb54rxK6Y/NoIAK98Up8YIiXbix"
+ "3YEjo3slFUYweRb46gVLlH8dwhzI47f0EEA8E8NfH1PoSOSGtHuhNbB7Jbq4046rPzidADQAmPPR"
+ "cZQwggMuMIICl6ADAgECAhEA0nYujRQMPX2yqCVdr+4NdTANBgkqhkiG9w0BAQIFADBfMQswCQYD"
+ "VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGlj"
+ "IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTgwNTEyMDAwMDAwWhcNMDgwNTEy"
+ "MjM1OTU5WjCBzDEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy"
+ "dXN0IE5ldHdvcmsxRjBEBgNVBAsTPXd3dy52ZXJpc2lnbi5jb20vcmVwb3NpdG9yeS9SUEEgSW5j"
+ "b3JwLiBCeSBSZWYuLExJQUIuTFREKGMpOTgxSDBGBgNVBAMTP1ZlcmlTaWduIENsYXNzIDEgQ0Eg"
+ "SW5kaXZpZHVhbCBTdWJzY3JpYmVyLVBlcnNvbmEgTm90IFZhbGlkYXRlZDCBnzANBgkqhkiG9w0B"
+ "AQEFAAOBjQAwgYkCgYEAu1pEigQWu1X9A3qKLZRPFXg2uA1Ksm+cVL+86HcqnbnwaLuV2TFBcHqB"
+ "S7lIE1YtxwjhhEKrwKKSq0RcqkLwgg4C6S/7wju7vsknCl22sDZCM7VuVIhPh0q/Gdr5FegPh7Yc"
+ "48zGmo5/aiSS4/zgZbqnsX7vyds3ashKyAkG5JkCAwEAAaN8MHowEQYJYIZIAYb4QgEBBAQDAgEG"
+ "MEcGA1UdIARAMD4wPAYLYIZIAYb4RQEHAQEwLTArBggrBgEFBQcCARYfd3d3LnZlcmlzaWduLmNv"
+ "bS9yZXBvc2l0b3J5L1JQQTAPBgNVHRMECDAGAQH/AgEAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0B"
+ "AQIFAAOBgQCIuDc73dqUNwCtqp/hgQFxHpJqbS/28Z3TymQ43BuYDAeGW4UVag+5SYWklfEXfWe0"
+ "fy0s3ZpCnsM+tI6q5QsG3vJWKvozx74Z11NMw73I4xe1pElCY+zCphcPXVgaSTyQXFWjZSAA/Rgg"
+ "5V+CprGoksVYasGNAzzrw80FopCubjCCA/gwggNhoAMCAQICEBbbn/1G1zppD6KsP01bwywwDQYJ"
+ "KoZIhvcNAQEEBQAwgcwxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln"
+ "biBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3JlcG9zaXRvcnkvUlBB"
+ "IEluY29ycC4gQnkgUmVmLixMSUFCLkxURChjKTk4MUgwRgYDVQQDEz9WZXJpU2lnbiBDbGFzcyAx"
+ "IENBIEluZGl2aWR1YWwgU3Vic2NyaWJlci1QZXJzb25hIE5vdCBWYWxpZGF0ZWQwHhcNMDAxMDAy"
+ "MDAwMDAwWhcNMDAxMjAxMjM1OTU5WjCCAQcxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYD"
+ "VQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3Jl"
+ "cG9zaXRvcnkvUlBBIEluY29ycC4gYnkgUmVmLixMSUFCLkxURChjKTk4MR4wHAYDVQQLExVQZXJz"
+ "b25hIE5vdCBWYWxpZGF0ZWQxJzAlBgNVBAsTHkRpZ2l0YWwgSUQgQ2xhc3MgMSAtIE1pY3Jvc29m"
+ "dDETMBEGA1UEAxQKRGF2aWQgUnlhbjElMCMGCSqGSIb3DQEJARYWZGF2aWRAbGl2ZW1lZGlhLmNv"
+ "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqxBsdeNmSvFqhMNwhQgNzM8mdjX9eSXb"
+ "DawpHtQHjmh0AKJSa3IwUY0VIsyZHuXWktO/CgaMBVPt6OVf/n0R2sQigMP6Y+PhEiS0vCJBL9aK"
+ "0+pOo2qXrjVBmq+XuCyPTnc+BOSrU26tJsX0P9BYorwySiEGxGanBNATdVL4NdUCAwEAAaOBnDCB"
+ "mTAJBgNVHRMEAjAAMEQGA1UdIAQ9MDswOQYLYIZIAYb4RQEHAQgwKjAoBggrBgEFBQcCARYcaHR0"
+ "cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTARBglghkgBhvhCAQEEBAMCB4AwMwYDVR0fBCwwKjAo"
+ "oCagJIYiaHR0cDovL2NybC52ZXJpc2lnbi5jb20vY2xhc3MxLmNybDANBgkqhkiG9w0BAQQFAAOB"
+ "gQBC8yIIdVGpFTf8/YiL14cMzcmL0nIRm4kGR3U59z7UtcXlfNXXJ8MyaeI/BnXwG/gD5OKYqW6R"
+ "yca9vZOxf1uoTBl82gInk865ED3Tej6msCqFzZffnSUQvOIeqLxxDlqYRQ6PmW2nAnZeyjcnbI5Y"
+ "syQSM2fmo7n6qJFP+GbFezGCAkUwggJBAgEBMIHhMIHMMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j"
+ "LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazFGMEQGA1UECxM9d3d3LnZlcmlzaWdu"
+ "LmNvbS9yZXBvc2l0b3J5L1JQQSBJbmNvcnAuIEJ5IFJlZi4sTElBQi5MVEQoYyk5ODFIMEYGA1UE"
+ "AxM/VmVyaVNpZ24gQ2xhc3MgMSBDQSBJbmRpdmlkdWFsIFN1YnNjcmliZXItUGVyc29uYSBOb3Qg"
+ "VmFsaWRhdGVkAhAW25/9Rtc6aQ+irD9NW8MsMAkGBSsOAwIaBQCggbowGAYJKoZIhvcNAQkDMQsG"
+ "CSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDAxMDAyMTczNTE4WjAjBgkqhkiG9w0BCQQxFgQU"
+ "gZjSaBEY2oxGvlQUIMnxSXhivK8wWwYJKoZIhvcNAQkPMU4wTDAKBggqhkiG9w0DBzAOBggqhkiG"
+ "9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwBwYFKw4DAh0w"
+ "DQYJKoZIhvcNAQEBBQAEgYAzk+PU91/ZFfoiuKOECjxEh9fDYE2jfDCheBIgh5gdcCo+sS1WQs8O"
+ "HreQ9Nop/JdJv1DQMBK6weNBBDoP0EEkRm1XCC144XhXZC82jBZohYmi2WvDbbC//YN58kRMYMyy"
+ "srrfn4Z9I+6kTriGXkrpGk9Q0LSGjmG2BIsqiF0dvwAAAAAAAA==");
//
// dsaWithSHA1 cert
//
byte[] cert7 = Base64.decode(
"MIIEXAYJKoZIhvcNAQcCoIIETTCCBEkCAQExCzAJBgUrDgMCGgUAMAsGCSqG"
+ "SIb3DQEHAaCCAsMwggK/MIIB4AIBADCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7"
+ "d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULjw3GobwaJX13kquPh"
+ "fVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABj"
+ "TUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/z"
+ "m8Q12PFp/PjOhh+nMA4xDDAKBgNVBAMTA0lEMzAeFw05NzEwMDEwMDAwMDBa"
+ "Fw0zODAxMDEwMDAwMDBaMA4xDDAKBgNVBAMTA0lEMzCB8DCBpwYFKw4DAhsw"
+ "gZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULj"
+ "w3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FE"
+ "WA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3"
+ "SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nA0QAAkEAkYkXLYMtGVGWj9OnzjPn"
+ "sB9sefSRPrVegZJCZbpW+Iv0/1RP1u04pHG9vtRpIQLjzUiWvLMU9EKQTThc"
+ "eNMmWDCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxg"
+ "Y61TX5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/Q"
+ "F4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jH"
+ "SqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nAy8AMCwC"
+ "FBY3dBSdeprGcqpr6wr3xbG+6WW+AhRMm/facKJNxkT3iKgJbp7R8Xd3QTGC"
+ "AWEwggFdAgEBMBMwDjEMMAoGA1UEAxMDSUQzAgEAMAkGBSsOAwIaBQCgXTAY"
+ "BgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMjA1"
+ "MjQyMzEzMDdaMCMGCSqGSIb3DQEJBDEWBBS4WMsoJhf7CVbZYCFcjoTRzPkJ"
+ "xjCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61T"
+ "X5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BU"
+ "j+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqji"
+ "jUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nBC8wLQIVALID"
+ "dt+MHwawrDrwsO1Z6sXBaaJsAhRaKssrpevmLkbygKPV07XiAKBG02Zvb2Jh"
+ "cg==");
//
// testcrl.pem
//
byte[] crl1 = Base64.decode(
"MIICjTCCAfowDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMxIDAeBgNVBAoT"
+ "F1JTQSBEYXRhIFNlY3VyaXR5LCBJbmMuMS4wLAYDVQQLEyVTZWN1cmUgU2VydmVy"
+ "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5Fw05NTA1MDIwMjEyMjZaFw05NTA2MDEw"
+ "MDAxNDlaMIIBaDAWAgUCQQAABBcNOTUwMjAxMTcyNDI2WjAWAgUCQQAACRcNOTUw"
+ "MjEwMDIxNjM5WjAWAgUCQQAADxcNOTUwMjI0MDAxMjQ5WjAWAgUCQQAADBcNOTUw"
+ "MjI1MDA0NjQ0WjAWAgUCQQAAGxcNOTUwMzEzMTg0MDQ5WjAWAgUCQQAAFhcNOTUw"
+ "MzE1MTkxNjU0WjAWAgUCQQAAGhcNOTUwMzE1MTk0MDQxWjAWAgUCQQAAHxcNOTUw"
+ "MzI0MTk0NDMzWjAWAgUCcgAABRcNOTUwMzI5MjAwNzExWjAWAgUCcgAAERcNOTUw"
+ "MzMwMDIzNDI2WjAWAgUCQQAAIBcNOTUwNDA3MDExMzIxWjAWAgUCcgAAHhcNOTUw"
+ "NDA4MDAwMjU5WjAWAgUCcgAAQRcNOTUwNDI4MTcxNzI0WjAWAgUCcgAAOBcNOTUw"
+ "NDI4MTcyNzIxWjAWAgUCcgAATBcNOTUwNTAyMDIxMjI2WjANBgkqhkiG9w0BAQIF"
+ "AAN+AHqOEJXSDejYy0UwxxrH/9+N2z5xu/if0J6qQmK92W0hW158wpJg+ovV3+wQ"
+ "wvIEPRL2rocL0tKfAsVq1IawSJzSNgxG0lrcla3MrJBnZ4GaZDu4FutZh72MR3Gt"
+ "JaAL3iTJHJD55kK2D/VoyY1djlsPuNh6AEgdVwFAyp0v");
//
// ecdsa cert with extra octet string.
//
byte[] oldEcdsa = Base64.decode(
"MIICljCCAkCgAwIBAgIBATALBgcqhkjOPQQBBQAwgY8xCzAJBgNVBAYTAkFVMSgwJ"
+ "gYDVQQKEx9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIwEAYDVQQHEw"
+ "lNZWxib3VybmUxETAPBgNVBAgTCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWV"
+ "kYmFjay1jcnlwdG9AYm91bmN5Y2FzdGxlLm9yZzAeFw0wMTEyMDcwMTAwMDRaFw0w"
+ "MTEyMDcwMTAxNDRaMIGPMQswCQYDVQQGEwJBVTEoMCYGA1UEChMfVGhlIExlZ2lvb"
+ "iBvZiB0aGUgQm91bmN5IENhc3RsZTESMBAGA1UEBxMJTWVsYm91cm5lMREwDwYDVQ"
+ "QIEwhWaWN0b3JpYTEvMC0GCSqGSIb3DQEJARYgZmVlZGJhY2stY3J5cHRvQGJvdW5"
+ "jeWNhc3RsZS5vcmcwgeQwgb0GByqGSM49AgEwgbECAQEwKQYHKoZIzj0BAQIef///"
+ "////////////f///////gAAAAAAAf///////MEAEHn///////////////3///////"
+ "4AAAAAAAH///////AQeawFsO9zxiUHQ1lSSFHXKcanbL7J9HTd5YYXClCwKBB8CD/"
+ "qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqvAh5///////////////9///+eXpq"
+ "fXZBx+9FSJoiQnQsDIgAEHwJbbcU7xholSP+w9nFHLebJUhqdLSU05lq/y9X+DHAw"
+ "CwYHKoZIzj0EAQUAA0MAMEACHnz6t4UNoVROp74ma4XNDjjGcjaqiIWPZLK8Bdw3G"
+ "QIeLZ4j3a6ividZl344UH+UPUE7xJxlYGuy7ejTsqRR");
byte[] uncompressedPtEC = Base64.decode(
"MIIDKzCCAsGgAwIBAgICA+kwCwYHKoZIzj0EAQUAMGYxCzAJBgNVBAYTAkpQ"
+ "MRUwEwYDVQQKEwxuaXRlY2guYWMuanAxDjAMBgNVBAsTBWFpbGFiMQ8wDQYD"
+ "VQQDEwZ0ZXN0Y2ExHzAdBgkqhkiG9w0BCQEWEHRlc3RjYUBsb2NhbGhvc3Qw"
+ "HhcNMDExMDEzMTE1MzE3WhcNMjAxMjEyMTE1MzE3WjBmMQswCQYDVQQGEwJK"
+ "UDEVMBMGA1UEChMMbml0ZWNoLmFjLmpwMQ4wDAYDVQQLEwVhaWxhYjEPMA0G"
+ "A1UEAxMGdGVzdGNhMR8wHQYJKoZIhvcNAQkBFhB0ZXN0Y2FAbG9jYWxob3N0"
+ "MIIBczCCARsGByqGSM49AgEwggEOAgEBMDMGByqGSM49AQECKEdYWnajFmnZ"
+ "tzrukK2XWdle2v+GsD9l1ZiR6g7ozQDbhFH/bBiMDQcwVAQoJ5EQKrI54/CT"
+ "xOQ2pMsd/fsXD+EX8YREd8bKHWiLz8lIVdD5cBNeVwQoMKSc6HfI7vKZp8Q2"
+ "zWgIFOarx1GQoWJbMcSt188xsl30ncJuJT2OoARRBAqJ4fD+q6hbqgNSjTQ7"
+ "htle1KO3eiaZgcJ8rrnyN8P+5A8+5K+H9aQ/NbBR4Gs7yto5PXIUZEUgodHA"
+ "TZMSAcSq5ZYt4KbnSYaLY0TtH9CqAigEwZ+hglbT21B7ZTzYX2xj0x+qooJD"
+ "hVTLtIPaYJK2HrMPxTw6/zfrAgEPA1IABAnvfFcFDgD/JicwBGn6vR3N8MIn"
+ "mptZf/mnJ1y649uCF60zOgdwIyI7pVSxBFsJ7ohqXEHW0x7LrGVkdSEiipiH"
+ "LYslqh3xrqbAgPbl93GUo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB"
+ "/wQEAwIBxjAdBgNVHQ4EFgQUAEo62Xm9H6DcsE0zUDTza4BRG90wCwYHKoZI"
+ "zj0EAQUAA1cAMFQCKAQsCHHSNOqfJXLgt3bg5+k49hIBGVr/bfG0B9JU3rNt"
+ "Ycl9Y2zfRPUCKAK2ccOQXByAWfsasDu8zKHxkZv7LVDTFjAIffz3HaCQeVhD"
+ "z+fauEg=");
byte[] keyUsage = Base64.decode(
"MIIE7TCCBFagAwIBAgIEOAOR7jANBgkqhkiG9w0BAQQFADCByTELMAkGA1UE"
+ "BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgYDVQQLFD93d3cuZW50"
+ "cnVzdC5uZXQvQ2xpZW50X0NBX0luZm8vQ1BTIGluY29ycC4gYnkgcmVmLiBs"
+ "aW1pdHMgbGlhYi4xJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExp"
+ "bWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENsaWVudCBDZXJ0aWZpY2F0"
+ "aW9uIEF1dGhvcml0eTAeFw05OTEwMTIxOTI0MzBaFw0xOTEwMTIxOTU0MzBa"
+ "MIHJMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxSDBGBgNV"
+ "BAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0FfSW5mby9DUFMgaW5jb3Jw"
+ "LiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UECxMcKGMpIDE5OTkgRW50"
+ "cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5uZXQgQ2xpZW50"
+ "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GL"
+ "ADCBhwKBgQDIOpleMRffrCdvkHvkGf9FozTC28GoT/Bo6oT9n3V5z8GKUZSv"
+ "x1cDR2SerYIbWtp/N3hHuzeYEpbOxhN979IMMFGpOZ5V+Pux5zDeg7K6PvHV"
+ "iTs7hbqqdCz+PzFur5GVbgbUB01LLFZHGARS2g4Qk79jkJvh34zmAqTmT173"
+ "iwIBA6OCAeAwggHcMBEGCWCGSAGG+EIBAQQEAwIABzCCASIGA1UdHwSCARkw"
+ "ggEVMIHkoIHhoIHepIHbMIHYMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50"
+ "cnVzdC5uZXQxSDBGBgNVBAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0Ff"
+ "SW5mby9DUFMgaW5jb3JwLiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UE"
+ "CxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50"
+ "cnVzdC5uZXQgQ2xpZW50IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYD"
+ "VQQDEwRDUkwxMCygKqAohiZodHRwOi8vd3d3LmVudHJ1c3QubmV0L0NSTC9D"
+ "bGllbnQxLmNybDArBgNVHRAEJDAigA8xOTk5MTAxMjE5MjQzMFqBDzIwMTkx"
+ "MDEyMTkyNDMwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUxPucKXuXzUyW"
+ "/O5bs8qZdIuV6kwwHQYDVR0OBBYEFMT7nCl7l81MlvzuW7PKmXSLlepMMAwG"
+ "A1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI"
+ "hvcNAQEEBQADgYEAP66K8ddmAwWePvrqHEa7pFuPeJoSSJn59DXeDDYHAmsQ"
+ "OokUgZwxpnyyQbJq5wcBoUv5nyU7lsqZwz6hURzzwy5E97BnRqqS5TvaHBkU"
+ "ODDV4qIxJS7x7EU47fgGWANzYrAQMY9Av2TgXD7FTx/aEkP/TOYGJqibGapE"
+ "PHayXOw=");
byte[] nameCert = Base64.decode(
"MIIEFjCCA3+gAwIBAgIEdS8BozANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJE"+
"RTERMA8GA1UEChQIREFURVYgZUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRQ0Eg"+
"REFURVYgRDAzIDE6UE4wIhgPMjAwMTA1MTAxMDIyNDhaGA8yMDA0MDUwOTEwMjI0"+
"OFowgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIFAZCYXllcm4xEjAQBgNVBAcUCU7I"+
"dXJuYmVyZzERMA8GA1UEChQIREFURVYgZUcxHTAbBgNVBAUTFDAwMDAwMDAwMDA4"+
"OTU3NDM2MDAxMR4wHAYDVQQDFBVEaWV0bWFyIFNlbmdlbmxlaXRuZXIwgaEwDQYJ"+
"KoZIhvcNAQEBBQADgY8AMIGLAoGBAJLI/LJLKaHoMk8fBECW/od8u5erZi6jI8Ug"+
"C0a/LZyQUO/R20vWJs6GrClQtXB+AtfiBSnyZOSYzOdfDI8yEKPEv8qSuUPpOHps"+
"uNCFdLZF1vavVYGEEWs2+y+uuPmg8q1oPRyRmUZ+x9HrDvCXJraaDfTEd9olmB/Z"+
"AuC/PqpjAgUAwAAAAaOCAcYwggHCMAwGA1UdEwEB/wQCMAAwDwYDVR0PAQH/BAUD"+
"AwdAADAxBgNVHSAEKjAoMCYGBSskCAEBMB0wGwYIKwYBBQUHAgEWD3d3dy56cy5k"+
"YXRldi5kZTApBgNVHREEIjAggR5kaWV0bWFyLnNlbmdlbmxlaXRuZXJAZGF0ZXYu"+
"ZGUwgYQGA1UdIwR9MHuhc6RxMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1"+
"bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0"+
"MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE6CBACm8LkwDgYHAoIG"+
"AQoMAAQDAQEAMEcGA1UdHwRAMD4wPKAUoBKGEHd3dy5jcmwuZGF0ZXYuZGWiJKQi"+
"MCAxCzAJBgNVBAYTAkRFMREwDwYDVQQKFAhEQVRFViBlRzAWBgUrJAgDBAQNMAsT"+
"A0VVUgIBBQIBATAdBgNVHQ4EFgQUfv6xFP0xk7027folhy+ziZvBJiwwLAYIKwYB"+
"BQUHAQEEIDAeMBwGCCsGAQUFBzABhhB3d3cuZGlyLmRhdGV2LmRlMA0GCSqGSIb3"+
"DQEBBQUAA4GBAEOVX6uQxbgtKzdgbTi6YLffMftFr2mmNwch7qzpM5gxcynzgVkg"+
"pnQcDNlm5AIbS6pO8jTCLfCd5TZ5biQksBErqmesIl3QD+VqtB+RNghxectZ3VEs"+
"nCUtcE7tJ8O14qwCb3TxS9dvIUFiVi4DjbxX46TdcTbTaK8/qr6AIf+l");
byte[] probSelfSignedCert = Base64.decode(
"MIICxTCCAi6gAwIBAgIQAQAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQUFADBF"
+ "MScwJQYDVQQKEx4gRElSRUNUSU9OIEdFTkVSQUxFIERFUyBJTVBPVFMxGjAYBgNV"
+ "BAMTESBBQyBNSU5FRkkgQiBURVNUMB4XDTA0MDUwNzEyMDAwMFoXDTE0MDUwNzEy"
+ "MDAwMFowRTEnMCUGA1UEChMeIERJUkVDVElPTiBHRU5FUkFMRSBERVMgSU1QT1RT"
+ "MRowGAYDVQQDExEgQUMgTUlORUZJIEIgVEVTVDCBnzANBgkqhkiG9w0BAQEFAAOB"
+ "jQAwgYkCgYEAveoCUOAukZdcFCs2qJk76vSqEX0ZFzHqQ6faBPZWjwkgUNwZ6m6m"
+ "qWvvyq1cuxhoDvpfC6NXILETawYc6MNwwxsOtVVIjuXlcF17NMejljJafbPximEt"
+ "DQ4LcQeSp4K7FyFlIAMLyt3BQ77emGzU5fjFTvHSUNb3jblx0sV28c0CAwEAAaOB"
+ "tTCBsjAfBgNVHSMEGDAWgBSEJ4bLbvEQY8cYMAFKPFD1/fFXlzAdBgNVHQ4EFgQU"
+ "hCeGy27xEGPHGDABSjxQ9f3xV5cwDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIB"
+ "AQQEAwIBBjA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vYWRvbmlzLnBrNy5jZXJ0"
+ "cGx1cy5uZXQvZGdpLXRlc3QuY3JsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN"
+ "AQEFBQADgYEAmToHJWjd3+4zknfsP09H6uMbolHNGG0zTS2lrLKpzcmkQfjhQpT9"
+ "LUTBvfs1jdjo9fGmQLvOG+Sm51Rbjglb8bcikVI5gLbclOlvqLkm77otjl4U4Z2/"
+ "Y0vP14Aov3Sn3k+17EfReYUZI4liuB95ncobC4e8ZM++LjQcIM0s+Vs=");
byte[] gost34102001base = Base64.decode(
"MIIB1DCCAYECEEjpVKXP6Wn1yVz3VeeDQa8wCgYGKoUDAgIDBQAwbTEfMB0G"
+ "A1UEAwwWR29zdFIzNDEwLTIwMDEgZXhhbXBsZTESMBAGA1UECgwJQ3J5cHRv"
+ "UHJvMQswCQYDVQQGEwJSVTEpMCcGCSqGSIb3DQEJARYaR29zdFIzNDEwLTIw"
+ "MDFAZXhhbXBsZS5jb20wHhcNMDUwMjAzMTUxNjQ2WhcNMTUwMjAzMTUxNjQ2"
+ "WjBtMR8wHQYDVQQDDBZHb3N0UjM0MTAtMjAwMSBleGFtcGxlMRIwEAYDVQQK"
+ "DAlDcnlwdG9Qcm8xCzAJBgNVBAYTAlJVMSkwJwYJKoZIhvcNAQkBFhpHb3N0"
+ "UjM0MTAtMjAwMUBleGFtcGxlLmNvbTBjMBwGBiqFAwICEzASBgcqhQMCAiQA"
+ "BgcqhQMCAh4BA0MABECElWh1YAIaQHUIzROMMYks/eUFA3pDXPRtKw/nTzJ+"
+ "V4/rzBa5lYgD0Jp8ha4P5I3qprt+VsfLsN8PZrzK6hpgMAoGBiqFAwICAwUA"
+ "A0EAHw5dw/aw/OiNvHyOE65kvyo4Hp0sfz3csM6UUkp10VO247ofNJK3tsLb"
+ "HOLjUaqzefrlGb11WpHYrvWFg+FcLA==");
byte[] gost341094base = Base64.decode(
"MIICDzCCAbwCEBcxKsIb0ghYvAQeUjfQdFAwCgYGKoUDAgIEBQAwaTEdMBsG"
+ "A1UEAwwUR29zdFIzNDEwLTk0IGV4YW1wbGUxEjAQBgNVBAoMCUNyeXB0b1By"
+ "bzELMAkGA1UEBhMCUlUxJzAlBgkqhkiG9w0BCQEWGEdvc3RSMzQxMC05NEBl"
+ "eGFtcGxlLmNvbTAeFw0wNTAyMDMxNTE2NTFaFw0xNTAyMDMxNTE2NTFaMGkx"
+ "HTAbBgNVBAMMFEdvc3RSMzQxMC05NCBleGFtcGxlMRIwEAYDVQQKDAlDcnlw"
+ "dG9Qcm8xCzAJBgNVBAYTAlJVMScwJQYJKoZIhvcNAQkBFhhHb3N0UjM0MTAt"
+ "OTRAZXhhbXBsZS5jb20wgaUwHAYGKoUDAgIUMBIGByqFAwICIAIGByqFAwIC"
+ "HgEDgYQABIGAu4Rm4XmeWzTYLIB/E6gZZnFX/oxUJSFHbzALJ3dGmMb7R1W+"
+ "t7Lzk2w5tUI3JoTiDRCKJA4fDEJNKzsRK6i/ZjkyXJSLwaj+G2MS9gklh8x1"
+ "G/TliYoJgmjTXHemD7aQEBON4z58nJHWrA0ILD54wbXCtrcaqCqLRYGTMjJ2"
+ "+nswCgYGKoUDAgIEBQADQQBxKNhOmjgz/i5CEgLOyKyz9pFGkDcaymsWYQWV"
+ "v7CZ0pTM8IzMzkUBW3GHsUjCFpanFZDfg2zuN+3kT+694n9B");
byte[] gost341094A = Base64.decode(
"MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOZGVmYXVsdDM0MTAtOTQx"
+ "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1vbGExDDAKBgNVBAgT"
+ "A01FTDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx"
+ "MzExNTdaFw0wNjAzMjkxMzExNTdaMIGBMRcwFQYDVQQDEw5kZWZhdWx0MzQxMC05NDENMAsGA1UE"
+ "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLW9sYTEMMAoGA1UECBMDTUVMMQsw"
+ "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq"
+ "hQMCAiACBgcqhQMCAh4BA4GEAASBgIQACDLEuxSdRDGgdZxHmy30g/DUYkRxO9Mi/uSHX5NjvZ31"
+ "b7JMEMFqBtyhql1HC5xZfUwZ0aT3UnEFDfFjLP+Bf54gA+LPkQXw4SNNGOj+klnqgKlPvoqMGlwa"
+ "+hLPKbS561WpvB2XSTgbV+pqqXR3j6j30STmybelEV3RdS2Now8wDTALBgNVHQ8EBAMCB4AwCgYG"
+ "KoUDAgIEBQADQQBCFy7xWRXtNVXflKvDs0pBdBuPzjCMeZAXVxK8vUxsxxKu76d9CsvhgIFknFRi"
+ "wWTPiZenvNoJ4R1uzeX+vREm");
byte[] gost341094B = Base64.decode(
"MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOcGFyYW0xLTM0MTAtOTQx"
+ "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNVBAgT"
+ "A01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx"
+ "MzEzNTZaFw0wNjAzMjkxMzEzNTZaMIGBMRcwFQYDVQQDEw5wYXJhbTEtMzQxMC05NDENMAsGA1UE"
+ "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMDTWVsMQsw"
+ "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq"
+ "hQMCAiADBgcqhQMCAh4BA4GEAASBgEa+AAcZmijWs1M9x5Pn9efE8D9ztG1NMoIt0/hNZNqln3+j"
+ "lMZjyqPt+kTLIjtmvz9BRDmIDk6FZz+4LhG2OTL7yGpWfrMxMRr56nxomTN9aLWRqbyWmn3brz9Y"
+ "AUD3ifnwjjIuW7UM84JNlDTOdxx0XRUfLQIPMCXe9cO02Xskow8wDTALBgNVHQ8EBAMCB4AwCgYG"
+ "KoUDAgIEBQADQQBzFcnuYc/639OTW+L5Ecjw9KxGr+dwex7lsS9S1BUgKa3m1d5c+cqI0B2XUFi5"
+ "4iaHHJG0dCyjtQYLJr0OZjRw");
byte[] gost34102001A = Base64.decode(
"MIICCzCCAbigAwIBAgIBATAKBgYqhQMCAgMFADCBhDEaMBgGA1UEAxMRZGVmYXVsdC0zNDEwLTIw"
+ "MDExDTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNV"
+ "BAgTA01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAz"
+ "MjkxMzE4MzFaFw0wNjAzMjkxMzE4MzFaMIGEMRowGAYDVQQDExFkZWZhdWx0LTM0MTAtMjAwMTEN"
+ "MAsGA1UEChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMD"
+ "TWVsMQswCQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MGMwHAYGKoUDAgIT"
+ "MBIGByqFAwICIwEGByqFAwICHgEDQwAEQG/4c+ZWb10IpeHfmR+vKcbpmSOClJioYmCVgnojw0Xn"
+ "ned0KTg7TJreRUc+VX7vca4hLQaZ1o/TxVtfEApK/O6jDzANMAsGA1UdDwQEAwIHgDAKBgYqhQMC"
+ "AgMFAANBAN8y2b6HuIdkD3aWujpfQbS1VIA/7hro4vLgDhjgVmev/PLzFB8oTh3gKhExpDo82IEs"
+ "ZftGNsbbyp1NFg7zda0=");
byte[] gostCA1 = Base64.decode(
"MIIDNDCCAuGgAwIBAgIQZLcKDcWcQopF+jp4p9jylDAKBgYqhQMCAgQFADBm"
+ "MQswCQYDVQQGEwJSVTEPMA0GA1UEBxMGTW9zY293MRcwFQYDVQQKEw5PT08g"
+ "Q3J5cHRvLVBybzEUMBIGA1UECxMLRGV2ZWxvcG1lbnQxFzAVBgNVBAMTDkNQ"
+ "IENTUCBUZXN0IENBMB4XDTAyMDYwOTE1NTIyM1oXDTA5MDYwOTE1NTkyOVow"
+ "ZjELMAkGA1UEBhMCUlUxDzANBgNVBAcTBk1vc2NvdzEXMBUGA1UEChMOT09P"
+ "IENyeXB0by1Qcm8xFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5D"
+ "UCBDU1AgVGVzdCBDQTCBpTAcBgYqhQMCAhQwEgYHKoUDAgIgAgYHKoUDAgIe"
+ "AQOBhAAEgYAYglywKuz1nMc9UiBYOaulKy53jXnrqxZKbCCBSVaJ+aCKbsQm"
+ "glhRFrw6Mwu8Cdeabo/ojmea7UDMZd0U2xhZFRti5EQ7OP6YpqD0alllo7za"
+ "4dZNXdX+/ag6fOORSLFdMpVx5ganU0wHMPk67j+audnCPUj/plbeyccgcdcd"
+ "WaOCASIwggEeMAsGA1UdDwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud"
+ "DgQWBBTe840gTo4zt2twHilw3PD9wJaX0TCBygYDVR0fBIHCMIG/MDygOqA4"
+ "hjYtaHR0cDovL2ZpZXdhbGwvQ2VydEVucm9sbC9DUCUyMENTUCUyMFRlc3Ql"
+ "MjBDQSgzKS5jcmwwRKBCoECGPmh0dHA6Ly93d3cuY3J5cHRvcHJvLnJ1L0Nl"
+ "cnRFbnJvbGwvQ1AlMjBDU1AlMjBUZXN0JTIwQ0EoMykuY3JsMDmgN6A1hjMt"
+ "ZmlsZTovL1xcZmlld2FsbFxDZXJ0RW5yb2xsXENQIENTUCBUZXN0IENBKDMp"
+ "LmNybC8wEgYJKwYBBAGCNxUBBAUCAwMAAzAKBgYqhQMCAgQFAANBAIJi7ni7"
+ "9rwMR5rRGTFftt2k70GbqyUEfkZYOzrgdOoKiB4IIsIstyBX0/ne6GsL9Xan"
+ "G2IN96RB7KrowEHeW+k=");
byte[] gostCA2 = Base64.decode(
"MIIC2DCCAoWgAwIBAgIQe9ZCugm42pRKNcHD8466zTAKBgYqhQMCAgMFADB+"
+ "MRowGAYJKoZIhvcNAQkBFgtzYmFAZGlndC5ydTELMAkGA1UEBhMCUlUxDDAK"
+ "BgNVBAgTA01FTDEUMBIGA1UEBxMLWW9zaGthci1PbGExDTALBgNVBAoTBERp"
+ "Z3QxDzANBgNVBAsTBkNyeXB0bzEPMA0GA1UEAxMGc2JhLUNBMB4XDTA0MDgw"
+ "MzEzMzE1OVoXDTE0MDgwMzEzNDAxMVowfjEaMBgGCSqGSIb3DQEJARYLc2Jh"
+ "QGRpZ3QucnUxCzAJBgNVBAYTAlJVMQwwCgYDVQQIEwNNRUwxFDASBgNVBAcT"
+ "C1lvc2hrYXItT2xhMQ0wCwYDVQQKEwREaWd0MQ8wDQYDVQQLEwZDcnlwdG8x"
+ "DzANBgNVBAMTBnNiYS1DQTBjMBwGBiqFAwICEzASBgcqhQMCAiMBBgcqhQMC"
+ "Ah4BA0MABEDMSy10CuOH+i8QKG2UWA4XmCt6+BFrNTZQtS6bOalyDY8Lz+G7"
+ "HybyipE3PqdTB4OIKAAPsEEeZOCZd2UXGQm5o4HaMIHXMBMGCSsGAQQBgjcU"
+ "AgQGHgQAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud"
+ "DgQWBBRJJl3LcNMxkZI818STfoi3ng1xoDBxBgNVHR8EajBoMDGgL6Athito"
+ "dHRwOi8vc2JhLmRpZ3QubG9jYWwvQ2VydEVucm9sbC9zYmEtQ0EuY3JsMDOg"
+ "MaAvhi1maWxlOi8vXFxzYmEuZGlndC5sb2NhbFxDZXJ0RW5yb2xsXHNiYS1D"
+ "QS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwCgYGKoUDAgIDBQADQQA+BRJHbc/p"
+ "q8EYl6iJqXCuR+ozRmH7hPAP3c4KqYSC38TClCgBloLapx/3/WdatctFJW/L"
+ "mcTovpq088927shE");
byte[] inDirectCrl = Base64.decode(
"MIIdXjCCHMcCAQEwDQYJKoZIhvcNAQEFBQAwdDELMAkGA1UEBhMCREUxHDAaBgNV"
+"BAoUE0RldXRzY2hlIFRlbGVrb20gQUcxFzAVBgNVBAsUDlQtVGVsZVNlYyBUZXN0"
+"MS4wDAYHAoIGAQoHFBMBMTAeBgNVBAMUF1QtVGVsZVNlYyBUZXN0IERJUiA4OlBO"
+"Fw0wNjA4MDQwODQ1MTRaFw0wNjA4MDQxNDQ1MTRaMIIbfzB+AgQvrj/pFw0wMzA3"
+"MjIwNTQxMjhaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+oXDTAzMDcyMjA1NDEyOFowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/5xcNMDQwNDA1MTMxODE3WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/oFw0wNDA0"
+"MDUxMzE4MTdaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+UXDTAzMDExMzExMTgxMVowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/5hcNMDMwMTEzMTExODExWjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/jFw0wMzAx"
+"MTMxMTI2NTZaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+QXDTAzMDExMzExMjY1NlowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/4hcNMDQwNzEzMDc1ODM4WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/eFw0wMzAy"
+"MTcwNjMzMjVaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP98XDTAzMDIxNzA2MzMyNVowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/0xcNMDMwMjE3MDYzMzI1WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/dFw0wMzAx"
+"MTMxMTI4MTRaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP9cXDTAzMDExMzExMjcwN1owZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/2BcNMDMwMTEzMTEyNzA3WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/VFw0wMzA0"
+"MzAxMjI3NTNaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP9YXDTAzMDQzMDEyMjc1M1owZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/xhcNMDMwMjEyMTM0NTQwWjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFUVEMgVGVzdCBDQSAxMTpQTjCBkAIEL64/xRcNMDMw"
+"MjEyMTM0NTQwWjB5MHcGA1UdHQEB/wRtMGukaTBnMQswCQYDVQQGEwJERTEcMBoG"
+"A1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEQMA4GA1UECxQHVGVsZVNlYzEoMAwG"
+"BwKCBgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNTpQTjB+AgQvrj/CFw0w"
+"MzAyMTIxMzA5MTZaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRww"
+"GgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNV"
+"BAMUEVRUQyBUZXN0IENBIDExOlBOMIGQAgQvrj/BFw0wMzAyMTIxMzA4NDBaMHkw"
+"dwYDVR0dAQH/BG0wa6RpMGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2No"
+"ZSBUZWxla29tIEFHMRAwDgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAY"
+"BgNVBAMUEVNpZ0cgVGVzdCBDQSA1OlBOMH4CBC+uP74XDTAzMDIxNzA2MzcyNVow"
+"ZzBlBgNVHR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRz"
+"Y2hlIFRlbGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRVFRDIFRlc3Qg"
+"Q0EgMTE6UE4wgZACBC+uP70XDTAzMDIxNzA2MzcyNVoweTB3BgNVHR0BAf8EbTBr"
+"pGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcx"
+"EDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBU"
+"ZXN0IENBIDU6UE4wgZACBC+uP7AXDTAzMDIxMjEzMDg1OVoweTB3BgNVHR0BAf8E"
+"bTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g"
+"QUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2ln"
+"RyBUZXN0IENBIDU6UE4wgZACBC+uP68XDTAzMDIxNzA2MzcyNVoweTB3BgNVHR0B"
+"Af8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVr"
+"b20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQR"
+"U2lnRyBUZXN0IENBIDU6UE4wfgIEL64/kxcNMDMwNDEwMDUyNjI4WjBnMGUGA1Ud"
+"HQEB/wRbMFmkVzBVMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVs"
+"ZWtvbSBBRzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFUVEMgVGVzdCBDQSAxMTpQ"
+"TjCBkAIEL64/khcNMDMwNDEwMDUyNjI4WjB5MHcGA1UdHQEB/wRtMGukaTBnMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEQMA4GA1UE"
+"CxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0Eg"
+"NTpQTjB+AgQvrj8/Fw0wMzAyMjYxMTA0NDRaMGcwZQYDVR0dAQH/BFswWaRXMFUx"
+"CzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYH"
+"AoIGAQoHFBMBMTAYBgNVBAMUEVRUQyBUZXN0IENBIDExOlBOMIGQAgQvrj8+Fw0w"
+"MzAyMjYxMTA0NDRaMHkwdwYDVR0dAQH/BG0wa6RpMGcxCzAJBgNVBAYTAkRFMRww"
+"GgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYDVQQLFAdUZWxlU2VjMSgw"
+"DAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBDQSA1OlBOMH4CBC+uPs0X"
+"DTAzMDUyMDA1MjczNlowZzBlBgNVHR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUx"
+"HDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgG"
+"A1UEAxQRVFRDIFRlc3QgQ0EgMTE6UE4wgZACBC+uPswXDTAzMDUyMDA1MjczNlow"
+"eTB3BgNVHR0BAf8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRz"
+"Y2hlIFRlbGVrb20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwEx"
+"MBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6UE4wfgIEL64+PBcNMDMwNjE3MTAzNDE2"
+"WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1"
+"dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFUVEMgVGVz"
+"dCBDQSAxMTpQTjCBkAIEL64+OxcNMDMwNjE3MTAzNDE2WjB5MHcGA1UdHQEB/wRt"
+"MGukaTBnMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBB"
+"RzEQMA4GA1UECxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFTaWdH"
+"IFRlc3QgQ0EgNjpQTjCBkAIEL64+OhcNMDMwNjE3MTAzNDE2WjB5MHcGA1UdHQEB"
+"/wRtMGukaTBnMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtv"
+"bSBBRzEQMA4GA1UECxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFT"
+"aWdHIFRlc3QgQ0EgNjpQTjB+AgQvrj45Fw0wMzA2MTcxMzAxMDBaMGcwZQYDVR0d"
+"AQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxl"
+"a29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVRUQyBUZXN0IENBIDExOlBO"
+"MIGQAgQvrj44Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6RpMGcxCzAJ"
+"BgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYDVQQL"
+"FAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBDQSA2"
+"OlBOMIGQAgQvrj43Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6RpMGcx"
+"CzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYD"
+"VQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBD"
+"QSA2OlBOMIGQAgQvrj42Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6Rp"
+"MGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAw"
+"DgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVz"
+"dCBDQSA2OlBOMIGQAgQvrj4zFw0wMzA2MTcxMDM3NDlaMHkwdwYDVR0dAQH/BG0w"
+"a6RpMGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFH"
+"MRAwDgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cg"
+"VGVzdCBDQSA2OlBOMH4CBC+uPjEXDTAzMDYxNzEwNDI1OFowZzBlBgNVHR0BAf8E"
+"WzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g"
+"QUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRVFRDIFRlc3QgQ0EgMTE6UE4wgZAC"
+"BC+uPjAXDTAzMDYxNzEwNDI1OFoweTB3BgNVHR0BAf8EbTBrpGkwZzELMAkGA1UE"
+"BhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNVBAsUB1Rl"
+"bGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6UE4w"
+"gZACBC+uPakXDTAzMTAyMjExMzIyNFoweTB3BgNVHR0BAf8EbTBrpGkwZzELMAkG"
+"A1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNVBAsU"
+"B1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6"
+"UE4wgZACBC+uPLIXDTA1MDMxMTA2NDQyNFoweTB3BgNVHR0BAf8EbTBrpGkwZzEL"
+"MAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNV"
+"BAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENB"
+"IDY6UE4wgZACBC+uPKsXDTA0MDQwMjA3NTQ1M1oweTB3BgNVHR0BAf8EbTBrpGkw"
+"ZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAO"
+"BgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0"
+"IENBIDY6UE4wgZACBC+uOugXDTA1MDEyNzEyMDMyNFoweTB3BgNVHR0BAf8EbTBr"
+"pGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcx"
+"EDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBU"
+"ZXN0IENBIDY6UE4wgZACBC+uOr4XDTA1MDIxNjA3NTcxNloweTB3BgNVHR0BAf8E"
+"bTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g"
+"QUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2ln"
+"RyBUZXN0IENBIDY6UE4wgZACBC+uOqcXDTA1MDMxMDA1NTkzNVoweTB3BgNVHR0B"
+"Af8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVr"
+"b20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQR"
+"U2lnRyBUZXN0IENBIDY6UE4wgZACBC+uOjwXDTA1MDUxMTEwNDk0NloweTB3BgNV"
+"HR0BAf8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UE"
+"AxQRU2lnRyBUZXN0IENBIDY6UE4wgaoCBC+sbdUXDTA1MTExMTEwMDMyMVowgZIw"
+"gY8GA1UdHQEB/wSBhDCBgaR/MH0xCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0"
+"c2NoZSBUZWxla29tIEFHMR8wHQYDVQQLFBZQcm9kdWt0emVudHJ1bSBUZWxlU2Vj"
+"MS8wDAYHAoIGAQoHFBMBMTAfBgNVBAMUGFRlbGVTZWMgUEtTIFNpZ0cgQ0EgMTpQ"
+"TjCBlQIEL64uaBcNMDYwMTIzMTAyNTU1WjB+MHwGA1UdHQEB/wRyMHCkbjBsMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEWMBQGA1UE"
+"CxQNWmVudHJhbGUgQm9ubjEnMAwGBwKCBgEKBxQTATEwFwYDVQQDFBBUVEMgVGVz"
+"dCBDQSA5OlBOMIGVAgQvribHFw0wNjA4MDEwOTQ4NDRaMH4wfAYDVR0dAQH/BHIw"
+"cKRuMGwxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFH"
+"MRYwFAYDVQQLFA1aZW50cmFsZSBCb25uMScwDAYHAoIGAQoHFBMBMTAXBgNVBAMU"
+"EFRUQyBUZXN0IENBIDk6UE6ggZswgZgwCwYDVR0UBAQCAhEMMB8GA1UdIwQYMBaA"
+"FANbyNumDI9545HwlCF26NuOJC45MA8GA1UdHAEB/wQFMAOEAf8wVwYDVR0SBFAw"
+"ToZMbGRhcDovL3Brc2xkYXAudHR0Yy5kZS9vdT1ULVRlbGVTZWMgVGVzdCBESVIg"
+"ODpQTixvPURldXRzY2hlIFRlbGVrb20gQUcsYz1kZTANBgkqhkiG9w0BAQUFAAOB"
+"gQBewL5gLFHpeOWO07Vk3Gg7pRDuAlvaovBH4coCyCWpk5jEhUfFSYEDuaQB7do4"
+"IlJmeTHvkI0PIZWJ7bwQ2PVdipPWDx0NVwS/Cz5jUKiS3BbAmZQZOueiKLFpQq3A"
+"b8aOHA7WHU4078/1lM+bgeu33Ln1CGykEbmSjA/oKPi/JA==");
byte[] directCRL = Base64.decode(
"MIIGXTCCBckCAQEwCgYGKyQDAwECBQAwdDELMAkGA1UEBhMCREUxHDAaBgNVBAoU"
+"E0RldXRzY2hlIFRlbGVrb20gQUcxFzAVBgNVBAsUDlQtVGVsZVNlYyBUZXN0MS4w"
+"DAYHAoIGAQoHFBMBMTAeBgNVBAMUF1QtVGVsZVNlYyBUZXN0IERJUiA4OlBOFw0w"
+"NjA4MDQwODQ1MTRaFw0wNjA4MDQxNDQ1MTRaMIIElTAVAgQvrj/pFw0wMzA3MjIw"
+"NTQxMjhaMBUCBC+uP+oXDTAzMDcyMjA1NDEyOFowFQIEL64/5xcNMDQwNDA1MTMx"
+"ODE3WjAVAgQvrj/oFw0wNDA0MDUxMzE4MTdaMBUCBC+uP+UXDTAzMDExMzExMTgx"
+"MVowFQIEL64/5hcNMDMwMTEzMTExODExWjAVAgQvrj/jFw0wMzAxMTMxMTI2NTZa"
+"MBUCBC+uP+QXDTAzMDExMzExMjY1NlowFQIEL64/4hcNMDQwNzEzMDc1ODM4WjAV"
+"AgQvrj/eFw0wMzAyMTcwNjMzMjVaMBUCBC+uP98XDTAzMDIxNzA2MzMyNVowFQIE"
+"L64/0xcNMDMwMjE3MDYzMzI1WjAVAgQvrj/dFw0wMzAxMTMxMTI4MTRaMBUCBC+u"
+"P9cXDTAzMDExMzExMjcwN1owFQIEL64/2BcNMDMwMTEzMTEyNzA3WjAVAgQvrj/V"
+"Fw0wMzA0MzAxMjI3NTNaMBUCBC+uP9YXDTAzMDQzMDEyMjc1M1owFQIEL64/xhcN"
+"MDMwMjEyMTM0NTQwWjAVAgQvrj/FFw0wMzAyMTIxMzQ1NDBaMBUCBC+uP8IXDTAz"
+"MDIxMjEzMDkxNlowFQIEL64/wRcNMDMwMjEyMTMwODQwWjAVAgQvrj++Fw0wMzAy"
+"MTcwNjM3MjVaMBUCBC+uP70XDTAzMDIxNzA2MzcyNVowFQIEL64/sBcNMDMwMjEy"
+"MTMwODU5WjAVAgQvrj+vFw0wMzAyMTcwNjM3MjVaMBUCBC+uP5MXDTAzMDQxMDA1"
+"MjYyOFowFQIEL64/khcNMDMwNDEwMDUyNjI4WjAVAgQvrj8/Fw0wMzAyMjYxMTA0"
+"NDRaMBUCBC+uPz4XDTAzMDIyNjExMDQ0NFowFQIEL64+zRcNMDMwNTIwMDUyNzM2"
+"WjAVAgQvrj7MFw0wMzA1MjAwNTI3MzZaMBUCBC+uPjwXDTAzMDYxNzEwMzQxNlow"
+"FQIEL64+OxcNMDMwNjE3MTAzNDE2WjAVAgQvrj46Fw0wMzA2MTcxMDM0MTZaMBUC"
+"BC+uPjkXDTAzMDYxNzEzMDEwMFowFQIEL64+OBcNMDMwNjE3MTMwMTAwWjAVAgQv"
+"rj43Fw0wMzA2MTcxMzAxMDBaMBUCBC+uPjYXDTAzMDYxNzEzMDEwMFowFQIEL64+"
+"MxcNMDMwNjE3MTAzNzQ5WjAVAgQvrj4xFw0wMzA2MTcxMDQyNThaMBUCBC+uPjAX"
+"DTAzMDYxNzEwNDI1OFowFQIEL649qRcNMDMxMDIyMTEzMjI0WjAVAgQvrjyyFw0w"
+"NTAzMTEwNjQ0MjRaMBUCBC+uPKsXDTA0MDQwMjA3NTQ1M1owFQIEL6466BcNMDUw"
+"MTI3MTIwMzI0WjAVAgQvrjq+Fw0wNTAyMTYwNzU3MTZaMBUCBC+uOqcXDTA1MDMx"
+"MDA1NTkzNVowFQIEL646PBcNMDUwNTExMTA0OTQ2WjAVAgQvrG3VFw0wNTExMTEx"
+"MDAzMjFaMBUCBC+uLmgXDTA2MDEyMzEwMjU1NVowFQIEL64mxxcNMDYwODAxMDk0"
+"ODQ0WqCBijCBhzALBgNVHRQEBAICEQwwHwYDVR0jBBgwFoAUA1vI26YMj3njkfCU"
+"IXbo244kLjkwVwYDVR0SBFAwToZMbGRhcDovL3Brc2xkYXAudHR0Yy5kZS9vdT1U"
+"LVRlbGVTZWMgVGVzdCBESVIgODpQTixvPURldXRzY2hlIFRlbGVrb20gQUcsYz1k"
+"ZTAKBgYrJAMDAQIFAAOBgQArj4eMlbAwuA2aS5O4UUUHQMKKdK/dtZi60+LJMiMY"
+"ojrMIf4+ZCkgm1Ca0Cd5T15MJxVHhh167Ehn/Hd48pdnAP6Dfz/6LeqkIHGWMHR+"
+"z6TXpwWB+P4BdUec1ztz04LypsznrHcLRa91ixg9TZCb1MrOG+InNhleRs1ImXk8"
+"MQ==");
private PublicKey dudPublicKey = new PublicKey()
{
public String getAlgorithm()
{
return null;
}
public String getFormat()
{
return null;
}
public byte[] getEncoded()
{
return null;
}
};
public String getName()
{
return "CertTest";
}
public void checkCertificate(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
Certificate cert = fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkNameCertificate(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
if (!cert.getIssuerDN().toString().equals("C=DE,O=DATEV eG,0.2.262.1.10.7.20=1+CN=CA DATEV D03 1:PN"))
{
fail(id + " failed - name test.");
}
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkKeyUsage(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
if (cert.getKeyUsage()[7])
{
fail("error generating cert - key usage wrong.");
}
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkSelfSignedCertificate(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
Certificate cert = fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
cert.verify(k);
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
/**
* we generate a self signed certificate for the sake of testing - RSA
*/
public void checkCreation1()
throws Exception
{
//
// a sample key pair.
//
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16));
RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
Vector ord = new Vector();
Vector values = new Vector();
ord.addElement(X509Principal.C);
ord.addElement(X509Principal.O);
ord.addElement(X509Principal.L);
ord.addElement(X509Principal.ST);
ord.addElement(X509Principal.E);
values.addElement("AU");
values.addElement("The Legion of the Bouncy Castle");
values.addElement("Melbourne");
values.addElement("Victoria");
values.addElement("[email protected]");
//
// extensions
//
//
// create the certificate - version 3 - without extensions
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
X509Certificate cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
Set dummySet = cert.getNonCriticalExtensionOIDs();
dummySet = cert.getNonCriticalExtensionOIDs();
//
// create the certificate - version 3 - with extensions
//
certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
certGen.addExtension("2.5.29.15", true,
new X509KeyUsage(X509KeyUsage.encipherOnly));
certGen.addExtension("2.5.29.37", true,
new DERSequence(KeyPurposeId.anyExtendedKeyUsage));
certGen.addExtension("2.5.29.17", true,
new GeneralNames(new GeneralName(GeneralName.rfc822Name, "[email protected]")));
cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream sbIn = new ByteArrayInputStream(cert.getEncoded());
ASN1InputStream sdIn = new ASN1InputStream(sbIn);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
if (!cert.getKeyUsage()[7])
{
fail("error generating cert - key usage wrong.");
}
List l = cert.getExtendedKeyUsage();
if (!l.get(0).equals(KeyPurposeId.anyExtendedKeyUsage.getId()))
{
fail("failed extended key usage test");
}
Collection c = cert.getSubjectAlternativeNames();
Iterator it = c.iterator();
while (it.hasNext())
{
List gn = (List)it.next();
if (!gn.get(1).equals("[email protected]"))
{
fail("failed subject alternative names test");
}
}
// System.out.println(cert);
//
// create the certificate - version 1
//
X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();
certGen1.setSerialNumber(BigInteger.valueOf(1));
certGen1.setIssuerDN(new X509Principal(ord, attrs));
certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen1.setSubjectDN(new X509Principal(ord, values));
certGen1.setPublicKey(pubKey);
certGen1.setSignatureAlgorithm("MD5WithRSAEncryption");
cert = certGen1.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
bIn = new ByteArrayInputStream(cert.getEncoded());
certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
// System.out.println(cert);
if (!cert.getIssuerDN().equals(cert.getSubjectDN()))
{
fail("name comparison fails");
}
}
/**
* we generate a self signed certificate for the sake of testing - DSA
*/
public void checkCreation2()
{
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
try
{
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN");
g.initialize(512, new SecureRandom());
KeyPair p = g.generateKeyPair();
privKey = p.getPrivate();
pubKey = p.getPublic();
}
catch (Exception e)
{
fail("error setting up keys - " + e.toString());
return;
}
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
//
// extensions
//
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA1withDSA");
try
{
X509Certificate cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
// System.out.println(cert);
}
catch (Exception e)
{
fail("error setting generating cert - " + e.toString());
}
//
// create the certificate - version 1
//
X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();
certGen1.setSerialNumber(BigInteger.valueOf(1));
certGen1.setIssuerDN(new X509Principal(attrs));
certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen1.setSubjectDN(new X509Principal(attrs));
certGen1.setPublicKey(pubKey);
certGen1.setSignatureAlgorithm("SHA1withDSA");
try
{
X509Certificate cert = certGen1.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
//System.out.println(cert);
}
catch (Exception e)
{
fail("error setting generating cert - " + e.toString());
}
//
// exception test
//
try
{
certGen.setPublicKey(dudPublicKey);
fail("key without encoding not detected in v1");
}
catch (IllegalArgumentException e)
{
// expected
}
}
/**
* we generate a self signed certificate for the sake of testing - ECDSA
*/
public void checkCreation3()
{
ECCurve curve = new ECCurve.Fp(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECParameterSpec spec = new ECParameterSpec(
curve,
curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n
ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
spec);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
spec);
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
try
{
KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
}
catch (Exception e)
{
fail("error setting up keys - " + e.toString());
return;
}
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
order.addElement(X509Principal.C);
order.addElement(X509Principal.O);
order.addElement(X509Principal.L);
order.addElement(X509Principal.ST);
order.addElement(X509Principal.E);
//
// toString test
//
X509Principal p = new X509Principal(order, attrs);
String s = p.toString();
if (!s.equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,[email protected]"))
{
fail("ordered X509Principal test failed - s = " + s + ".");
}
p = new X509Principal(attrs);
s = p.toString();
//
// we need two of these as the hash code for strings changed...
//
if (!s.equals("O=The Legion of the Bouncy Castle,[email protected],ST=Victoria,L=Melbourne,C=AU") && !s.equals("ST=Victoria,L=Melbourne,C=AU,[email protected],O=The Legion of the Bouncy Castle"))
{
fail("unordered X509Principal test failed.");
}
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(order, attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(order, attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA1withECDSA");
try
{
X509Certificate cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
//
// try with point compression turned off
//
((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
certGen.setPublicKey(pubKey);
cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
bIn = new ByteArrayInputStream(cert.getEncoded());
fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
// System.out.println(cert);
}
catch (Exception e)
{
fail("error setting generating cert - " + e.toString());
}
X509Principal pr = new X509Principal("O=\"The Bouncy Castle, The Legion of\",[email protected],ST=Victoria,L=Melbourne,C=AU");
if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
{
fail("string based X509Principal test failed.");
}
pr = new X509Principal("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU");
if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
{
fail("string based X509Principal test failed.");
}
}
/**
* we generate a self signed certificate for the sake of testing - SHA224withECDSA
*/
private void createECCert(String algorithm, DERObjectIdentifier algOid)
throws Exception
{
ECCurve.Fp curve = new ECCurve.Fp(
new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a
new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b
ECParameterSpec spec = new ECParameterSpec(
curve,
curve.decodePoint(Hex.decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n
ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(
new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
spec);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
spec);
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
order.addElement(X509Principal.C);
order.addElement(X509Principal.O);
order.addElement(X509Principal.L);
order.addElement(X509Principal.ST);
order.addElement(X509Principal.E);
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(order, attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(order, attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm(algorithm);
X509Certificate cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
//
// try with point compression turned off
//
((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
certGen.setPublicKey(pubKey);
cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
bIn = new ByteArrayInputStream(cert.getEncoded());
certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
if (!cert.getSigAlgOID().equals(algOid.toString()))
{
fail("ECDSA oid incorrect.");
}
if (cert.getSigAlgParams() != null)
{
fail("sig parameters present");
}
Signature sig = Signature.getInstance(algorithm, "BC");
sig.initVerify(pubKey);
sig.update(cert.getTBSCertificate());
if (!sig.verify(cert.getSignature()))
{
fail("EC certificate signature not mapped correctly.");
}
// System.out.println(cert);
}
private void checkCRL(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
CRL cert = fact.generateCRL(bIn);
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkCRLCreation1()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
Date now = new Date();
KeyPair pair = kpGen.generateKeyPair();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
crlGen.addCRLEntry(BigInteger.ONE, now, CRLReason.privilegeWithdrawn);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL crl = crlGen.generate(pair.getPrivate(), "BC");
if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA")))
{
fail("failed CRL issuer test");
}
byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (authExt == null)
{
fail("failed to find CRL extension");
}
AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);
X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE);
if (entry == null)
{
fail("failed to find CRL entry");
}
if (!entry.getSerialNumber().equals(BigInteger.ONE))
{
fail("CRL cert serial number does not match");
}
if (!entry.hasExtensions())
{
fail("CRL entry extension not found");
}
byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId());
if (ext != null)
{
DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext);
if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn)
{
fail("CRL entry reasonCode wrong");
}
}
else
{
fail("CRL entry reasonCode not found");
}
}
public void checkCRLCreation2()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
Date now = new Date();
KeyPair pair = kpGen.generateKeyPair();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
Vector extOids = new Vector();
Vector extValues = new Vector();
CRLReason crlReason = new CRLReason(CRLReason.privilegeWithdrawn);
try
{
extOids.addElement(X509Extensions.ReasonCode);
extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded())));
}
catch (IOException e)
{
throw new IllegalArgumentException("error encoding reason: " + e);
}
X509Extensions entryExtensions = new X509Extensions(extOids, extValues);
crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL crl = crlGen.generate(pair.getPrivate(), "BC");
if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA")))
{
fail("failed CRL issuer test");
}
byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (authExt == null)
{
fail("failed to find CRL extension");
}
AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);
X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE);
if (entry == null)
{
fail("failed to find CRL entry");
}
if (!entry.getSerialNumber().equals(BigInteger.ONE))
{
fail("CRL cert serial number does not match");
}
if (!entry.hasExtensions())
{
fail("CRL entry extension not found");
}
byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId());
if (ext != null)
{
DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext);
if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn)
{
fail("CRL entry reasonCode wrong");
}
}
else
{
fail("CRL entry reasonCode not found");
}
}
public void checkCRLCreation3()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
Date now = new Date();
KeyPair pair = kpGen.generateKeyPair();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
Vector extOids = new Vector();
Vector extValues = new Vector();
CRLReason crlReason = new CRLReason(CRLReason.privilegeWithdrawn);
try
{
extOids.addElement(X509Extensions.ReasonCode);
extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded())));
}
catch (IOException e)
{
throw new IllegalArgumentException("error encoding reason: " + e);
}
X509Extensions entryExtensions = new X509Extensions(extOids, extValues);
crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL crl = crlGen.generate(pair.getPrivate(), "BC");
if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA")))
{
fail("failed CRL issuer test");
}
byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (authExt == null)
{
fail("failed to find CRL extension");
}
AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);
X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE);
if (entry == null)
{
fail("failed to find CRL entry");
}
if (!entry.getSerialNumber().equals(BigInteger.ONE))
{
fail("CRL cert serial number does not match");
}
if (!entry.hasExtensions())
{
fail("CRL entry extension not found");
}
byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId());
if (ext != null)
{
DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext);
if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn)
{
fail("CRL entry reasonCode wrong");
}
}
else
{
fail("CRL entry reasonCode not found");
}
//
// check loading of existing CRL
//
crlGen = new X509V2CRLGenerator();
now = new Date();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
crlGen.addCRL(crl);
crlGen.addCRLEntry(BigInteger.valueOf(2), now, entryExtensions);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL newCrl = crlGen.generate(pair.getPrivate(), "BC");
int count = 0;
boolean oneFound = false;
boolean twoFound = false;
Iterator it = newCrl.getRevokedCertificates().iterator();
while (it.hasNext())
{
X509CRLEntry crlEnt = (X509CRLEntry)it.next();
if (crlEnt.getSerialNumber().intValue() == 1)
{
oneFound = true;
}
else if (crlEnt.getSerialNumber().intValue() == 2)
{
twoFound = true;
}
count++;
}
if (count != 2)
{
fail("wrong number of CRLs found");
}
if (!oneFound || !twoFound)
{
fail("wrong CRLs found in copied list");
}
//
// check factory read back
//
CertificateFactory cFact = CertificateFactory.getInstance("X.509", "BC");
X509CRL readCrl = (X509CRL)cFact.generateCRL(new ByteArrayInputStream(newCrl.getEncoded()));
if (readCrl == null)
{
fail("crl not returned!");
}
Collection col = cFact.generateCRLs(new ByteArrayInputStream(newCrl.getEncoded()));
if (col.size() != 1)
{
fail("wrong number of CRLs found in collection");
}
}
/**
* we generate a self signed certificate for the sake of testing - GOST3410
*/
public void checkCreation4()
throws Exception
{
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
KeyPairGenerator g = KeyPairGenerator.getInstance("GOST3410", "BC");
GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A");
g.initialize(gost3410P, new SecureRandom());
KeyPair p = g.generateKeyPair();
privKey = p.getPrivate();
pubKey = p.getPublic();
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
//
// extensions
//
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("GOST3411withGOST3410");
X509Certificate cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
//
// check verifies in general
//
cert.verify(pubKey);
//
// check verifies with contained key
//
cert.verify(cert.getPublicKey());
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
//System.out.println(cert);
//check getEncoded()
byte[] bytesch = cert.getEncoded();
}
public void checkCreation5()
throws Exception
{
//
// a sample key pair.
//
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16));
RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
//
// set up the keys
//
SecureRandom rand = new SecureRandom();
PrivateKey privKey;
PublicKey pubKey;
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
Vector ord = new Vector();
Vector values = new Vector();
ord.addElement(X509Principal.C);
ord.addElement(X509Principal.O);
ord.addElement(X509Principal.L);
ord.addElement(X509Principal.ST);
ord.addElement(X509Principal.E);
values.addElement("AU");
values.addElement("The Legion of the Bouncy Castle");
values.addElement("Melbourne");
values.addElement("Victoria");
values.addElement("[email protected]");
//
// create base certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
certGen.addExtension("2.5.29.15", true,
new X509KeyUsage(X509KeyUsage.encipherOnly));
certGen.addExtension("2.5.29.37", true,
new DERSequence(KeyPurposeId.anyExtendedKeyUsage));
certGen.addExtension("2.5.29.17", true,
new GeneralNames(new GeneralName(GeneralName.rfc822Name, "[email protected]")));
X509Certificate baseCert = certGen.generate(privKey, "BC");
//
// copy certificate
//
certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
certGen.copyAndAddExtension(new DERObjectIdentifier("2.5.29.15"), true, baseCert);
certGen.copyAndAddExtension("2.5.29.37", false, baseCert);
X509Certificate cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
if (!areEqual(baseCert.getExtensionValue("2.5.29.15"), cert.getExtensionValue("2.5.29.15")))
{
fail("2.5.29.15 differs");
}
if (!areEqual(baseCert.getExtensionValue("2.5.29.37"), cert.getExtensionValue("2.5.29.37")))
{
fail("2.5.29.37 differs");
}
//
// exception test
//
try
{
certGen.copyAndAddExtension("2.5.99.99", true, baseCert);
fail("exception not thrown on dud extension copy");
}
catch (CertificateParsingException e)
{
// expected
}
try
{
certGen.setPublicKey(dudPublicKey);
certGen.generate(privKey, "BC");
fail("key without encoding not detected in v3");
}
catch (IllegalArgumentException e)
{
// expected
}
}
private void testForgedSignature()
throws Exception
{
String cert = "MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV"
+ "BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD"
+ "VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU4NTVa"
+ "Fw0wNjEwMTEyMzU4NTVaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs"
+ "YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy"
+ "IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD"
+ "hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u"
+ "12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAbynCRIlUQgaqyNgU"
+ "DF6P14yRKUtX8akOP2TwStaSiVf/akYqfLFm3UGka5XbPj4rifrZ0/sOoZEEBvHQ"
+ "e20sRA==";
CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC");
X509Certificate x509 = (X509Certificate)certFact.generateCertificate(new ByteArrayInputStream(Base64.decode(cert)));
try
{
x509.verify(x509.getPublicKey());
fail("forged RSA signature passed");
}
catch (Exception e)
{
// expected
}
}
private void pemTest()
throws Exception
{
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
Certificate cert = cf.generateCertificate(new ByteArrayInputStream(PEMData.CERTIFICATE_1.getBytes("US-ASCII")));
if (cert == null)
{
fail("PEM cert not read");
}
CRL crl = cf.generateCRL(new ByteArrayInputStream(PEMData.CRL_1.getBytes("US-ASCII")));
if (crl == null)
{
fail("PEM crl not read");
}
Collection col = cf.generateCertificates(new ByteArrayInputStream(PEMData.CERTIFICATE_2.getBytes("US-ASCII")));
if (col.size() != 1 || !col.contains(cert))
{
fail("PEM cert collection not right");
}
col = cf.generateCRLs(new ByteArrayInputStream(PEMData.CRL_2.getBytes("US-ASCII")));
if (col.size() != 1 || !col.contains(crl))
{
fail("PEM crl collection not right");
}
}
private void pkcs7Test()
throws Exception
{
ASN1EncodableVector certs = new ASN1EncodableVector();
certs.add(new ASN1InputStream(CertPathTest.rootCertBin).readObject());
certs.add(new ASN1InputStream(AttrCertTest.attrCert).readObject());
ASN1EncodableVector crls = new ASN1EncodableVector();
crls.add(new ASN1InputStream(CertPathTest.rootCrlBin).readObject());
SignedData sigData = new SignedData(new DERSet(), new ContentInfo(CMSObjectIdentifiers.data, null), new DERSet(certs), new DERSet(crls), new DERSet());
ContentInfo info = new ContentInfo(CMSObjectIdentifiers.signedData, sigData);
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(info.getEncoded()));
if (cert == null || !areEqual(cert.getEncoded(), certs.get(0).getDERObject().getEncoded()))
{
fail("PKCS7 cert not read");
}
X509CRL crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(info.getEncoded()));
if (crl == null || !areEqual(crl.getEncoded(), crls.get(0).getDERObject().getEncoded()))
{
fail("PKCS7 crl not read");
}
Collection col = cf.generateCertificates(new ByteArrayInputStream(info.getEncoded()));
if (col.size() != 1 || !col.contains(cert))
{
fail("PKCS7 cert collection not right");
}
col = cf.generateCRLs(new ByteArrayInputStream(info.getEncoded()));
if (col.size() != 1 || !col.contains(crl))
{
fail("PKCS7 crl collection not right");
}
// data with no certificates or CRLs
sigData = new SignedData(new DERSet(), new ContentInfo(CMSObjectIdentifiers.data, null), new DERSet(), new DERSet(), new DERSet());
info = new ContentInfo(CMSObjectIdentifiers.signedData, sigData);
cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(info.getEncoded()));
if (cert != null)
{
fail("PKCS7 cert present");
}
crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(info.getEncoded()));
if (crl != null)
{
fail("PKCS7 crl present");
}
}
public void performTest()
throws Exception
{
checkCertificate(1, cert1);
checkCertificate(2, cert2);
checkCertificate(4, cert4);
checkCertificate(5, cert5);
checkCertificate(6, oldEcdsa);
checkCertificate(7, cert7);
checkKeyUsage(8, keyUsage);
checkSelfSignedCertificate(9, uncompressedPtEC);
checkNameCertificate(10, nameCert);
checkSelfSignedCertificate(11, probSelfSignedCert);
checkSelfSignedCertificate(12, gostCA1);
checkSelfSignedCertificate(13, gostCA2);
checkSelfSignedCertificate(14, gost341094base);
checkSelfSignedCertificate(15, gost34102001base);
checkSelfSignedCertificate(16, gost341094A);
checkSelfSignedCertificate(17, gost341094B);
checkSelfSignedCertificate(17, gost34102001A);
checkCRL(1, crl1);
checkCreation1();
checkCreation2();
checkCreation3();
checkCreation4();
checkCreation5();
createECCert("SHA1withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1);
createECCert("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
createECCert("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
createECCert("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
createECCert("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
checkCRLCreation1();
checkCRLCreation2();
checkCRLCreation3();
pemTest();
pkcs7Test();
testForgedSignature();
}
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new CertTest());
}
}
| test/src/org/bouncycastle/jce/provider/test/CertTest.java | package org.bouncycastle.jce.provider.test;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.DEREnumerated;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.CRLReason;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.X509KeyUsage;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.interfaces.ECPointEncoder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.jce.spec.GOST3410ParameterSpec;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.SimpleTest;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.bouncycastle.x509.X509V2CRLGenerator;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure;
import org.bouncycastle.x509.extension.X509ExtensionUtil;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.cert.CRL;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509CRL;
import java.security.cert.X509CRLEntry;
import java.security.cert.X509Certificate;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
public class CertTest
extends SimpleTest
{
//
// server.crt
//
byte[] cert1 = Base64.decode(
"MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx"
+ "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY"
+ "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB"
+ "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ"
+ "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU2MjFaFw0wMTA2"
+ "MDIwNzU2MjFaMIG4MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW"
+ "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM"
+ "dGQxFzAVBgNVBAsTDldlYnNlcnZlciBUZWFtMR0wGwYDVQQDExR3d3cyLmNvbm5l"
+ "Y3Q0LmNvbS5hdTEoMCYGCSqGSIb3DQEJARYZd2VibWFzdGVyQGNvbm5lY3Q0LmNv"
+ "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArvDxclKAhyv7Q/Wmr2re"
+ "Gw4XL9Cnh9e+6VgWy2AWNy/MVeXdlxzd7QAuc1eOWQkGQEiLPy5XQtTY+sBUJ3AO"
+ "Rvd2fEVJIcjf29ey7bYua9J/vz5MG2KYo9/WCHIwqD9mmG9g0xLcfwq/s8ZJBswE"
+ "7sb85VU+h94PTvsWOsWuKaECAwEAAaN3MHUwJAYDVR0RBB0wG4EZd2VibWFzdGVy"
+ "QGNvbm5lY3Q0LmNvbS5hdTA6BglghkgBhvhCAQ0ELRYrbW9kX3NzbCBnZW5lcmF0"
+ "ZWQgY3VzdG9tIHNlcnZlciBjZXJ0aWZpY2F0ZTARBglghkgBhvhCAQEEBAMCBkAw"
+ "DQYJKoZIhvcNAQEEBQADgYEAotccfKpwSsIxM1Hae8DR7M/Rw8dg/RqOWx45HNVL"
+ "iBS4/3N/TO195yeQKbfmzbAA2jbPVvIvGgTxPgO1MP4ZgvgRhasaa0qCJCkWvpM4"
+ "yQf33vOiYQbpv4rTwzU8AmRlBG45WdjyNIigGV+oRc61aKCTnLq7zB8N3z1TF/bF"
+ "5/8=");
//
// ca.crt
//
byte[] cert2 = Base64.decode(
"MIIDbDCCAtWgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx"
+ "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY"
+ "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB"
+ "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ"
+ "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU1MzNaFw0wMTA2"
+ "MDIwNzU1MzNaMIG3MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW"
+ "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM"
+ "dGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEVMBMGA1UEAxMMQ29u"
+ "bmVjdCA0IENBMSgwJgYJKoZIhvcNAQkBFhl3ZWJtYXN0ZXJAY29ubmVjdDQuY29t"
+ "LmF1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgs5ptNG6Qv1ZpCDuUNGmv"
+ "rhjqMDPd3ri8JzZNRiiFlBA4e6/ReaO1U8ASewDeQMH6i9R6degFdQRLngbuJP0s"
+ "xcEE+SksEWNvygfzLwV9J/q+TQDyJYK52utb++lS0b48A1KPLwEsyL6kOAgelbur"
+ "ukwxowprKUIV7Knf1ajetQIDAQABo4GFMIGCMCQGA1UdEQQdMBuBGXdlYm1hc3Rl"
+ "ckBjb25uZWN0NC5jb20uYXUwDwYDVR0TBAgwBgEB/wIBADA2BglghkgBhvhCAQ0E"
+ "KRYnbW9kX3NzbCBnZW5lcmF0ZWQgY3VzdG9tIENBIGNlcnRpZmljYXRlMBEGCWCG"
+ "SAGG+EIBAQQEAwICBDANBgkqhkiG9w0BAQQFAAOBgQCsGvfdghH8pPhlwm1r3pQk"
+ "msnLAVIBb01EhbXm2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz"
+ "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ"
+ "DhkaJ8VqOMajkQFma2r9iA==");
//
// testx509.pem
//
byte[] cert3 = Base64.decode(
"MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV"
+ "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz"
+ "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM"
+ "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF"
+ "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO"
+ "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE"
+ "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ"
+ "zl9HYIMxATFyqSiD9jsx");
//
// v3-cert1.pem
//
byte[] cert4 = Base64.decode(
"MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx"
+ "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz"
+ "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw"
+ "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu"
+ "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2"
+ "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp"
+ "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C"
+ "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK"
+ "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x"
+ "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR"
+ "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB"
+ "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21"
+ "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3"
+ "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO");
//
// v3-cert2.pem
//
byte[] cert5 = Base64.decode(
"MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD"
+ "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0"
+ "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu"
+ "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1"
+ "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV"
+ "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx"
+ "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA"
+ "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT"
+ "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ"
+ "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm"
+ "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc"
+ "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz"
+ "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap"
+ "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU=");
//
// pem encoded pkcs7
//
byte[] cert6 = Base64.decode(
"MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIJbzCCAj0w"
+ "ggGmAhEAzbp/VvDf5LxU/iKss3KqVTANBgkqhkiG9w0BAQIFADBfMQswCQYDVQQGEwJVUzEXMBUG"
+ "A1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGljIFByaW1hcnkgQ2Vy"
+ "dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTYwMTI5MDAwMDAwWhcNMjgwODAxMjM1OTU5WjBfMQsw"
+ "CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVi"
+ "bGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0A"
+ "MIGJAoGBAOUZv22jVmEtmUhx9mfeuY3rt56GgAqRDvo4Ja9GiILlc6igmyRdDR/MZW4MsNBWhBiH"
+ "mgabEKFz37RYOWtuwfYV1aioP6oSBo0xrH+wNNePNGeICc0UEeJORVZpH3gCgNrcR5EpuzbJY1zF"
+ "4Ncth3uhtzKwezC6Ki8xqu6jZ9rbAgMBAAEwDQYJKoZIhvcNAQECBQADgYEATD+4i8Zo3+5DMw5d"
+ "6abLB4RNejP/khv0Nq3YlSI2aBFsfELM85wuxAc/FLAPT/+Qknb54rxK6Y/NoIAK98Up8YIiXbix"
+ "3YEjo3slFUYweRb46gVLlH8dwhzI47f0EEA8E8NfH1PoSOSGtHuhNbB7Jbq4046rPzidADQAmPPR"
+ "cZQwggMuMIICl6ADAgECAhEA0nYujRQMPX2yqCVdr+4NdTANBgkqhkiG9w0BAQIFADBfMQswCQYD"
+ "VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGlj"
+ "IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTgwNTEyMDAwMDAwWhcNMDgwNTEy"
+ "MjM1OTU5WjCBzDEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy"
+ "dXN0IE5ldHdvcmsxRjBEBgNVBAsTPXd3dy52ZXJpc2lnbi5jb20vcmVwb3NpdG9yeS9SUEEgSW5j"
+ "b3JwLiBCeSBSZWYuLExJQUIuTFREKGMpOTgxSDBGBgNVBAMTP1ZlcmlTaWduIENsYXNzIDEgQ0Eg"
+ "SW5kaXZpZHVhbCBTdWJzY3JpYmVyLVBlcnNvbmEgTm90IFZhbGlkYXRlZDCBnzANBgkqhkiG9w0B"
+ "AQEFAAOBjQAwgYkCgYEAu1pEigQWu1X9A3qKLZRPFXg2uA1Ksm+cVL+86HcqnbnwaLuV2TFBcHqB"
+ "S7lIE1YtxwjhhEKrwKKSq0RcqkLwgg4C6S/7wju7vsknCl22sDZCM7VuVIhPh0q/Gdr5FegPh7Yc"
+ "48zGmo5/aiSS4/zgZbqnsX7vyds3ashKyAkG5JkCAwEAAaN8MHowEQYJYIZIAYb4QgEBBAQDAgEG"
+ "MEcGA1UdIARAMD4wPAYLYIZIAYb4RQEHAQEwLTArBggrBgEFBQcCARYfd3d3LnZlcmlzaWduLmNv"
+ "bS9yZXBvc2l0b3J5L1JQQTAPBgNVHRMECDAGAQH/AgEAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0B"
+ "AQIFAAOBgQCIuDc73dqUNwCtqp/hgQFxHpJqbS/28Z3TymQ43BuYDAeGW4UVag+5SYWklfEXfWe0"
+ "fy0s3ZpCnsM+tI6q5QsG3vJWKvozx74Z11NMw73I4xe1pElCY+zCphcPXVgaSTyQXFWjZSAA/Rgg"
+ "5V+CprGoksVYasGNAzzrw80FopCubjCCA/gwggNhoAMCAQICEBbbn/1G1zppD6KsP01bwywwDQYJ"
+ "KoZIhvcNAQEEBQAwgcwxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln"
+ "biBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3JlcG9zaXRvcnkvUlBB"
+ "IEluY29ycC4gQnkgUmVmLixMSUFCLkxURChjKTk4MUgwRgYDVQQDEz9WZXJpU2lnbiBDbGFzcyAx"
+ "IENBIEluZGl2aWR1YWwgU3Vic2NyaWJlci1QZXJzb25hIE5vdCBWYWxpZGF0ZWQwHhcNMDAxMDAy"
+ "MDAwMDAwWhcNMDAxMjAxMjM1OTU5WjCCAQcxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYD"
+ "VQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3Jl"
+ "cG9zaXRvcnkvUlBBIEluY29ycC4gYnkgUmVmLixMSUFCLkxURChjKTk4MR4wHAYDVQQLExVQZXJz"
+ "b25hIE5vdCBWYWxpZGF0ZWQxJzAlBgNVBAsTHkRpZ2l0YWwgSUQgQ2xhc3MgMSAtIE1pY3Jvc29m"
+ "dDETMBEGA1UEAxQKRGF2aWQgUnlhbjElMCMGCSqGSIb3DQEJARYWZGF2aWRAbGl2ZW1lZGlhLmNv"
+ "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqxBsdeNmSvFqhMNwhQgNzM8mdjX9eSXb"
+ "DawpHtQHjmh0AKJSa3IwUY0VIsyZHuXWktO/CgaMBVPt6OVf/n0R2sQigMP6Y+PhEiS0vCJBL9aK"
+ "0+pOo2qXrjVBmq+XuCyPTnc+BOSrU26tJsX0P9BYorwySiEGxGanBNATdVL4NdUCAwEAAaOBnDCB"
+ "mTAJBgNVHRMEAjAAMEQGA1UdIAQ9MDswOQYLYIZIAYb4RQEHAQgwKjAoBggrBgEFBQcCARYcaHR0"
+ "cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTARBglghkgBhvhCAQEEBAMCB4AwMwYDVR0fBCwwKjAo"
+ "oCagJIYiaHR0cDovL2NybC52ZXJpc2lnbi5jb20vY2xhc3MxLmNybDANBgkqhkiG9w0BAQQFAAOB"
+ "gQBC8yIIdVGpFTf8/YiL14cMzcmL0nIRm4kGR3U59z7UtcXlfNXXJ8MyaeI/BnXwG/gD5OKYqW6R"
+ "yca9vZOxf1uoTBl82gInk865ED3Tej6msCqFzZffnSUQvOIeqLxxDlqYRQ6PmW2nAnZeyjcnbI5Y"
+ "syQSM2fmo7n6qJFP+GbFezGCAkUwggJBAgEBMIHhMIHMMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j"
+ "LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazFGMEQGA1UECxM9d3d3LnZlcmlzaWdu"
+ "LmNvbS9yZXBvc2l0b3J5L1JQQSBJbmNvcnAuIEJ5IFJlZi4sTElBQi5MVEQoYyk5ODFIMEYGA1UE"
+ "AxM/VmVyaVNpZ24gQ2xhc3MgMSBDQSBJbmRpdmlkdWFsIFN1YnNjcmliZXItUGVyc29uYSBOb3Qg"
+ "VmFsaWRhdGVkAhAW25/9Rtc6aQ+irD9NW8MsMAkGBSsOAwIaBQCggbowGAYJKoZIhvcNAQkDMQsG"
+ "CSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDAxMDAyMTczNTE4WjAjBgkqhkiG9w0BCQQxFgQU"
+ "gZjSaBEY2oxGvlQUIMnxSXhivK8wWwYJKoZIhvcNAQkPMU4wTDAKBggqhkiG9w0DBzAOBggqhkiG"
+ "9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwBwYFKw4DAh0w"
+ "DQYJKoZIhvcNAQEBBQAEgYAzk+PU91/ZFfoiuKOECjxEh9fDYE2jfDCheBIgh5gdcCo+sS1WQs8O"
+ "HreQ9Nop/JdJv1DQMBK6weNBBDoP0EEkRm1XCC144XhXZC82jBZohYmi2WvDbbC//YN58kRMYMyy"
+ "srrfn4Z9I+6kTriGXkrpGk9Q0LSGjmG2BIsqiF0dvwAAAAAAAA==");
//
// dsaWithSHA1 cert
//
byte[] cert7 = Base64.decode(
"MIIEXAYJKoZIhvcNAQcCoIIETTCCBEkCAQExCzAJBgUrDgMCGgUAMAsGCSqG"
+ "SIb3DQEHAaCCAsMwggK/MIIB4AIBADCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7"
+ "d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULjw3GobwaJX13kquPh"
+ "fVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABj"
+ "TUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/z"
+ "m8Q12PFp/PjOhh+nMA4xDDAKBgNVBAMTA0lEMzAeFw05NzEwMDEwMDAwMDBa"
+ "Fw0zODAxMDEwMDAwMDBaMA4xDDAKBgNVBAMTA0lEMzCB8DCBpwYFKw4DAhsw"
+ "gZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULj"
+ "w3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FE"
+ "WA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3"
+ "SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nA0QAAkEAkYkXLYMtGVGWj9OnzjPn"
+ "sB9sefSRPrVegZJCZbpW+Iv0/1RP1u04pHG9vtRpIQLjzUiWvLMU9EKQTThc"
+ "eNMmWDCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxg"
+ "Y61TX5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/Q"
+ "F4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jH"
+ "SqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nAy8AMCwC"
+ "FBY3dBSdeprGcqpr6wr3xbG+6WW+AhRMm/facKJNxkT3iKgJbp7R8Xd3QTGC"
+ "AWEwggFdAgEBMBMwDjEMMAoGA1UEAxMDSUQzAgEAMAkGBSsOAwIaBQCgXTAY"
+ "BgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMjA1"
+ "MjQyMzEzMDdaMCMGCSqGSIb3DQEJBDEWBBS4WMsoJhf7CVbZYCFcjoTRzPkJ"
+ "xjCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61T"
+ "X5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BU"
+ "j+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqji"
+ "jUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nBC8wLQIVALID"
+ "dt+MHwawrDrwsO1Z6sXBaaJsAhRaKssrpevmLkbygKPV07XiAKBG02Zvb2Jh"
+ "cg==");
//
// testcrl.pem
//
byte[] crl1 = Base64.decode(
"MIICjTCCAfowDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMxIDAeBgNVBAoT"
+ "F1JTQSBEYXRhIFNlY3VyaXR5LCBJbmMuMS4wLAYDVQQLEyVTZWN1cmUgU2VydmVy"
+ "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5Fw05NTA1MDIwMjEyMjZaFw05NTA2MDEw"
+ "MDAxNDlaMIIBaDAWAgUCQQAABBcNOTUwMjAxMTcyNDI2WjAWAgUCQQAACRcNOTUw"
+ "MjEwMDIxNjM5WjAWAgUCQQAADxcNOTUwMjI0MDAxMjQ5WjAWAgUCQQAADBcNOTUw"
+ "MjI1MDA0NjQ0WjAWAgUCQQAAGxcNOTUwMzEzMTg0MDQ5WjAWAgUCQQAAFhcNOTUw"
+ "MzE1MTkxNjU0WjAWAgUCQQAAGhcNOTUwMzE1MTk0MDQxWjAWAgUCQQAAHxcNOTUw"
+ "MzI0MTk0NDMzWjAWAgUCcgAABRcNOTUwMzI5MjAwNzExWjAWAgUCcgAAERcNOTUw"
+ "MzMwMDIzNDI2WjAWAgUCQQAAIBcNOTUwNDA3MDExMzIxWjAWAgUCcgAAHhcNOTUw"
+ "NDA4MDAwMjU5WjAWAgUCcgAAQRcNOTUwNDI4MTcxNzI0WjAWAgUCcgAAOBcNOTUw"
+ "NDI4MTcyNzIxWjAWAgUCcgAATBcNOTUwNTAyMDIxMjI2WjANBgkqhkiG9w0BAQIF"
+ "AAN+AHqOEJXSDejYy0UwxxrH/9+N2z5xu/if0J6qQmK92W0hW158wpJg+ovV3+wQ"
+ "wvIEPRL2rocL0tKfAsVq1IawSJzSNgxG0lrcla3MrJBnZ4GaZDu4FutZh72MR3Gt"
+ "JaAL3iTJHJD55kK2D/VoyY1djlsPuNh6AEgdVwFAyp0v");
//
// ecdsa cert with extra octet string.
//
byte[] oldEcdsa = Base64.decode(
"MIICljCCAkCgAwIBAgIBATALBgcqhkjOPQQBBQAwgY8xCzAJBgNVBAYTAkFVMSgwJ"
+ "gYDVQQKEx9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIwEAYDVQQHEw"
+ "lNZWxib3VybmUxETAPBgNVBAgTCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWV"
+ "kYmFjay1jcnlwdG9AYm91bmN5Y2FzdGxlLm9yZzAeFw0wMTEyMDcwMTAwMDRaFw0w"
+ "MTEyMDcwMTAxNDRaMIGPMQswCQYDVQQGEwJBVTEoMCYGA1UEChMfVGhlIExlZ2lvb"
+ "iBvZiB0aGUgQm91bmN5IENhc3RsZTESMBAGA1UEBxMJTWVsYm91cm5lMREwDwYDVQ"
+ "QIEwhWaWN0b3JpYTEvMC0GCSqGSIb3DQEJARYgZmVlZGJhY2stY3J5cHRvQGJvdW5"
+ "jeWNhc3RsZS5vcmcwgeQwgb0GByqGSM49AgEwgbECAQEwKQYHKoZIzj0BAQIef///"
+ "////////////f///////gAAAAAAAf///////MEAEHn///////////////3///////"
+ "4AAAAAAAH///////AQeawFsO9zxiUHQ1lSSFHXKcanbL7J9HTd5YYXClCwKBB8CD/"
+ "qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqvAh5///////////////9///+eXpq"
+ "fXZBx+9FSJoiQnQsDIgAEHwJbbcU7xholSP+w9nFHLebJUhqdLSU05lq/y9X+DHAw"
+ "CwYHKoZIzj0EAQUAA0MAMEACHnz6t4UNoVROp74ma4XNDjjGcjaqiIWPZLK8Bdw3G"
+ "QIeLZ4j3a6ividZl344UH+UPUE7xJxlYGuy7ejTsqRR");
byte[] uncompressedPtEC = Base64.decode(
"MIIDKzCCAsGgAwIBAgICA+kwCwYHKoZIzj0EAQUAMGYxCzAJBgNVBAYTAkpQ"
+ "MRUwEwYDVQQKEwxuaXRlY2guYWMuanAxDjAMBgNVBAsTBWFpbGFiMQ8wDQYD"
+ "VQQDEwZ0ZXN0Y2ExHzAdBgkqhkiG9w0BCQEWEHRlc3RjYUBsb2NhbGhvc3Qw"
+ "HhcNMDExMDEzMTE1MzE3WhcNMjAxMjEyMTE1MzE3WjBmMQswCQYDVQQGEwJK"
+ "UDEVMBMGA1UEChMMbml0ZWNoLmFjLmpwMQ4wDAYDVQQLEwVhaWxhYjEPMA0G"
+ "A1UEAxMGdGVzdGNhMR8wHQYJKoZIhvcNAQkBFhB0ZXN0Y2FAbG9jYWxob3N0"
+ "MIIBczCCARsGByqGSM49AgEwggEOAgEBMDMGByqGSM49AQECKEdYWnajFmnZ"
+ "tzrukK2XWdle2v+GsD9l1ZiR6g7ozQDbhFH/bBiMDQcwVAQoJ5EQKrI54/CT"
+ "xOQ2pMsd/fsXD+EX8YREd8bKHWiLz8lIVdD5cBNeVwQoMKSc6HfI7vKZp8Q2"
+ "zWgIFOarx1GQoWJbMcSt188xsl30ncJuJT2OoARRBAqJ4fD+q6hbqgNSjTQ7"
+ "htle1KO3eiaZgcJ8rrnyN8P+5A8+5K+H9aQ/NbBR4Gs7yto5PXIUZEUgodHA"
+ "TZMSAcSq5ZYt4KbnSYaLY0TtH9CqAigEwZ+hglbT21B7ZTzYX2xj0x+qooJD"
+ "hVTLtIPaYJK2HrMPxTw6/zfrAgEPA1IABAnvfFcFDgD/JicwBGn6vR3N8MIn"
+ "mptZf/mnJ1y649uCF60zOgdwIyI7pVSxBFsJ7ohqXEHW0x7LrGVkdSEiipiH"
+ "LYslqh3xrqbAgPbl93GUo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB"
+ "/wQEAwIBxjAdBgNVHQ4EFgQUAEo62Xm9H6DcsE0zUDTza4BRG90wCwYHKoZI"
+ "zj0EAQUAA1cAMFQCKAQsCHHSNOqfJXLgt3bg5+k49hIBGVr/bfG0B9JU3rNt"
+ "Ycl9Y2zfRPUCKAK2ccOQXByAWfsasDu8zKHxkZv7LVDTFjAIffz3HaCQeVhD"
+ "z+fauEg=");
byte[] keyUsage = Base64.decode(
"MIIE7TCCBFagAwIBAgIEOAOR7jANBgkqhkiG9w0BAQQFADCByTELMAkGA1UE"
+ "BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgYDVQQLFD93d3cuZW50"
+ "cnVzdC5uZXQvQ2xpZW50X0NBX0luZm8vQ1BTIGluY29ycC4gYnkgcmVmLiBs"
+ "aW1pdHMgbGlhYi4xJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExp"
+ "bWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENsaWVudCBDZXJ0aWZpY2F0"
+ "aW9uIEF1dGhvcml0eTAeFw05OTEwMTIxOTI0MzBaFw0xOTEwMTIxOTU0MzBa"
+ "MIHJMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxSDBGBgNV"
+ "BAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0FfSW5mby9DUFMgaW5jb3Jw"
+ "LiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UECxMcKGMpIDE5OTkgRW50"
+ "cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5uZXQgQ2xpZW50"
+ "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GL"
+ "ADCBhwKBgQDIOpleMRffrCdvkHvkGf9FozTC28GoT/Bo6oT9n3V5z8GKUZSv"
+ "x1cDR2SerYIbWtp/N3hHuzeYEpbOxhN979IMMFGpOZ5V+Pux5zDeg7K6PvHV"
+ "iTs7hbqqdCz+PzFur5GVbgbUB01LLFZHGARS2g4Qk79jkJvh34zmAqTmT173"
+ "iwIBA6OCAeAwggHcMBEGCWCGSAGG+EIBAQQEAwIABzCCASIGA1UdHwSCARkw"
+ "ggEVMIHkoIHhoIHepIHbMIHYMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50"
+ "cnVzdC5uZXQxSDBGBgNVBAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0Ff"
+ "SW5mby9DUFMgaW5jb3JwLiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UE"
+ "CxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50"
+ "cnVzdC5uZXQgQ2xpZW50IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYD"
+ "VQQDEwRDUkwxMCygKqAohiZodHRwOi8vd3d3LmVudHJ1c3QubmV0L0NSTC9D"
+ "bGllbnQxLmNybDArBgNVHRAEJDAigA8xOTk5MTAxMjE5MjQzMFqBDzIwMTkx"
+ "MDEyMTkyNDMwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUxPucKXuXzUyW"
+ "/O5bs8qZdIuV6kwwHQYDVR0OBBYEFMT7nCl7l81MlvzuW7PKmXSLlepMMAwG"
+ "A1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI"
+ "hvcNAQEEBQADgYEAP66K8ddmAwWePvrqHEa7pFuPeJoSSJn59DXeDDYHAmsQ"
+ "OokUgZwxpnyyQbJq5wcBoUv5nyU7lsqZwz6hURzzwy5E97BnRqqS5TvaHBkU"
+ "ODDV4qIxJS7x7EU47fgGWANzYrAQMY9Av2TgXD7FTx/aEkP/TOYGJqibGapE"
+ "PHayXOw=");
byte[] nameCert = Base64.decode(
"MIIEFjCCA3+gAwIBAgIEdS8BozANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJE"+
"RTERMA8GA1UEChQIREFURVYgZUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRQ0Eg"+
"REFURVYgRDAzIDE6UE4wIhgPMjAwMTA1MTAxMDIyNDhaGA8yMDA0MDUwOTEwMjI0"+
"OFowgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIFAZCYXllcm4xEjAQBgNVBAcUCU7I"+
"dXJuYmVyZzERMA8GA1UEChQIREFURVYgZUcxHTAbBgNVBAUTFDAwMDAwMDAwMDA4"+
"OTU3NDM2MDAxMR4wHAYDVQQDFBVEaWV0bWFyIFNlbmdlbmxlaXRuZXIwgaEwDQYJ"+
"KoZIhvcNAQEBBQADgY8AMIGLAoGBAJLI/LJLKaHoMk8fBECW/od8u5erZi6jI8Ug"+
"C0a/LZyQUO/R20vWJs6GrClQtXB+AtfiBSnyZOSYzOdfDI8yEKPEv8qSuUPpOHps"+
"uNCFdLZF1vavVYGEEWs2+y+uuPmg8q1oPRyRmUZ+x9HrDvCXJraaDfTEd9olmB/Z"+
"AuC/PqpjAgUAwAAAAaOCAcYwggHCMAwGA1UdEwEB/wQCMAAwDwYDVR0PAQH/BAUD"+
"AwdAADAxBgNVHSAEKjAoMCYGBSskCAEBMB0wGwYIKwYBBQUHAgEWD3d3dy56cy5k"+
"YXRldi5kZTApBgNVHREEIjAggR5kaWV0bWFyLnNlbmdlbmxlaXRuZXJAZGF0ZXYu"+
"ZGUwgYQGA1UdIwR9MHuhc6RxMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1"+
"bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0"+
"MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE6CBACm8LkwDgYHAoIG"+
"AQoMAAQDAQEAMEcGA1UdHwRAMD4wPKAUoBKGEHd3dy5jcmwuZGF0ZXYuZGWiJKQi"+
"MCAxCzAJBgNVBAYTAkRFMREwDwYDVQQKFAhEQVRFViBlRzAWBgUrJAgDBAQNMAsT"+
"A0VVUgIBBQIBATAdBgNVHQ4EFgQUfv6xFP0xk7027folhy+ziZvBJiwwLAYIKwYB"+
"BQUHAQEEIDAeMBwGCCsGAQUFBzABhhB3d3cuZGlyLmRhdGV2LmRlMA0GCSqGSIb3"+
"DQEBBQUAA4GBAEOVX6uQxbgtKzdgbTi6YLffMftFr2mmNwch7qzpM5gxcynzgVkg"+
"pnQcDNlm5AIbS6pO8jTCLfCd5TZ5biQksBErqmesIl3QD+VqtB+RNghxectZ3VEs"+
"nCUtcE7tJ8O14qwCb3TxS9dvIUFiVi4DjbxX46TdcTbTaK8/qr6AIf+l");
byte[] probSelfSignedCert = Base64.decode(
"MIICxTCCAi6gAwIBAgIQAQAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQUFADBF"
+ "MScwJQYDVQQKEx4gRElSRUNUSU9OIEdFTkVSQUxFIERFUyBJTVBPVFMxGjAYBgNV"
+ "BAMTESBBQyBNSU5FRkkgQiBURVNUMB4XDTA0MDUwNzEyMDAwMFoXDTE0MDUwNzEy"
+ "MDAwMFowRTEnMCUGA1UEChMeIERJUkVDVElPTiBHRU5FUkFMRSBERVMgSU1QT1RT"
+ "MRowGAYDVQQDExEgQUMgTUlORUZJIEIgVEVTVDCBnzANBgkqhkiG9w0BAQEFAAOB"
+ "jQAwgYkCgYEAveoCUOAukZdcFCs2qJk76vSqEX0ZFzHqQ6faBPZWjwkgUNwZ6m6m"
+ "qWvvyq1cuxhoDvpfC6NXILETawYc6MNwwxsOtVVIjuXlcF17NMejljJafbPximEt"
+ "DQ4LcQeSp4K7FyFlIAMLyt3BQ77emGzU5fjFTvHSUNb3jblx0sV28c0CAwEAAaOB"
+ "tTCBsjAfBgNVHSMEGDAWgBSEJ4bLbvEQY8cYMAFKPFD1/fFXlzAdBgNVHQ4EFgQU"
+ "hCeGy27xEGPHGDABSjxQ9f3xV5cwDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIB"
+ "AQQEAwIBBjA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vYWRvbmlzLnBrNy5jZXJ0"
+ "cGx1cy5uZXQvZGdpLXRlc3QuY3JsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN"
+ "AQEFBQADgYEAmToHJWjd3+4zknfsP09H6uMbolHNGG0zTS2lrLKpzcmkQfjhQpT9"
+ "LUTBvfs1jdjo9fGmQLvOG+Sm51Rbjglb8bcikVI5gLbclOlvqLkm77otjl4U4Z2/"
+ "Y0vP14Aov3Sn3k+17EfReYUZI4liuB95ncobC4e8ZM++LjQcIM0s+Vs=");
byte[] gost34102001base = Base64.decode(
"MIIB1DCCAYECEEjpVKXP6Wn1yVz3VeeDQa8wCgYGKoUDAgIDBQAwbTEfMB0G"
+ "A1UEAwwWR29zdFIzNDEwLTIwMDEgZXhhbXBsZTESMBAGA1UECgwJQ3J5cHRv"
+ "UHJvMQswCQYDVQQGEwJSVTEpMCcGCSqGSIb3DQEJARYaR29zdFIzNDEwLTIw"
+ "MDFAZXhhbXBsZS5jb20wHhcNMDUwMjAzMTUxNjQ2WhcNMTUwMjAzMTUxNjQ2"
+ "WjBtMR8wHQYDVQQDDBZHb3N0UjM0MTAtMjAwMSBleGFtcGxlMRIwEAYDVQQK"
+ "DAlDcnlwdG9Qcm8xCzAJBgNVBAYTAlJVMSkwJwYJKoZIhvcNAQkBFhpHb3N0"
+ "UjM0MTAtMjAwMUBleGFtcGxlLmNvbTBjMBwGBiqFAwICEzASBgcqhQMCAiQA"
+ "BgcqhQMCAh4BA0MABECElWh1YAIaQHUIzROMMYks/eUFA3pDXPRtKw/nTzJ+"
+ "V4/rzBa5lYgD0Jp8ha4P5I3qprt+VsfLsN8PZrzK6hpgMAoGBiqFAwICAwUA"
+ "A0EAHw5dw/aw/OiNvHyOE65kvyo4Hp0sfz3csM6UUkp10VO247ofNJK3tsLb"
+ "HOLjUaqzefrlGb11WpHYrvWFg+FcLA==");
byte[] gost341094base = Base64.decode(
"MIICDzCCAbwCEBcxKsIb0ghYvAQeUjfQdFAwCgYGKoUDAgIEBQAwaTEdMBsG"
+ "A1UEAwwUR29zdFIzNDEwLTk0IGV4YW1wbGUxEjAQBgNVBAoMCUNyeXB0b1By"
+ "bzELMAkGA1UEBhMCUlUxJzAlBgkqhkiG9w0BCQEWGEdvc3RSMzQxMC05NEBl"
+ "eGFtcGxlLmNvbTAeFw0wNTAyMDMxNTE2NTFaFw0xNTAyMDMxNTE2NTFaMGkx"
+ "HTAbBgNVBAMMFEdvc3RSMzQxMC05NCBleGFtcGxlMRIwEAYDVQQKDAlDcnlw"
+ "dG9Qcm8xCzAJBgNVBAYTAlJVMScwJQYJKoZIhvcNAQkBFhhHb3N0UjM0MTAt"
+ "OTRAZXhhbXBsZS5jb20wgaUwHAYGKoUDAgIUMBIGByqFAwICIAIGByqFAwIC"
+ "HgEDgYQABIGAu4Rm4XmeWzTYLIB/E6gZZnFX/oxUJSFHbzALJ3dGmMb7R1W+"
+ "t7Lzk2w5tUI3JoTiDRCKJA4fDEJNKzsRK6i/ZjkyXJSLwaj+G2MS9gklh8x1"
+ "G/TliYoJgmjTXHemD7aQEBON4z58nJHWrA0ILD54wbXCtrcaqCqLRYGTMjJ2"
+ "+nswCgYGKoUDAgIEBQADQQBxKNhOmjgz/i5CEgLOyKyz9pFGkDcaymsWYQWV"
+ "v7CZ0pTM8IzMzkUBW3GHsUjCFpanFZDfg2zuN+3kT+694n9B");
byte[] gost341094A = Base64.decode(
"MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOZGVmYXVsdDM0MTAtOTQx"
+ "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1vbGExDDAKBgNVBAgT"
+ "A01FTDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx"
+ "MzExNTdaFw0wNjAzMjkxMzExNTdaMIGBMRcwFQYDVQQDEw5kZWZhdWx0MzQxMC05NDENMAsGA1UE"
+ "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLW9sYTEMMAoGA1UECBMDTUVMMQsw"
+ "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq"
+ "hQMCAiACBgcqhQMCAh4BA4GEAASBgIQACDLEuxSdRDGgdZxHmy30g/DUYkRxO9Mi/uSHX5NjvZ31"
+ "b7JMEMFqBtyhql1HC5xZfUwZ0aT3UnEFDfFjLP+Bf54gA+LPkQXw4SNNGOj+klnqgKlPvoqMGlwa"
+ "+hLPKbS561WpvB2XSTgbV+pqqXR3j6j30STmybelEV3RdS2Now8wDTALBgNVHQ8EBAMCB4AwCgYG"
+ "KoUDAgIEBQADQQBCFy7xWRXtNVXflKvDs0pBdBuPzjCMeZAXVxK8vUxsxxKu76d9CsvhgIFknFRi"
+ "wWTPiZenvNoJ4R1uzeX+vREm");
byte[] gost341094B = Base64.decode(
"MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOcGFyYW0xLTM0MTAtOTQx"
+ "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNVBAgT"
+ "A01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx"
+ "MzEzNTZaFw0wNjAzMjkxMzEzNTZaMIGBMRcwFQYDVQQDEw5wYXJhbTEtMzQxMC05NDENMAsGA1UE"
+ "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMDTWVsMQsw"
+ "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq"
+ "hQMCAiADBgcqhQMCAh4BA4GEAASBgEa+AAcZmijWs1M9x5Pn9efE8D9ztG1NMoIt0/hNZNqln3+j"
+ "lMZjyqPt+kTLIjtmvz9BRDmIDk6FZz+4LhG2OTL7yGpWfrMxMRr56nxomTN9aLWRqbyWmn3brz9Y"
+ "AUD3ifnwjjIuW7UM84JNlDTOdxx0XRUfLQIPMCXe9cO02Xskow8wDTALBgNVHQ8EBAMCB4AwCgYG"
+ "KoUDAgIEBQADQQBzFcnuYc/639OTW+L5Ecjw9KxGr+dwex7lsS9S1BUgKa3m1d5c+cqI0B2XUFi5"
+ "4iaHHJG0dCyjtQYLJr0OZjRw");
byte[] gost34102001A = Base64.decode(
"MIICCzCCAbigAwIBAgIBATAKBgYqhQMCAgMFADCBhDEaMBgGA1UEAxMRZGVmYXVsdC0zNDEwLTIw"
+ "MDExDTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNV"
+ "BAgTA01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAz"
+ "MjkxMzE4MzFaFw0wNjAzMjkxMzE4MzFaMIGEMRowGAYDVQQDExFkZWZhdWx0LTM0MTAtMjAwMTEN"
+ "MAsGA1UEChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMD"
+ "TWVsMQswCQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MGMwHAYGKoUDAgIT"
+ "MBIGByqFAwICIwEGByqFAwICHgEDQwAEQG/4c+ZWb10IpeHfmR+vKcbpmSOClJioYmCVgnojw0Xn"
+ "ned0KTg7TJreRUc+VX7vca4hLQaZ1o/TxVtfEApK/O6jDzANMAsGA1UdDwQEAwIHgDAKBgYqhQMC"
+ "AgMFAANBAN8y2b6HuIdkD3aWujpfQbS1VIA/7hro4vLgDhjgVmev/PLzFB8oTh3gKhExpDo82IEs"
+ "ZftGNsbbyp1NFg7zda0=");
byte[] gostCA1 = Base64.decode(
"MIIDNDCCAuGgAwIBAgIQZLcKDcWcQopF+jp4p9jylDAKBgYqhQMCAgQFADBm"
+ "MQswCQYDVQQGEwJSVTEPMA0GA1UEBxMGTW9zY293MRcwFQYDVQQKEw5PT08g"
+ "Q3J5cHRvLVBybzEUMBIGA1UECxMLRGV2ZWxvcG1lbnQxFzAVBgNVBAMTDkNQ"
+ "IENTUCBUZXN0IENBMB4XDTAyMDYwOTE1NTIyM1oXDTA5MDYwOTE1NTkyOVow"
+ "ZjELMAkGA1UEBhMCUlUxDzANBgNVBAcTBk1vc2NvdzEXMBUGA1UEChMOT09P"
+ "IENyeXB0by1Qcm8xFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5D"
+ "UCBDU1AgVGVzdCBDQTCBpTAcBgYqhQMCAhQwEgYHKoUDAgIgAgYHKoUDAgIe"
+ "AQOBhAAEgYAYglywKuz1nMc9UiBYOaulKy53jXnrqxZKbCCBSVaJ+aCKbsQm"
+ "glhRFrw6Mwu8Cdeabo/ojmea7UDMZd0U2xhZFRti5EQ7OP6YpqD0alllo7za"
+ "4dZNXdX+/ag6fOORSLFdMpVx5ganU0wHMPk67j+audnCPUj/plbeyccgcdcd"
+ "WaOCASIwggEeMAsGA1UdDwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud"
+ "DgQWBBTe840gTo4zt2twHilw3PD9wJaX0TCBygYDVR0fBIHCMIG/MDygOqA4"
+ "hjYtaHR0cDovL2ZpZXdhbGwvQ2VydEVucm9sbC9DUCUyMENTUCUyMFRlc3Ql"
+ "MjBDQSgzKS5jcmwwRKBCoECGPmh0dHA6Ly93d3cuY3J5cHRvcHJvLnJ1L0Nl"
+ "cnRFbnJvbGwvQ1AlMjBDU1AlMjBUZXN0JTIwQ0EoMykuY3JsMDmgN6A1hjMt"
+ "ZmlsZTovL1xcZmlld2FsbFxDZXJ0RW5yb2xsXENQIENTUCBUZXN0IENBKDMp"
+ "LmNybC8wEgYJKwYBBAGCNxUBBAUCAwMAAzAKBgYqhQMCAgQFAANBAIJi7ni7"
+ "9rwMR5rRGTFftt2k70GbqyUEfkZYOzrgdOoKiB4IIsIstyBX0/ne6GsL9Xan"
+ "G2IN96RB7KrowEHeW+k=");
byte[] gostCA2 = Base64.decode(
"MIIC2DCCAoWgAwIBAgIQe9ZCugm42pRKNcHD8466zTAKBgYqhQMCAgMFADB+"
+ "MRowGAYJKoZIhvcNAQkBFgtzYmFAZGlndC5ydTELMAkGA1UEBhMCUlUxDDAK"
+ "BgNVBAgTA01FTDEUMBIGA1UEBxMLWW9zaGthci1PbGExDTALBgNVBAoTBERp"
+ "Z3QxDzANBgNVBAsTBkNyeXB0bzEPMA0GA1UEAxMGc2JhLUNBMB4XDTA0MDgw"
+ "MzEzMzE1OVoXDTE0MDgwMzEzNDAxMVowfjEaMBgGCSqGSIb3DQEJARYLc2Jh"
+ "QGRpZ3QucnUxCzAJBgNVBAYTAlJVMQwwCgYDVQQIEwNNRUwxFDASBgNVBAcT"
+ "C1lvc2hrYXItT2xhMQ0wCwYDVQQKEwREaWd0MQ8wDQYDVQQLEwZDcnlwdG8x"
+ "DzANBgNVBAMTBnNiYS1DQTBjMBwGBiqFAwICEzASBgcqhQMCAiMBBgcqhQMC"
+ "Ah4BA0MABEDMSy10CuOH+i8QKG2UWA4XmCt6+BFrNTZQtS6bOalyDY8Lz+G7"
+ "HybyipE3PqdTB4OIKAAPsEEeZOCZd2UXGQm5o4HaMIHXMBMGCSsGAQQBgjcU"
+ "AgQGHgQAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud"
+ "DgQWBBRJJl3LcNMxkZI818STfoi3ng1xoDBxBgNVHR8EajBoMDGgL6Athito"
+ "dHRwOi8vc2JhLmRpZ3QubG9jYWwvQ2VydEVucm9sbC9zYmEtQ0EuY3JsMDOg"
+ "MaAvhi1maWxlOi8vXFxzYmEuZGlndC5sb2NhbFxDZXJ0RW5yb2xsXHNiYS1D"
+ "QS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwCgYGKoUDAgIDBQADQQA+BRJHbc/p"
+ "q8EYl6iJqXCuR+ozRmH7hPAP3c4KqYSC38TClCgBloLapx/3/WdatctFJW/L"
+ "mcTovpq088927shE");
byte[] inDirectCrl = Base64.decode(
"MIIdXjCCHMcCAQEwDQYJKoZIhvcNAQEFBQAwdDELMAkGA1UEBhMCREUxHDAaBgNV"
+"BAoUE0RldXRzY2hlIFRlbGVrb20gQUcxFzAVBgNVBAsUDlQtVGVsZVNlYyBUZXN0"
+"MS4wDAYHAoIGAQoHFBMBMTAeBgNVBAMUF1QtVGVsZVNlYyBUZXN0IERJUiA4OlBO"
+"Fw0wNjA4MDQwODQ1MTRaFw0wNjA4MDQxNDQ1MTRaMIIbfzB+AgQvrj/pFw0wMzA3"
+"MjIwNTQxMjhaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+oXDTAzMDcyMjA1NDEyOFowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/5xcNMDQwNDA1MTMxODE3WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/oFw0wNDA0"
+"MDUxMzE4MTdaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+UXDTAzMDExMzExMTgxMVowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/5hcNMDMwMTEzMTExODExWjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/jFw0wMzAx"
+"MTMxMTI2NTZaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+QXDTAzMDExMzExMjY1NlowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/4hcNMDQwNzEzMDc1ODM4WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/eFw0wMzAy"
+"MTcwNjMzMjVaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP98XDTAzMDIxNzA2MzMyNVowZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/0xcNMDMwMjE3MDYzMzI1WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/dFw0wMzAx"
+"MTMxMTI4MTRaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP9cXDTAzMDExMzExMjcwN1owZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/2BcNMDMwMTEzMTEyNzA3WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/VFw0wMzA0"
+"MzAxMjI3NTNaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD"
+"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU"
+"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP9YXDTAzMDQzMDEyMjc1M1owZzBlBgNV"
+"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6"
+"UE4wfgIEL64/xhcNMDMwMjEyMTM0NTQwWjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC"
+"BgEKBxQTATEwGAYDVQQDFBFUVEMgVGVzdCBDQSAxMTpQTjCBkAIEL64/xRcNMDMw"
+"MjEyMTM0NTQwWjB5MHcGA1UdHQEB/wRtMGukaTBnMQswCQYDVQQGEwJERTEcMBoG"
+"A1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEQMA4GA1UECxQHVGVsZVNlYzEoMAwG"
+"BwKCBgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNTpQTjB+AgQvrj/CFw0w"
+"MzAyMTIxMzA5MTZaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRww"
+"GgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNV"
+"BAMUEVRUQyBUZXN0IENBIDExOlBOMIGQAgQvrj/BFw0wMzAyMTIxMzA4NDBaMHkw"
+"dwYDVR0dAQH/BG0wa6RpMGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2No"
+"ZSBUZWxla29tIEFHMRAwDgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAY"
+"BgNVBAMUEVNpZ0cgVGVzdCBDQSA1OlBOMH4CBC+uP74XDTAzMDIxNzA2MzcyNVow"
+"ZzBlBgNVHR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRz"
+"Y2hlIFRlbGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRVFRDIFRlc3Qg"
+"Q0EgMTE6UE4wgZACBC+uP70XDTAzMDIxNzA2MzcyNVoweTB3BgNVHR0BAf8EbTBr"
+"pGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcx"
+"EDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBU"
+"ZXN0IENBIDU6UE4wgZACBC+uP7AXDTAzMDIxMjEzMDg1OVoweTB3BgNVHR0BAf8E"
+"bTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g"
+"QUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2ln"
+"RyBUZXN0IENBIDU6UE4wgZACBC+uP68XDTAzMDIxNzA2MzcyNVoweTB3BgNVHR0B"
+"Af8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVr"
+"b20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQR"
+"U2lnRyBUZXN0IENBIDU6UE4wfgIEL64/kxcNMDMwNDEwMDUyNjI4WjBnMGUGA1Ud"
+"HQEB/wRbMFmkVzBVMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVs"
+"ZWtvbSBBRzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFUVEMgVGVzdCBDQSAxMTpQ"
+"TjCBkAIEL64/khcNMDMwNDEwMDUyNjI4WjB5MHcGA1UdHQEB/wRtMGukaTBnMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEQMA4GA1UE"
+"CxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0Eg"
+"NTpQTjB+AgQvrj8/Fw0wMzAyMjYxMTA0NDRaMGcwZQYDVR0dAQH/BFswWaRXMFUx"
+"CzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYH"
+"AoIGAQoHFBMBMTAYBgNVBAMUEVRUQyBUZXN0IENBIDExOlBOMIGQAgQvrj8+Fw0w"
+"MzAyMjYxMTA0NDRaMHkwdwYDVR0dAQH/BG0wa6RpMGcxCzAJBgNVBAYTAkRFMRww"
+"GgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYDVQQLFAdUZWxlU2VjMSgw"
+"DAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBDQSA1OlBOMH4CBC+uPs0X"
+"DTAzMDUyMDA1MjczNlowZzBlBgNVHR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUx"
+"HDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgG"
+"A1UEAxQRVFRDIFRlc3QgQ0EgMTE6UE4wgZACBC+uPswXDTAzMDUyMDA1MjczNlow"
+"eTB3BgNVHR0BAf8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRz"
+"Y2hlIFRlbGVrb20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwEx"
+"MBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6UE4wfgIEL64+PBcNMDMwNjE3MTAzNDE2"
+"WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1"
+"dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFUVEMgVGVz"
+"dCBDQSAxMTpQTjCBkAIEL64+OxcNMDMwNjE3MTAzNDE2WjB5MHcGA1UdHQEB/wRt"
+"MGukaTBnMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBB"
+"RzEQMA4GA1UECxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFTaWdH"
+"IFRlc3QgQ0EgNjpQTjCBkAIEL64+OhcNMDMwNjE3MTAzNDE2WjB5MHcGA1UdHQEB"
+"/wRtMGukaTBnMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtv"
+"bSBBRzEQMA4GA1UECxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFT"
+"aWdHIFRlc3QgQ0EgNjpQTjB+AgQvrj45Fw0wMzA2MTcxMzAxMDBaMGcwZQYDVR0d"
+"AQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxl"
+"a29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVRUQyBUZXN0IENBIDExOlBO"
+"MIGQAgQvrj44Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6RpMGcxCzAJ"
+"BgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYDVQQL"
+"FAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBDQSA2"
+"OlBOMIGQAgQvrj43Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6RpMGcx"
+"CzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYD"
+"VQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBD"
+"QSA2OlBOMIGQAgQvrj42Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6Rp"
+"MGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAw"
+"DgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVz"
+"dCBDQSA2OlBOMIGQAgQvrj4zFw0wMzA2MTcxMDM3NDlaMHkwdwYDVR0dAQH/BG0w"
+"a6RpMGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFH"
+"MRAwDgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cg"
+"VGVzdCBDQSA2OlBOMH4CBC+uPjEXDTAzMDYxNzEwNDI1OFowZzBlBgNVHR0BAf8E"
+"WzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g"
+"QUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRVFRDIFRlc3QgQ0EgMTE6UE4wgZAC"
+"BC+uPjAXDTAzMDYxNzEwNDI1OFoweTB3BgNVHR0BAf8EbTBrpGkwZzELMAkGA1UE"
+"BhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNVBAsUB1Rl"
+"bGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6UE4w"
+"gZACBC+uPakXDTAzMTAyMjExMzIyNFoweTB3BgNVHR0BAf8EbTBrpGkwZzELMAkG"
+"A1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNVBAsU"
+"B1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6"
+"UE4wgZACBC+uPLIXDTA1MDMxMTA2NDQyNFoweTB3BgNVHR0BAf8EbTBrpGkwZzEL"
+"MAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNV"
+"BAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENB"
+"IDY6UE4wgZACBC+uPKsXDTA0MDQwMjA3NTQ1M1oweTB3BgNVHR0BAf8EbTBrpGkw"
+"ZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAO"
+"BgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0"
+"IENBIDY6UE4wgZACBC+uOugXDTA1MDEyNzEyMDMyNFoweTB3BgNVHR0BAf8EbTBr"
+"pGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcx"
+"EDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBU"
+"ZXN0IENBIDY6UE4wgZACBC+uOr4XDTA1MDIxNjA3NTcxNloweTB3BgNVHR0BAf8E"
+"bTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g"
+"QUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2ln"
+"RyBUZXN0IENBIDY6UE4wgZACBC+uOqcXDTA1MDMxMDA1NTkzNVoweTB3BgNVHR0B"
+"Af8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVr"
+"b20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQR"
+"U2lnRyBUZXN0IENBIDY6UE4wgZACBC+uOjwXDTA1MDUxMTEwNDk0NloweTB3BgNV"
+"HR0BAf8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl"
+"bGVrb20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UE"
+"AxQRU2lnRyBUZXN0IENBIDY6UE4wgaoCBC+sbdUXDTA1MTExMTEwMDMyMVowgZIw"
+"gY8GA1UdHQEB/wSBhDCBgaR/MH0xCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0"
+"c2NoZSBUZWxla29tIEFHMR8wHQYDVQQLFBZQcm9kdWt0emVudHJ1bSBUZWxlU2Vj"
+"MS8wDAYHAoIGAQoHFBMBMTAfBgNVBAMUGFRlbGVTZWMgUEtTIFNpZ0cgQ0EgMTpQ"
+"TjCBlQIEL64uaBcNMDYwMTIzMTAyNTU1WjB+MHwGA1UdHQEB/wRyMHCkbjBsMQsw"
+"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEWMBQGA1UE"
+"CxQNWmVudHJhbGUgQm9ubjEnMAwGBwKCBgEKBxQTATEwFwYDVQQDFBBUVEMgVGVz"
+"dCBDQSA5OlBOMIGVAgQvribHFw0wNjA4MDEwOTQ4NDRaMH4wfAYDVR0dAQH/BHIw"
+"cKRuMGwxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFH"
+"MRYwFAYDVQQLFA1aZW50cmFsZSBCb25uMScwDAYHAoIGAQoHFBMBMTAXBgNVBAMU"
+"EFRUQyBUZXN0IENBIDk6UE6ggZswgZgwCwYDVR0UBAQCAhEMMB8GA1UdIwQYMBaA"
+"FANbyNumDI9545HwlCF26NuOJC45MA8GA1UdHAEB/wQFMAOEAf8wVwYDVR0SBFAw"
+"ToZMbGRhcDovL3Brc2xkYXAudHR0Yy5kZS9vdT1ULVRlbGVTZWMgVGVzdCBESVIg"
+"ODpQTixvPURldXRzY2hlIFRlbGVrb20gQUcsYz1kZTANBgkqhkiG9w0BAQUFAAOB"
+"gQBewL5gLFHpeOWO07Vk3Gg7pRDuAlvaovBH4coCyCWpk5jEhUfFSYEDuaQB7do4"
+"IlJmeTHvkI0PIZWJ7bwQ2PVdipPWDx0NVwS/Cz5jUKiS3BbAmZQZOueiKLFpQq3A"
+"b8aOHA7WHU4078/1lM+bgeu33Ln1CGykEbmSjA/oKPi/JA==");
byte[] directCRL = Base64.decode(
"MIIGXTCCBckCAQEwCgYGKyQDAwECBQAwdDELMAkGA1UEBhMCREUxHDAaBgNVBAoU"
+"E0RldXRzY2hlIFRlbGVrb20gQUcxFzAVBgNVBAsUDlQtVGVsZVNlYyBUZXN0MS4w"
+"DAYHAoIGAQoHFBMBMTAeBgNVBAMUF1QtVGVsZVNlYyBUZXN0IERJUiA4OlBOFw0w"
+"NjA4MDQwODQ1MTRaFw0wNjA4MDQxNDQ1MTRaMIIElTAVAgQvrj/pFw0wMzA3MjIw"
+"NTQxMjhaMBUCBC+uP+oXDTAzMDcyMjA1NDEyOFowFQIEL64/5xcNMDQwNDA1MTMx"
+"ODE3WjAVAgQvrj/oFw0wNDA0MDUxMzE4MTdaMBUCBC+uP+UXDTAzMDExMzExMTgx"
+"MVowFQIEL64/5hcNMDMwMTEzMTExODExWjAVAgQvrj/jFw0wMzAxMTMxMTI2NTZa"
+"MBUCBC+uP+QXDTAzMDExMzExMjY1NlowFQIEL64/4hcNMDQwNzEzMDc1ODM4WjAV"
+"AgQvrj/eFw0wMzAyMTcwNjMzMjVaMBUCBC+uP98XDTAzMDIxNzA2MzMyNVowFQIE"
+"L64/0xcNMDMwMjE3MDYzMzI1WjAVAgQvrj/dFw0wMzAxMTMxMTI4MTRaMBUCBC+u"
+"P9cXDTAzMDExMzExMjcwN1owFQIEL64/2BcNMDMwMTEzMTEyNzA3WjAVAgQvrj/V"
+"Fw0wMzA0MzAxMjI3NTNaMBUCBC+uP9YXDTAzMDQzMDEyMjc1M1owFQIEL64/xhcN"
+"MDMwMjEyMTM0NTQwWjAVAgQvrj/FFw0wMzAyMTIxMzQ1NDBaMBUCBC+uP8IXDTAz"
+"MDIxMjEzMDkxNlowFQIEL64/wRcNMDMwMjEyMTMwODQwWjAVAgQvrj++Fw0wMzAy"
+"MTcwNjM3MjVaMBUCBC+uP70XDTAzMDIxNzA2MzcyNVowFQIEL64/sBcNMDMwMjEy"
+"MTMwODU5WjAVAgQvrj+vFw0wMzAyMTcwNjM3MjVaMBUCBC+uP5MXDTAzMDQxMDA1"
+"MjYyOFowFQIEL64/khcNMDMwNDEwMDUyNjI4WjAVAgQvrj8/Fw0wMzAyMjYxMTA0"
+"NDRaMBUCBC+uPz4XDTAzMDIyNjExMDQ0NFowFQIEL64+zRcNMDMwNTIwMDUyNzM2"
+"WjAVAgQvrj7MFw0wMzA1MjAwNTI3MzZaMBUCBC+uPjwXDTAzMDYxNzEwMzQxNlow"
+"FQIEL64+OxcNMDMwNjE3MTAzNDE2WjAVAgQvrj46Fw0wMzA2MTcxMDM0MTZaMBUC"
+"BC+uPjkXDTAzMDYxNzEzMDEwMFowFQIEL64+OBcNMDMwNjE3MTMwMTAwWjAVAgQv"
+"rj43Fw0wMzA2MTcxMzAxMDBaMBUCBC+uPjYXDTAzMDYxNzEzMDEwMFowFQIEL64+"
+"MxcNMDMwNjE3MTAzNzQ5WjAVAgQvrj4xFw0wMzA2MTcxMDQyNThaMBUCBC+uPjAX"
+"DTAzMDYxNzEwNDI1OFowFQIEL649qRcNMDMxMDIyMTEzMjI0WjAVAgQvrjyyFw0w"
+"NTAzMTEwNjQ0MjRaMBUCBC+uPKsXDTA0MDQwMjA3NTQ1M1owFQIEL6466BcNMDUw"
+"MTI3MTIwMzI0WjAVAgQvrjq+Fw0wNTAyMTYwNzU3MTZaMBUCBC+uOqcXDTA1MDMx"
+"MDA1NTkzNVowFQIEL646PBcNMDUwNTExMTA0OTQ2WjAVAgQvrG3VFw0wNTExMTEx"
+"MDAzMjFaMBUCBC+uLmgXDTA2MDEyMzEwMjU1NVowFQIEL64mxxcNMDYwODAxMDk0"
+"ODQ0WqCBijCBhzALBgNVHRQEBAICEQwwHwYDVR0jBBgwFoAUA1vI26YMj3njkfCU"
+"IXbo244kLjkwVwYDVR0SBFAwToZMbGRhcDovL3Brc2xkYXAudHR0Yy5kZS9vdT1U"
+"LVRlbGVTZWMgVGVzdCBESVIgODpQTixvPURldXRzY2hlIFRlbGVrb20gQUcsYz1k"
+"ZTAKBgYrJAMDAQIFAAOBgQArj4eMlbAwuA2aS5O4UUUHQMKKdK/dtZi60+LJMiMY"
+"ojrMIf4+ZCkgm1Ca0Cd5T15MJxVHhh167Ehn/Hd48pdnAP6Dfz/6LeqkIHGWMHR+"
+"z6TXpwWB+P4BdUec1ztz04LypsznrHcLRa91ixg9TZCb1MrOG+InNhleRs1ImXk8"
+"MQ==");
private PublicKey dudPublicKey = new PublicKey()
{
public String getAlgorithm()
{
return null;
}
public String getFormat()
{
return null;
}
public byte[] getEncoded()
{
return null;
}
};
public String getName()
{
return "CertTest";
}
public void checkCertificate(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
Certificate cert = fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkNameCertificate(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
if (!cert.getIssuerDN().toString().equals("C=DE,O=DATEV eG,0.2.262.1.10.7.20=1+CN=CA DATEV D03 1:PN"))
{
fail(id + " failed - name test.");
}
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkKeyUsage(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
if (cert.getKeyUsage()[7])
{
fail("error generating cert - key usage wrong.");
}
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkSelfSignedCertificate(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
Certificate cert = fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
cert.verify(k);
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
/**
* we generate a self signed certificate for the sake of testing - RSA
*/
public void checkCreation1()
throws Exception
{
//
// a sample key pair.
//
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16));
RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
Vector ord = new Vector();
Vector values = new Vector();
ord.addElement(X509Principal.C);
ord.addElement(X509Principal.O);
ord.addElement(X509Principal.L);
ord.addElement(X509Principal.ST);
ord.addElement(X509Principal.E);
values.addElement("AU");
values.addElement("The Legion of the Bouncy Castle");
values.addElement("Melbourne");
values.addElement("Victoria");
values.addElement("[email protected]");
//
// extensions
//
//
// create the certificate - version 3 - without extensions
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
X509Certificate cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
Set dummySet = cert.getNonCriticalExtensionOIDs();
dummySet = cert.getNonCriticalExtensionOIDs();
//
// create the certificate - version 3 - with extensions
//
certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
certGen.addExtension("2.5.29.15", true,
new X509KeyUsage(X509KeyUsage.encipherOnly));
certGen.addExtension("2.5.29.37", true,
new DERSequence(KeyPurposeId.anyExtendedKeyUsage));
certGen.addExtension("2.5.29.17", true,
new GeneralNames(new GeneralName(GeneralName.rfc822Name, "[email protected]")));
cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream sbIn = new ByteArrayInputStream(cert.getEncoded());
ASN1InputStream sdIn = new ASN1InputStream(sbIn);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
if (!cert.getKeyUsage()[7])
{
fail("error generating cert - key usage wrong.");
}
List l = cert.getExtendedKeyUsage();
if (!l.get(0).equals(KeyPurposeId.anyExtendedKeyUsage.getId()))
{
fail("failed extended key usage test");
}
Collection c = cert.getSubjectAlternativeNames();
Iterator it = c.iterator();
while (it.hasNext())
{
List gn = (List)it.next();
if (!gn.get(1).equals("[email protected]"))
{
fail("failed subject alternative names test");
}
}
// System.out.println(cert);
//
// create the certificate - version 1
//
X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();
certGen1.setSerialNumber(BigInteger.valueOf(1));
certGen1.setIssuerDN(new X509Principal(ord, attrs));
certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen1.setSubjectDN(new X509Principal(ord, values));
certGen1.setPublicKey(pubKey);
certGen1.setSignatureAlgorithm("MD5WithRSAEncryption");
cert = certGen1.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
bIn = new ByteArrayInputStream(cert.getEncoded());
certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
// System.out.println(cert);
if (!cert.getIssuerDN().equals(cert.getSubjectDN()))
{
fail("name comparison fails");
}
}
/**
* we generate a self signed certificate for the sake of testing - DSA
*/
public void checkCreation2()
{
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
try
{
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN");
g.initialize(512, new SecureRandom());
KeyPair p = g.generateKeyPair();
privKey = p.getPrivate();
pubKey = p.getPublic();
}
catch (Exception e)
{
fail("error setting up keys - " + e.toString());
return;
}
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
//
// extensions
//
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA1withDSA");
try
{
X509Certificate cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
// System.out.println(cert);
}
catch (Exception e)
{
fail("error setting generating cert - " + e.toString());
}
//
// create the certificate - version 1
//
X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();
certGen1.setSerialNumber(BigInteger.valueOf(1));
certGen1.setIssuerDN(new X509Principal(attrs));
certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen1.setSubjectDN(new X509Principal(attrs));
certGen1.setPublicKey(pubKey);
certGen1.setSignatureAlgorithm("SHA1withDSA");
try
{
X509Certificate cert = certGen1.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
//System.out.println(cert);
}
catch (Exception e)
{
fail("error setting generating cert - " + e.toString());
}
//
// exception test
//
try
{
certGen.setPublicKey(dudPublicKey);
fail("key without encoding not detected in v1");
}
catch (IllegalArgumentException e)
{
// expected
}
}
/**
* we generate a self signed certificate for the sake of testing - ECDSA
*/
public void checkCreation3()
{
ECCurve curve = new ECCurve.Fp(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECParameterSpec spec = new ECParameterSpec(
curve,
curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n
ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
spec);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
spec);
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
try
{
KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
}
catch (Exception e)
{
fail("error setting up keys - " + e.toString());
return;
}
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
order.addElement(X509Principal.C);
order.addElement(X509Principal.O);
order.addElement(X509Principal.L);
order.addElement(X509Principal.ST);
order.addElement(X509Principal.E);
//
// toString test
//
X509Principal p = new X509Principal(order, attrs);
String s = p.toString();
if (!s.equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,[email protected]"))
{
fail("ordered X509Principal test failed - s = " + s + ".");
}
p = new X509Principal(attrs);
s = p.toString();
//
// we need two of these as the hash code for strings changed...
//
if (!s.equals("O=The Legion of the Bouncy Castle,[email protected],ST=Victoria,L=Melbourne,C=AU") && !s.equals("ST=Victoria,L=Melbourne,C=AU,[email protected],O=The Legion of the Bouncy Castle"))
{
fail("unordered X509Principal test failed.");
}
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(order, attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(order, attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA1withECDSA");
try
{
X509Certificate cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
//
// try with point compression turned off
//
((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
certGen.setPublicKey(pubKey);
cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
bIn = new ByteArrayInputStream(cert.getEncoded());
fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
// System.out.println(cert);
}
catch (Exception e)
{
fail("error setting generating cert - " + e.toString());
}
X509Principal pr = new X509Principal("O=\"The Bouncy Castle, The Legion of\",[email protected],ST=Victoria,L=Melbourne,C=AU");
if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
{
fail("string based X509Principal test failed.");
}
pr = new X509Principal("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU");
if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
{
fail("string based X509Principal test failed.");
}
}
/**
* we generate a self signed certificate for the sake of testing - SHA224withECDSA
*/
private void createECCert(String algorithm, DERObjectIdentifier algOid)
throws Exception
{
ECCurve.Fp curve = new ECCurve.Fp(
new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a
new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b
ECParameterSpec spec = new ECParameterSpec(
curve,
curve.decodePoint(Hex.decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n
ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(
new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
spec);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
spec);
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
order.addElement(X509Principal.C);
order.addElement(X509Principal.O);
order.addElement(X509Principal.L);
order.addElement(X509Principal.ST);
order.addElement(X509Principal.E);
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(order, attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(order, attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm(algorithm);
X509Certificate cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
//
// try with point compression turned off
//
((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
certGen.setPublicKey(pubKey);
cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
bIn = new ByteArrayInputStream(cert.getEncoded());
certFact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)certFact.generateCertificate(bIn);
if (!cert.getSigAlgOID().equals(algOid.toString()))
{
fail("ECDSA oid incorrect.");
}
if (cert.getSigAlgParams() != null)
{
fail("sig parameters present");
}
Signature sig = Signature.getInstance(algorithm, "BC");
sig.initVerify(pubKey);
sig.update(cert.getTBSCertificate());
if (!sig.verify(cert.getSignature()))
{
fail("EC certificate signature not mapped correctly.");
}
// System.out.println(cert);
}
private void checkCRL(
int id,
byte[] bytes)
{
ByteArrayInputStream bIn;
String dump = "";
try
{
bIn = new ByteArrayInputStream(bytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
CRL cert = fact.generateCRL(bIn);
// System.out.println(cert);
}
catch (Exception e)
{
fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e);
}
}
public void checkCRLCreation1()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
Date now = new Date();
KeyPair pair = kpGen.generateKeyPair();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
crlGen.addCRLEntry(BigInteger.ONE, now, CRLReason.privilegeWithdrawn);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL crl = crlGen.generate(pair.getPrivate(), "BC");
if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA")))
{
fail("failed CRL issuer test");
}
byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (authExt == null)
{
fail("failed to find CRL extension");
}
AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);
X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE);
if (entry == null)
{
fail("failed to find CRL entry");
}
if (!entry.getSerialNumber().equals(BigInteger.ONE))
{
fail("CRL cert serial number does not match");
}
if (!entry.hasExtensions())
{
fail("CRL entry extension not found");
}
byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId());
if (ext != null)
{
DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext);
if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn)
{
fail("CRL entry reasonCode wrong");
}
}
else
{
fail("CRL entry reasonCode not found");
}
}
public void checkCRLCreation2()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
Date now = new Date();
KeyPair pair = kpGen.generateKeyPair();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
Vector extOids = new Vector();
Vector extValues = new Vector();
CRLReason crlReason = new CRLReason(CRLReason.privilegeWithdrawn);
try
{
extOids.addElement(X509Extensions.ReasonCode);
extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded())));
}
catch (IOException e)
{
throw new IllegalArgumentException("error encoding reason: " + e);
}
X509Extensions entryExtensions = new X509Extensions(extOids, extValues);
crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL crl = crlGen.generate(pair.getPrivate(), "BC");
if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA")))
{
fail("failed CRL issuer test");
}
byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (authExt == null)
{
fail("failed to find CRL extension");
}
AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);
X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE);
if (entry == null)
{
fail("failed to find CRL entry");
}
if (!entry.getSerialNumber().equals(BigInteger.ONE))
{
fail("CRL cert serial number does not match");
}
if (!entry.hasExtensions())
{
fail("CRL entry extension not found");
}
byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId());
if (ext != null)
{
DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext);
if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn)
{
fail("CRL entry reasonCode wrong");
}
}
else
{
fail("CRL entry reasonCode not found");
}
}
public void checkCRLCreation3()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
Date now = new Date();
KeyPair pair = kpGen.generateKeyPair();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
Vector extOids = new Vector();
Vector extValues = new Vector();
CRLReason crlReason = new CRLReason(CRLReason.privilegeWithdrawn);
try
{
extOids.addElement(X509Extensions.ReasonCode);
extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded())));
}
catch (IOException e)
{
throw new IllegalArgumentException("error encoding reason: " + e);
}
X509Extensions entryExtensions = new X509Extensions(extOids, extValues);
crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL crl = crlGen.generate(pair.getPrivate(), "BC");
if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA")))
{
fail("failed CRL issuer test");
}
byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (authExt == null)
{
fail("failed to find CRL extension");
}
AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);
X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE);
if (entry == null)
{
fail("failed to find CRL entry");
}
if (!entry.getSerialNumber().equals(BigInteger.ONE))
{
fail("CRL cert serial number does not match");
}
if (!entry.hasExtensions())
{
fail("CRL entry extension not found");
}
byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId());
if (ext != null)
{
DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext);
if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn)
{
fail("CRL entry reasonCode wrong");
}
}
else
{
fail("CRL entry reasonCode not found");
}
//
// check loading of existing CRL
//
crlGen = new X509V2CRLGenerator();
now = new Date();
crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
crlGen.setThisUpdate(now);
crlGen.setNextUpdate(new Date(now.getTime() + 100000));
crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
crlGen.addCRL(crl);
crlGen.addCRLEntry(BigInteger.valueOf(2), now, entryExtensions);
crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
X509CRL newCrl = crlGen.generate(pair.getPrivate(), "BC");
int count = 0;
boolean oneFound = false;
boolean twoFound = false;
Iterator it = newCrl.getRevokedCertificates().iterator();
while (it.hasNext())
{
X509CRLEntry crlEnt = (X509CRLEntry)it.next();
if (crlEnt.getSerialNumber().intValue() == 1)
{
oneFound = true;
}
else if (crlEnt.getSerialNumber().intValue() == 2)
{
twoFound = true;
}
count++;
}
if (count != 2)
{
fail("wrong number of CRLs found");
}
if (!oneFound || !twoFound)
{
fail("wrong CRLs found in copied list");
}
//
// check factory read back
//
CertificateFactory cFact = CertificateFactory.getInstance("X.509", "BC");
X509CRL readCrl = (X509CRL)cFact.generateCRL(new ByteArrayInputStream(newCrl.getEncoded()));
if (readCrl == null)
{
fail("crl not returned!");
}
Collection col = cFact.generateCRLs(new ByteArrayInputStream(newCrl.getEncoded()));
if (col.size() != 1)
{
fail("wrong number of CRLs found in collection");
}
}
/**
* we generate a self signed certificate for the sake of testing - GOST3410
*/
public void checkCreation4()
throws Exception
{
//
// set up the keys
//
PrivateKey privKey;
PublicKey pubKey;
KeyPairGenerator g = KeyPairGenerator.getInstance("GOST3410", "BC");
GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A");
g.initialize(gost3410P, new SecureRandom());
KeyPair p = g.generateKeyPair();
privKey = p.getPrivate();
pubKey = p.getPublic();
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
//
// extensions
//
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("GOST3411withGOST3410");
X509Certificate cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
//
// check verifies in general
//
cert.verify(pubKey);
//
// check verifies with contained key
//
cert.verify(cert.getPublicKey());
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
//System.out.println(cert);
//check getEncoded()
byte[] bytesch = cert.getEncoded();
}
public void checkCreation5()
throws Exception
{
//
// a sample key pair.
//
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16));
RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
//
// set up the keys
//
SecureRandom rand = new SecureRandom();
PrivateKey privKey;
PublicKey pubKey;
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
privKey = fact.generatePrivate(privKeySpec);
pubKey = fact.generatePublic(pubKeySpec);
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.E, "[email protected]");
Vector ord = new Vector();
Vector values = new Vector();
ord.addElement(X509Principal.C);
ord.addElement(X509Principal.O);
ord.addElement(X509Principal.L);
ord.addElement(X509Principal.ST);
ord.addElement(X509Principal.E);
values.addElement("AU");
values.addElement("The Legion of the Bouncy Castle");
values.addElement("Melbourne");
values.addElement("Victoria");
values.addElement("[email protected]");
//
// create base certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
certGen.addExtension("2.5.29.15", true,
new X509KeyUsage(X509KeyUsage.encipherOnly));
certGen.addExtension("2.5.29.37", true,
new DERSequence(KeyPurposeId.anyExtendedKeyUsage));
certGen.addExtension("2.5.29.17", true,
new GeneralNames(new GeneralName(GeneralName.rfc822Name, "[email protected]")));
X509Certificate baseCert = certGen.generate(privKey, "BC");
//
// copy certificate
//
certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
certGen.copyAndAddExtension(new DERObjectIdentifier("2.5.29.15"), true, baseCert);
certGen.copyAndAddExtension("2.5.29.37", false, baseCert);
X509Certificate cert = certGen.generate(privKey, "BC");
cert.checkValidity(new Date());
cert.verify(pubKey);
if (!areEqual(baseCert.getExtensionValue("2.5.29.15"), cert.getExtensionValue("2.5.29.15")))
{
fail("2.5.29.15 differs");
}
if (!areEqual(baseCert.getExtensionValue("2.5.29.37"), cert.getExtensionValue("2.5.29.37")))
{
fail("2.5.29.37 differs");
}
//
// exception test
//
try
{
certGen.copyAndAddExtension("2.5.99.99", true, baseCert);
fail("exception not thrown on dud extension copy");
}
catch (CertificateParsingException e)
{
// expected
}
try
{
certGen.setPublicKey(dudPublicKey);
certGen.generate(privKey, "BC");
fail("key without encoding not detected in v3");
}
catch (IllegalArgumentException e)
{
// expected
}
}
private void testForgedSignature()
throws Exception
{
String cert = "MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV"
+ "BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD"
+ "VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU4NTVa"
+ "Fw0wNjEwMTEyMzU4NTVaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs"
+ "YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy"
+ "IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD"
+ "hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u"
+ "12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAbynCRIlUQgaqyNgU"
+ "DF6P14yRKUtX8akOP2TwStaSiVf/akYqfLFm3UGka5XbPj4rifrZ0/sOoZEEBvHQ"
+ "e20sRA==";
CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC");
X509Certificate x509 = (X509Certificate)certFact.generateCertificate(new ByteArrayInputStream(Base64.decode(cert)));
try
{
x509.verify(x509.getPublicKey());
fail("forged RSA signature passed");
}
catch (Exception e)
{
// expected
}
}
public void performTest()
throws Exception
{
checkCertificate(1, cert1);
checkCertificate(2, cert2);
checkCertificate(4, cert4);
checkCertificate(5, cert5);
checkCertificate(6, oldEcdsa);
checkCertificate(7, cert7);
checkKeyUsage(8, keyUsage);
checkSelfSignedCertificate(9, uncompressedPtEC);
checkNameCertificate(10, nameCert);
checkSelfSignedCertificate(11, probSelfSignedCert);
checkSelfSignedCertificate(12, gostCA1);
checkSelfSignedCertificate(13, gostCA2);
checkSelfSignedCertificate(14, gost341094base);
checkSelfSignedCertificate(15, gost34102001base);
checkSelfSignedCertificate(16, gost341094A);
checkSelfSignedCertificate(17, gost341094B);
checkSelfSignedCertificate(17, gost34102001A);
checkCRL(1, crl1);
checkCreation1();
checkCreation2();
checkCreation3();
checkCreation4();
checkCreation5();
createECCert("SHA1withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1);
createECCert("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
createECCert("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
createECCert("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
createECCert("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
checkCRLCreation1();
checkCRLCreation2();
checkCRLCreation3();
testForgedSignature();
}
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new CertTest());
}
}
| added tests for PKCS7/PEM
| test/src/org/bouncycastle/jce/provider/test/CertTest.java | added tests for PKCS7/PEM | <ide><path>est/src/org/bouncycastle/jce/provider/test/CertTest.java
<ide> package org.bouncycastle.jce.provider.test;
<ide>
<add>import org.bouncycastle.asn1.ASN1EncodableVector;
<ide> import org.bouncycastle.asn1.ASN1InputStream;
<ide> import org.bouncycastle.asn1.DEREnumerated;
<ide> import org.bouncycastle.asn1.DERObjectIdentifier;
<ide> import org.bouncycastle.asn1.DEROctetString;
<ide> import org.bouncycastle.asn1.DERSequence;
<add>import org.bouncycastle.asn1.DERSet;
<add>import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
<add>import org.bouncycastle.asn1.cms.ContentInfo;
<add>import org.bouncycastle.asn1.cms.SignedData;
<ide> import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
<ide> import org.bouncycastle.asn1.x509.CRLReason;
<ide> import org.bouncycastle.asn1.x509.GeneralName;
<ide> }
<ide> }
<ide>
<add>
<add> private void pemTest()
<add> throws Exception
<add> {
<add> CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
<add>
<add> Certificate cert = cf.generateCertificate(new ByteArrayInputStream(PEMData.CERTIFICATE_1.getBytes("US-ASCII")));
<add> if (cert == null)
<add> {
<add> fail("PEM cert not read");
<add> }
<add> CRL crl = cf.generateCRL(new ByteArrayInputStream(PEMData.CRL_1.getBytes("US-ASCII")));
<add> if (crl == null)
<add> {
<add> fail("PEM crl not read");
<add> }
<add> Collection col = cf.generateCertificates(new ByteArrayInputStream(PEMData.CERTIFICATE_2.getBytes("US-ASCII")));
<add> if (col.size() != 1 || !col.contains(cert))
<add> {
<add> fail("PEM cert collection not right");
<add> }
<add> col = cf.generateCRLs(new ByteArrayInputStream(PEMData.CRL_2.getBytes("US-ASCII")));
<add> if (col.size() != 1 || !col.contains(crl))
<add> {
<add> fail("PEM crl collection not right");
<add> }
<add> }
<add>
<add> private void pkcs7Test()
<add> throws Exception
<add> {
<add> ASN1EncodableVector certs = new ASN1EncodableVector();
<add>
<add> certs.add(new ASN1InputStream(CertPathTest.rootCertBin).readObject());
<add> certs.add(new ASN1InputStream(AttrCertTest.attrCert).readObject());
<add>
<add> ASN1EncodableVector crls = new ASN1EncodableVector();
<add>
<add> crls.add(new ASN1InputStream(CertPathTest.rootCrlBin).readObject());
<add> SignedData sigData = new SignedData(new DERSet(), new ContentInfo(CMSObjectIdentifiers.data, null), new DERSet(certs), new DERSet(crls), new DERSet());
<add>
<add> ContentInfo info = new ContentInfo(CMSObjectIdentifiers.signedData, sigData);
<add>
<add> CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
<add>
<add> X509Certificate cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(info.getEncoded()));
<add> if (cert == null || !areEqual(cert.getEncoded(), certs.get(0).getDERObject().getEncoded()))
<add> {
<add> fail("PKCS7 cert not read");
<add> }
<add> X509CRL crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(info.getEncoded()));
<add> if (crl == null || !areEqual(crl.getEncoded(), crls.get(0).getDERObject().getEncoded()))
<add> {
<add> fail("PKCS7 crl not read");
<add> }
<add> Collection col = cf.generateCertificates(new ByteArrayInputStream(info.getEncoded()));
<add> if (col.size() != 1 || !col.contains(cert))
<add> {
<add> fail("PKCS7 cert collection not right");
<add> }
<add> col = cf.generateCRLs(new ByteArrayInputStream(info.getEncoded()));
<add> if (col.size() != 1 || !col.contains(crl))
<add> {
<add> fail("PKCS7 crl collection not right");
<add> }
<add>
<add> // data with no certificates or CRLs
<add>
<add> sigData = new SignedData(new DERSet(), new ContentInfo(CMSObjectIdentifiers.data, null), new DERSet(), new DERSet(), new DERSet());
<add>
<add> info = new ContentInfo(CMSObjectIdentifiers.signedData, sigData);
<add>
<add> cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(info.getEncoded()));
<add> if (cert != null)
<add> {
<add> fail("PKCS7 cert present");
<add> }
<add> crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(info.getEncoded()));
<add> if (crl != null)
<add> {
<add> fail("PKCS7 crl present");
<add> }
<add> }
<add>
<ide> public void performTest()
<ide> throws Exception
<ide> {
<ide> checkCertificate(5, cert5);
<ide> checkCertificate(6, oldEcdsa);
<ide> checkCertificate(7, cert7);
<del>
<add>
<ide> checkKeyUsage(8, keyUsage);
<ide> checkSelfSignedCertificate(9, uncompressedPtEC);
<ide> checkNameCertificate(10, nameCert);
<del>
<add>
<ide> checkSelfSignedCertificate(11, probSelfSignedCert);
<ide> checkSelfSignedCertificate(12, gostCA1);
<ide> checkSelfSignedCertificate(13, gostCA2);
<ide> checkSelfSignedCertificate(16, gost341094A);
<ide> checkSelfSignedCertificate(17, gost341094B);
<ide> checkSelfSignedCertificate(17, gost34102001A);
<del>
<add>
<ide> checkCRL(1, crl1);
<del>
<add>
<ide> checkCreation1();
<ide> checkCreation2();
<ide> checkCreation3();
<ide> checkCreation4();
<ide> checkCreation5();
<del>
<add>
<ide> createECCert("SHA1withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1);
<ide> createECCert("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
<ide> createECCert("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
<ide> createECCert("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
<ide> createECCert("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
<del>
<add>
<ide> checkCRLCreation1();
<ide> checkCRLCreation2();
<ide> checkCRLCreation3();
<add>
<add> pemTest();
<add> pkcs7Test();
<ide>
<ide> testForgedSignature();
<ide> } |
|
JavaScript | mit | 9fae29f1065fb758c5c175bbe71990a4eb8818f5 | 0 | devm33/gulp-ng-template-strings | 'use strict';
var es = require('event-stream');
var gutil = require('gulp-util');
var fs = require('fs');
var path = require('path');
var NAME = 'gulp-ng-template-strings';
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
function getTemplateRegex(url) {
if (!url) {
url = '[^"\']+'; // Url can be anything except quotes
} else {
url = escapeRegExp(url);
}
var regexStr = [
'(["\']?)', // Optional quote around keyword, saved in group \1
'templateUrl', // Keyword
'\\1', // Match first quote if exists
'\\s*:\\s*', // Colon surrounded by any whitespace (including newline)
'(["\'])', // One quote around url, saved in \2
'(', url, ')', // Save the url in the third group
'\\2', // Match quote around url
].join('');
return new RegExp(regexStr, 'g');
}
function findUrls(contents) {
var templateUrls = getTemplateRegex();
var urls = [];
var match;
while ((match = templateUrls.exec(contents)) !== null) {
urls.push(match[3]);
}
return urls;
}
function buffer(options, file, cb) {
var contents = file.contents.toString();
var urls = findUrls(contents);
var cwd = options.cwd || file.cwd || process.cwd();
if (urls.length === 0) {
return cb(null, file);
}
urls.forEach(function(url) {
var template;
try {
template = fs.readFileSync(path.join(cwd, url)).toString();
} catch (e) {
gutil.log(NAME, gutil.colors.yellow('WARN'), 'unable to read', cwd, url);
}
if (template) {
template = template.replace(/\s*\n\s*/g, '');
contents = contents.replace(getTemplateRegex(url),
'template: \'' + template + '\'');
}
});
file.contents = new Buffer(contents);
cb(null, file);
}
module.exports = function(options) {
options = options || {};
return es.map(templates);
function templates(file, cb) {
if (file.isBuffer()) {
return buffer(options, file, cb);
}
if (file.isStream()) {
return cb(new gutil.PluginError(NAME, 'Streaming not supported'));
}
return cb(null, file);
}
};
| index.js | 'use strict';
var es = require('event-stream');
var gutil = require('gulp-util');
var fs = require('fs');
var NAME = 'gulp-ng-template-strings';
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
function getTemplateRegex(url) {
if (!url) {
url = '[^"\']+'; // Url can be anything except quotes
} else {
url = escapeRegExp(url);
}
var regexStr = [
'(["\']?)', // Optional quote around keyword, saved in group \1
'templateUrl', // Keyword
'\\1', // Match first quote if exists
'\\s*:\\s*', // Colon surrounded by any whitespace (including newline)
'(["\'])', // One quote around url, saved in \2
'(', url, ')', // Save the url in the third group
'\\2', // Match quote around url
].join('');
return new RegExp(regexStr, 'g');
}
function findUrls(contents) {
var templateUrls = getTemplateRegex();
var urls = [];
var match;
while ((match = templateUrls.exec(contents)) !== null) {
urls.push(match[3]);
}
return urls;
}
function buffer(file, cb) {
var contents = file.contents.toString();
var urls = findUrls(contents);
if (urls.length === 0) {
return cb(null, file);
}
urls.forEach(function(url) {
var template;
try {
template = fs.readFileSync(file.base + url).toString();
} catch (e) {
// Do nothing when file does not exist
}
if (template) {
template = template.replace(/\s*\n\s*/g, '');
contents = contents.replace(getTemplateRegex(url),
'template: \'' + template + '\'');
}
});
file.contents = new Buffer(contents);
cb(null, file);
}
function templates(file, cb) {
if (file.isBuffer()) {
return buffer(file, cb);
}
if (file.isStream()) {
return cb(new gutil.PluginError(NAME, 'Streaming not supported'));
}
return cb(null, file);
}
module.exports = function() {
return es.map(templates);
};
| log when file not found, add cwd option to override process.cwd
| index.js | log when file not found, add cwd option to override process.cwd | <ide><path>ndex.js
<ide> var es = require('event-stream');
<ide> var gutil = require('gulp-util');
<ide> var fs = require('fs');
<add>var path = require('path');
<ide> var NAME = 'gulp-ng-template-strings';
<ide>
<ide> function escapeRegExp(str) {
<ide> return urls;
<ide> }
<ide>
<del>function buffer(file, cb) {
<add>function buffer(options, file, cb) {
<ide> var contents = file.contents.toString();
<ide> var urls = findUrls(contents);
<add> var cwd = options.cwd || file.cwd || process.cwd();
<ide> if (urls.length === 0) {
<ide> return cb(null, file);
<ide> }
<ide> urls.forEach(function(url) {
<ide> var template;
<ide> try {
<del> template = fs.readFileSync(file.base + url).toString();
<add> template = fs.readFileSync(path.join(cwd, url)).toString();
<ide> } catch (e) {
<del> // Do nothing when file does not exist
<add> gutil.log(NAME, gutil.colors.yellow('WARN'), 'unable to read', cwd, url);
<ide> }
<ide> if (template) {
<ide> template = template.replace(/\s*\n\s*/g, '');
<ide> cb(null, file);
<ide> }
<ide>
<del>function templates(file, cb) {
<del> if (file.isBuffer()) {
<del> return buffer(file, cb);
<add>module.exports = function(options) {
<add> options = options || {};
<add> return es.map(templates);
<add>
<add> function templates(file, cb) {
<add> if (file.isBuffer()) {
<add> return buffer(options, file, cb);
<add> }
<add> if (file.isStream()) {
<add> return cb(new gutil.PluginError(NAME, 'Streaming not supported'));
<add> }
<add> return cb(null, file);
<ide> }
<del> if (file.isStream()) {
<del> return cb(new gutil.PluginError(NAME, 'Streaming not supported'));
<del> }
<del> return cb(null, file);
<del>}
<del>
<del>module.exports = function() {
<del> return es.map(templates);
<ide> }; |
|
Java | apache-2.0 | 509799095c1d9d04075fff61da52408f2f97db2a | 0 | aemay2/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,SingingTree/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir | package ca.uhn.fhir.jpa.migrate.tasks;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.jpa.migrate.DriverTypeEnum;
import ca.uhn.fhir.jpa.migrate.tasks.api.ISchemaInitializationProvider;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class SchemaInitializationProvider implements ISchemaInitializationProvider {
private final String mySchemaFileClassPath;
private final String mySchemaExistsIndicatorTable;
/**
*
* @param theSchemaFileClassPath pathname to script used to initialize schema
* @param theSchemaExistsIndicatorTable a table name we can use to determine if this schema has already been initialized
*/
public SchemaInitializationProvider(String theSchemaFileClassPath, String theSchemaExistsIndicatorTable) {
mySchemaFileClassPath = theSchemaFileClassPath;
mySchemaExistsIndicatorTable = theSchemaExistsIndicatorTable;
}
@Override
public List<String> getSqlStatements(DriverTypeEnum theDriverType) {
List<String> retval = new ArrayList<>();
String initScript;
initScript = mySchemaFileClassPath + "/" + theDriverType.getSchemaFilename();
try {
InputStream sqlFileInputStream = SchemaInitializationProvider.class.getResourceAsStream(initScript);
if (sqlFileInputStream == null) {
throw new ConfigurationException("Schema initialization script " + initScript + " not found on classpath");
}
// Assumes no escaped semicolons...
String[] statements = IOUtils.toString(sqlFileInputStream, Charsets.UTF_8).split("\\;");
for (String statement : statements) {
if (!statement.trim().isEmpty()) {
retval.add(statement);
}
}
} catch (IOException e) {
throw new ConfigurationException("Error reading schema initialization script " + initScript, e);
}
return retval;
}
@Override
public boolean equals(Object theO) {
if (this == theO) return true;
if (theO == null || getClass() != theO.getClass()) return false;
SchemaInitializationProvider that = (SchemaInitializationProvider) theO;
return this.getClass().getSimpleName() == that.getClass().getSimpleName();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(this.getClass().getSimpleName())
.toHashCode();
}
@Override
public String getSchemaExistsIndicatorTable() {
return mySchemaExistsIndicatorTable;
}
}
| hapi-fhir-jpaserver-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/tasks/SchemaInitializationProvider.java | package ca.uhn.fhir.jpa.migrate.tasks;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.jpa.migrate.DriverTypeEnum;
import ca.uhn.fhir.jpa.migrate.tasks.api.ISchemaInitializationProvider;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class SchemaInitializationProvider implements ISchemaInitializationProvider {
private final String mySchemaFileClassPath;
private final String mySchemaExistsIndicatorTable;
/**
*
* @param theSchemaFileClassPath pathname to script used to initialize schema
* @param theSchemaExistsIndicatorTable a table name we can use to determine if this schema has already been initialized
*/
public SchemaInitializationProvider(String theSchemaFileClassPath, String theSchemaExistsIndicatorTable) {
mySchemaFileClassPath = theSchemaFileClassPath;
mySchemaExistsIndicatorTable = theSchemaExistsIndicatorTable;
}
@Override
public List<String> getSqlStatements(DriverTypeEnum theDriverType) {
List<String> retval = new ArrayList<>();
String initScript;
initScript = mySchemaFileClassPath + "/" + theDriverType.getSchemaFilename();
try {
InputStream sqlFileInputStream = SchemaInitializationProvider.class.getResourceAsStream(initScript);
if (sqlFileInputStream == null) {
throw new ConfigurationException("Schema initialization script " + initScript + " not found on classpath");
}
// Assumes no escaped semicolons...
String[] statements = IOUtils.toString(sqlFileInputStream, Charsets.UTF_8).split("\\;");
for (String statement : statements) {
if (!statement.trim().isEmpty()) {
retval.add(statement);
}
}
} catch (IOException e) {
throw new ConfigurationException("Error reading schema initialization script " + initScript, e);
}
return retval;
}
@Override
public boolean equals(Object theO) {
if (this == theO) return true;
if (theO == null || getClass() != theO.getClass()) return false;
SchemaInitializationProvider that = (SchemaInitializationProvider) theO;
return size() == that.size();
}
private int size() {
return getSqlStatements(DriverTypeEnum.H2_EMBEDDED).size();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(size())
.toHashCode();
}
@Override
public String getSchemaExistsIndicatorTable() {
return mySchemaExistsIndicatorTable;
}
}
| don't hash on init script length since it will change. Hash based on class name.
| hapi-fhir-jpaserver-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/tasks/SchemaInitializationProvider.java | don't hash on init script length since it will change. Hash based on class name. | <ide><path>api-fhir-jpaserver-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/tasks/SchemaInitializationProvider.java
<ide>
<ide> SchemaInitializationProvider that = (SchemaInitializationProvider) theO;
<ide>
<del> return size() == that.size();
<del> }
<del>
<del> private int size() {
<del> return getSqlStatements(DriverTypeEnum.H2_EMBEDDED).size();
<add> return this.getClass().getSimpleName() == that.getClass().getSimpleName();
<ide> }
<ide>
<ide> @Override
<ide> public int hashCode() {
<ide> return new HashCodeBuilder(17, 37)
<del> .append(size())
<add> .append(this.getClass().getSimpleName())
<ide> .toHashCode();
<ide> }
<ide> |
|
Java | mit | 3b35625d5b706bd9f9f251e8b8b77f06aff5e0d3 | 0 | CECS429-SearchEngine/GuddenTheEngine | package model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
public class Indexer {
private HashMap<String, List<PositionalPosting>> index;
public Indexer() {
this.index = new HashMap<String, List<PositionalPosting>>();
}
public void addPosition(String term, int docId, int position) {
if (!containsTerm(term))
createTerm(term);
if (!containsDocId(term, docId))
addDocId(term, docId);
PositionalPosting posting = getRecentPosting(getPostings(term));
posting.addPosition(position);
}
public List<PositionalPosting> getPostings(String term) {
return this.index.get(term);
}
public int getTermCount() {
return this.index.size();
}
public String[] getDictionary() {
SortedSet<String> terms = new TreeSet<String>(this.index.keySet());
return terms.toArray(new String[terms.size()]);
}
private boolean containsTerm(String term) {
return this.index.containsKey(term);
}
private boolean containsDocId(String term, int docId) {
List<PositionalPosting> postingsList = getPostings(term);
int lastIndex = postingsList.size() - 1;
return !postingsList.isEmpty() && postingsList.get(lastIndex).getDocId() >= docId;
}
private void createTerm(String term) {
this.index.put(term, new ArrayList<PositionalPosting>());
}
private void addDocId(String term, int docId) {
List<PositionalPosting> postingsList = getPostings(term);
postingsList.add(new PositionalPosting(docId));
}
private PositionalPosting getRecentPosting(List<PositionalPosting> postingsList) {
int lastIndex = postingsList.size() - 1;
return postingsList.get(lastIndex);
}
public String toString() {
StringBuilder sb = new StringBuilder();
String[] dictionary = getDictionary();
for(int j = 0; j < dictionary.length; j++) {
List<PositionalPosting> ppList = getPostings(dictionary[j]);
sb.append(dictionary[j] + ":" + "\n");
for(PositionalPosting e : ppList) {
sb.append("Document ID " + e.getDocId() + ": ");
for(int l : e.getPositions())
sb.append(l + " ");
sb.append("\n");
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
Indexer indexer = new Indexer();
String[] exDoc = {"the","fox","jumped","over","the","fox"};
for(int x = 0; x < exDoc.length; x++) {
indexer.addPosition(exDoc[x], 0, x);
}
String[] dictionary = indexer.getDictionary();
for(int j = 0; j < dictionary.length; j++) {
List<PositionalPosting> ppList = indexer.getPostings(dictionary[j]);
System.out.print(dictionary[j] + " ");
for(PositionalPosting e : ppList) {
System.out.print(e.getDocId() + " ");
for(int l : e.getPositions())
System.out.print(l + " ");
System.out.println();
}
}
}
}
| Gudden/src/model/Indexer.java | package model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class Indexer {
private HashMap<String, List<PositionalPosting>> index;
public Indexer() {
this.index = new HashMap<String, List<PositionalPosting>>();
}
public void addPosition(String term, int docId, int position) {
if (!containsTerm(term))
createTerm(term);
if (!containsDocId(term, docId))
addDocId(term, docId);
PositionalPosting posting = getRecentPosting(getPostings(term));
posting.addPosition(position);
}
public List<PositionalPosting> getPostings(String term) {
return this.index.get(term);
}
public int getTermCount() {
return this.index.size();
}
public String[] getDictionary() {
String test[] = index.keySet().toArray(new String[index.size()]);
Arrays.sort(test);
return test;
}
private boolean containsTerm(String term) {
return this.index.containsKey(term);
}
private boolean containsDocId(String term, int docId) {
List<PositionalPosting> postingsList = getPostings(term);
int lastIndex = postingsList.size() - 1;
return !postingsList.isEmpty() && postingsList.get(lastIndex).getDocId() >= docId;
}
private void createTerm(String term) {
this.index.put(term, new ArrayList<PositionalPosting>());
}
private void addDocId(String term, int docId) {
List<PositionalPosting> postingsList = getPostings(term);
postingsList.add(new PositionalPosting(docId));
}
private PositionalPosting getRecentPosting(List<PositionalPosting> postingsList) {
int lastIndex = postingsList.size() - 1;
return postingsList.get(lastIndex);
}
public String toString() {
StringBuilder sb = new StringBuilder();
String[] dictionary = getDictionary();
for(int j = 0; j < dictionary.length; j++) {
List<PositionalPosting> ppList = getPostings(dictionary[j]);
sb.append(dictionary[j] + ":" + "\n");
for(PositionalPosting e : ppList) {
sb.append("Document ID " + e.getDocId() + ": ");
for(int l : e.getPositions())
sb.append(l + " ");
sb.append("\n");
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
Indexer indexer = new Indexer();
String[] exDoc = {"the","fox","jumped","over","the","fox"};
for(int x = 0; x < exDoc.length; x++) {
indexer.addPosition(exDoc[x], 0, x);
}
String[] dictionary = indexer.getDictionary();
for(int j = 0; j < dictionary.length; j++) {
List<PositionalPosting> ppList = indexer.getPostings(dictionary[j]);
System.out.print(dictionary[j] + " ");
for(PositionalPosting e : ppList) {
System.out.print(e.getDocId() + " ");
for(int l : e.getPositions())
System.out.print(l + " ");
System.out.println();
}
}
}
}
| Updated getDictionary to use sortedset.
| Gudden/src/model/Indexer.java | Updated getDictionary to use sortedset. | <ide><path>udden/src/model/Indexer.java
<ide> import java.util.Arrays;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<add>import java.util.SortedSet;
<add>import java.util.TreeSet;
<ide>
<ide> public class Indexer {
<ide>
<ide> }
<ide>
<ide> public String[] getDictionary() {
<del> String test[] = index.keySet().toArray(new String[index.size()]);
<del> Arrays.sort(test);
<del> return test;
<add> SortedSet<String> terms = new TreeSet<String>(this.index.keySet());
<add> return terms.toArray(new String[terms.size()]);
<ide> }
<ide>
<ide> private boolean containsTerm(String term) { |
|
Java | apache-2.0 | 379881e69bd7e93f11cfa13b415afe14be8634f6 | 0 | milleruntime/accumulo,ivakegg/accumulo,mikewalch/accumulo,lstav/accumulo,phrocker/accumulo-1,mikewalch/accumulo,ctubbsii/accumulo,adamjshook/accumulo,keith-turner/accumulo,milleruntime/accumulo,dhutchis/accumulo,lstav/accumulo,ctubbsii/accumulo,adamjshook/accumulo,mikewalch/accumulo,ivakegg/accumulo,mikewalch/accumulo,adamjshook/accumulo,lstav/accumulo,apache/accumulo,mjwall/accumulo,apache/accumulo,ivakegg/accumulo,phrocker/accumulo-1,dhutchis/accumulo,ivakegg/accumulo,lstav/accumulo,joshelser/accumulo,mjwall/accumulo,adamjshook/accumulo,lstav/accumulo,milleruntime/accumulo,dhutchis/accumulo,mjwall/accumulo,lstav/accumulo,keith-turner/accumulo,mjwall/accumulo,lstav/accumulo,dhutchis/accumulo,mikewalch/accumulo,joshelser/accumulo,joshelser/accumulo,phrocker/accumulo-1,joshelser/accumulo,mikewalch/accumulo,mjwall/accumulo,milleruntime/accumulo,phrocker/accumulo-1,joshelser/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,keith-turner/accumulo,ctubbsii/accumulo,joshelser/accumulo,adamjshook/accumulo,keith-turner/accumulo,mjwall/accumulo,dhutchis/accumulo,ctubbsii/accumulo,dhutchis/accumulo,ivakegg/accumulo,dhutchis/accumulo,apache/accumulo,ivakegg/accumulo,dhutchis/accumulo,dhutchis/accumulo,adamjshook/accumulo,milleruntime/accumulo,apache/accumulo,joshelser/accumulo,phrocker/accumulo-1,milleruntime/accumulo,ivakegg/accumulo,ctubbsii/accumulo,keith-turner/accumulo,adamjshook/accumulo,adamjshook/accumulo,keith-turner/accumulo,mikewalch/accumulo,keith-turner/accumulo,joshelser/accumulo,apache/accumulo,mjwall/accumulo,milleruntime/accumulo,adamjshook/accumulo,mikewalch/accumulo,phrocker/accumulo-1,apache/accumulo,apache/accumulo | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.client.mapreduce.lib.util;
import static org.apache.accumulo.core.util.ArgumentChecker.notNull;
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.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.ClientSideIteratorScanner;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.IsolatedScanner;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.RowIterator;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.impl.Tables;
import org.apache.accumulo.core.client.impl.TabletLocator;
import org.apache.accumulo.core.client.mapreduce.InputTableConfig;
import org.apache.accumulo.core.client.mock.MockTabletLocator;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.PartialKey;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.TextUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.StringUtils;
import com.google.common.collect.Maps;
/**
* @since 1.5.0
*/
public class InputConfigurator extends ConfiguratorBase {
/**
* Configuration keys for {@link Scanner}.
*
* @since 1.5.0
*/
public static enum ScanOpts {
TABLE_NAME, AUTHORIZATIONS, RANGES, COLUMNS, ITERATORS, TABLE_CONFIGS
}
/**
* Configuration keys for various features.
*
* @since 1.5.0
*/
public static enum Features {
AUTO_ADJUST_RANGES, SCAN_ISOLATION, USE_LOCAL_ITERATORS, SCAN_OFFLINE
}
/**
* Sets the name of the input table, over which this job will scan.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param tableName
* the table to use when the tablename is null in the write call
* @since 1.5.0
*/
public static void setInputTableName(Class<?> implementingClass, Configuration conf, String tableName) {
notNull(tableName);
conf.set(enumToConfKey(implementingClass, ScanOpts.TABLE_NAME), tableName);
}
/**
* Sets the name of the input table, over which this job will scan.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @since 1.5.0
*/
public static String getInputTableName(Class<?> implementingClass, Configuration conf) {
return conf.get(enumToConfKey(implementingClass, ScanOpts.TABLE_NAME));
}
/**
* Sets the {@link Authorizations} used to scan. Must be a subset of the user's authorization. Defaults to the empty set.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param auths
* the user's authorizations
* @since 1.5.0
*/
public static void setScanAuthorizations(Class<?> implementingClass, Configuration conf, Authorizations auths) {
if (auths != null && !auths.isEmpty())
conf.set(enumToConfKey(implementingClass, ScanOpts.AUTHORIZATIONS), auths.serialize());
}
/**
* Gets the authorizations to set for the scans from the configuration.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return the Accumulo scan authorizations
* @since 1.5.0
* @see #setScanAuthorizations(Class, Configuration, Authorizations)
*/
public static Authorizations getScanAuthorizations(Class<?> implementingClass, Configuration conf) {
String authString = conf.get(enumToConfKey(implementingClass, ScanOpts.AUTHORIZATIONS));
return authString == null ? Authorizations.EMPTY : new Authorizations(authString.getBytes());
}
/**
* Sets the input ranges to scan on all input tables for this job. If not set, the entire table will be scanned.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param ranges
* the ranges that will be mapped over
* @throws IllegalArgumentException
* if the ranges cannot be encoded into base 64
* @since 1.5.0
*/
public static void setRanges(Class<?> implementingClass, Configuration conf, Collection<Range> ranges) {
notNull(ranges);
ArrayList<String> rangeStrings = new ArrayList<String>(ranges.size());
try {
for (Range r : ranges) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
r.write(new DataOutputStream(baos));
rangeStrings.add(new String(Base64.encodeBase64(baos.toByteArray())));
}
conf.setStrings(enumToConfKey(implementingClass, ScanOpts.RANGES), rangeStrings.toArray(new String[0]));
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to encode ranges to Base64", ex);
}
}
/**
* Gets the ranges to scan over from a job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return the ranges
* @throws IOException
* if the ranges have been encoded improperly
* @since 1.5.0
* @see #setRanges(Class, Configuration, Collection)
*/
public static List<Range> getRanges(Class<?> implementingClass, Configuration conf) throws IOException {
Collection<String> encodedRanges = conf.getStringCollection(enumToConfKey(implementingClass, ScanOpts.RANGES));
List<Range> ranges = new ArrayList<Range>();
for (String rangeString : encodedRanges) {
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(rangeString.getBytes()));
Range range = new Range();
range.readFields(new DataInputStream(bais));
ranges.add(range);
}
return ranges;
}
/**
* Gets a list of the iterator settings (for iterators to apply to a scanner) from this configuration.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return a list of iterators
* @since 1.5.0
* @see #addIterator(Class, Configuration, IteratorSetting)
*/
public static List<IteratorSetting> getIterators(Class<?> implementingClass, Configuration conf) {
String iterators = conf.get(enumToConfKey(implementingClass, ScanOpts.ITERATORS));
// If no iterators are present, return an empty list
if (iterators == null || iterators.isEmpty())
return new ArrayList<IteratorSetting>();
// Compose the set of iterators encoded in the job configuration
StringTokenizer tokens = new StringTokenizer(iterators, StringUtils.COMMA_STR);
List<IteratorSetting> list = new ArrayList<IteratorSetting>();
try {
while (tokens.hasMoreTokens()) {
String itstring = tokens.nextToken();
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(itstring.getBytes()));
list.add(new IteratorSetting(new DataInputStream(bais)));
bais.close();
}
} catch (IOException e) {
throw new IllegalArgumentException("couldn't decode iterator settings");
}
return list;
}
/**
* Restricts the columns that will be mapped over for the single input table on this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param columnFamilyColumnQualifierPairs
* a pair of {@link Text} objects corresponding to column family and column qualifier. If the column qualifier is null, the entire column family is
* selected. An empty set is the default and is equivalent to scanning the all columns.
* @throws IllegalArgumentException
* if the column family is null
* @since 1.5.0
*/
public static void fetchColumns(Class<?> implementingClass, Configuration conf, Collection<Pair<Text,Text>> columnFamilyColumnQualifierPairs) {
notNull(columnFamilyColumnQualifierPairs);
String[] columnStrings = serializeColumns(columnFamilyColumnQualifierPairs);
conf.setStrings(enumToConfKey(implementingClass, ScanOpts.COLUMNS), columnStrings);
}
public static String[] serializeColumns(Collection<Pair<Text,Text>> columnFamilyColumnQualifierPairs) {
notNull(columnFamilyColumnQualifierPairs);
ArrayList<String> columnStrings = new ArrayList<String>(columnFamilyColumnQualifierPairs.size());
for (Pair<Text,Text> column : columnFamilyColumnQualifierPairs) {
if (column.getFirst() == null)
throw new IllegalArgumentException("Column family can not be null");
String col = new String(Base64.encodeBase64(TextUtil.getBytes(column.getFirst())), Constants.UTF8);
if (column.getSecond() != null)
col += ":" + new String(Base64.encodeBase64(TextUtil.getBytes(column.getSecond())), Constants.UTF8);
columnStrings.add(col);
}
return columnStrings.toArray(new String[0]);
}
/**
* Gets the columns to be mapped over from this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return a set of columns
* @since 1.5.0
* @see #fetchColumns(Class, Configuration, Collection)
*/
public static Set<Pair<Text,Text>> getFetchedColumns(Class<?> implementingClass, Configuration conf) {
notNull(conf);
return deserializeFetchedColumns(conf.getStringCollection(enumToConfKey(implementingClass, ScanOpts.COLUMNS)));
}
public static Set<Pair<Text,Text>> deserializeFetchedColumns(Collection<String> serialized) {
Set<Pair<Text,Text>> columns = new HashSet<Pair<Text,Text>>();
if (null == serialized) {
return columns;
}
for (String col : serialized) {
int idx = col.indexOf(":");
Text cf = new Text(idx < 0 ? Base64.decodeBase64(col.getBytes(Constants.UTF8)) : Base64.decodeBase64(col.substring(0, idx).getBytes(Constants.UTF8)));
Text cq = idx < 0 ? null : new Text(Base64.decodeBase64(col.substring(idx + 1).getBytes()));
columns.add(new Pair<Text,Text>(cf, cq));
}
return columns;
}
/**
* Encode an iterator on the input for the single input table associated with this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param cfg
* the configuration of the iterator
* @throws IllegalArgumentException
* if the iterator can't be serialized into the configuration
* @since 1.5.0
*/
public static void addIterator(Class<?> implementingClass, Configuration conf, IteratorSetting cfg) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String newIter;
try {
cfg.write(new DataOutputStream(baos));
newIter = new String(Base64.encodeBase64(baos.toByteArray()), Constants.UTF8);
baos.close();
} catch (IOException e) {
throw new IllegalArgumentException("unable to serialize IteratorSetting");
}
String confKey = enumToConfKey(implementingClass, ScanOpts.ITERATORS);
String iterators = conf.get(confKey);
// No iterators specified yet, create a new string
if (iterators == null || iterators.isEmpty()) {
iterators = newIter;
} else {
// append the next iterator & reset
iterators = iterators.concat(StringUtils.COMMA_STR + newIter);
}
// Store the iterators w/ the job
conf.set(confKey, iterators);
}
/**
* Controls the automatic adjustment of ranges for this job. This feature merges overlapping ranges, then splits them to align with tablet boundaries.
* Disabling this feature will cause exactly one Map task to be created for each specified range. The default setting is enabled. *
*
* <p>
* By default, this feature is <b>enabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @see #setRanges(Class, Configuration, Collection)
* @since 1.5.0
*/
public static void setAutoAdjustRanges(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.AUTO_ADJUST_RANGES), enableFeature);
}
/**
* Determines whether a configuration has auto-adjust ranges enabled.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return false if the feature is disabled, true otherwise
* @since 1.5.0
* @see #setAutoAdjustRanges(Class, Configuration, boolean)
*/
public static Boolean getAutoAdjustRanges(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.AUTO_ADJUST_RANGES), true);
}
/**
* Controls the use of the {@link IsolatedScanner} in this job.
*
* <p>
* By default, this feature is <b>disabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @since 1.5.0
*/
public static void setScanIsolation(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.SCAN_ISOLATION), enableFeature);
}
/**
* Determines whether a configuration has isolation enabled.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return true if the feature is enabled, false otherwise
* @since 1.5.0
* @see #setScanIsolation(Class, Configuration, boolean)
*/
public static Boolean isIsolated(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.SCAN_ISOLATION), false);
}
/**
* Controls the use of the {@link ClientSideIteratorScanner} in this job. Enabling this feature will cause the iterator stack to be constructed within the Map
* task, rather than within the Accumulo TServer. To use this feature, all classes needed for those iterators must be available on the classpath for the task.
*
* <p>
* By default, this feature is <b>disabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @since 1.5.0
*/
public static void setLocalIterators(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.USE_LOCAL_ITERATORS), enableFeature);
}
/**
* Determines whether a configuration uses local iterators.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return true if the feature is enabled, false otherwise
* @since 1.5.0
* @see #setLocalIterators(Class, Configuration, boolean)
*/
public static Boolean usesLocalIterators(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.USE_LOCAL_ITERATORS), false);
}
/**
* <p>
* Enable reading offline tables. By default, this feature is disabled and only online tables are scanned. This will make the map reduce job directly read the
* table's files. If the table is not offline, then the job will fail. If the table comes online during the map reduce job, it is likely that the job will
* fail.
*
* <p>
* To use this option, the map reduce user will need access to read the Accumulo directory in HDFS.
*
* <p>
* Reading the offline table will create the scan time iterator stack in the map process. So any iterators that are configured for the table will need to be
* on the mapper's classpath. The accumulo-site.xml may need to be on the mapper's classpath if HDFS or the Accumulo directory in HDFS are non-standard.
*
* <p>
* One way to use this feature is to clone a table, take the clone offline, and use the clone as the input table for a map reduce job. If you plan to map
* reduce over the data many times, it may be better to the compact the table, clone it, take it offline, and use the clone for all map reduce jobs. The
* reason to do this is that compaction will reduce each tablet in the table to one file, and it is faster to read from one file.
*
* <p>
* There are two possible advantages to reading a tables file directly out of HDFS. First, you may see better read performance. Second, it will support
* speculative execution better. When reading an online table speculative execution can put more load on an already slow tablet server.
*
* <p>
* By default, this feature is <b>disabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @since 1.5.0
*/
public static void setOfflineTableScan(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.SCAN_OFFLINE), enableFeature);
}
/**
* Determines whether a configuration has the offline table scan feature enabled.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return true if the feature is enabled, false otherwise
* @since 1.5.0
* @see #setOfflineTableScan(Class, Configuration, boolean)
*/
public static Boolean isOfflineScan(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.SCAN_OFFLINE), false);
}
/**
* Sets configurations for multiple tables at a time.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param configs
* an array of {@link InputTableConfig} objects to associate with the job
* @since 1.6.0
*/
public static void setInputTableConfigs(Class<?> implementingClass, Configuration conf, Map<String,InputTableConfig> configs) {
MapWritable mapWritable = new MapWritable();
for (Map.Entry<String,InputTableConfig> tableConfig : configs.entrySet())
mapWritable.put(new Text(tableConfig.getKey()), tableConfig.getValue());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
mapWritable.write(new DataOutputStream(baos));
} catch (IOException e) {
throw new IllegalStateException("Table configuration could not be serialized.");
}
String confKey = enumToConfKey(implementingClass, ScanOpts.TABLE_CONFIGS);
conf.set(confKey, new String(Base64.encodeBase64(baos.toByteArray())));
}
/**
* Returns all {@link InputTableConfig} objects associated with this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return all of the table query configs for the job
* @since 1.6.0
*/
public static Map<String,InputTableConfig> getInputTableConfigs(Class<?> implementingClass, Configuration conf) {
Map<String,InputTableConfig> configs = new HashMap<String,InputTableConfig>();
Map.Entry<String,InputTableConfig> defaultConfig = getDefaultInputTableConfig(implementingClass, conf);
if (defaultConfig != null)
configs.put(defaultConfig.getKey(), defaultConfig.getValue());
String configString = conf.get(enumToConfKey(implementingClass, ScanOpts.TABLE_CONFIGS));
MapWritable mapWritable = new MapWritable();
if (configString != null) {
try {
byte[] bytes = Base64.decodeBase64(configString.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
mapWritable.readFields(new DataInputStream(bais));
bais.close();
} catch (IOException e) {
throw new IllegalStateException("The table query configurations could not be deserialized from the given configuration");
}
}
for (Map.Entry<Writable,Writable> entry : mapWritable.entrySet())
configs.put(((Text) entry.getKey()).toString(), (InputTableConfig) entry.getValue());
return configs;
}
/**
* Returns the {@link InputTableConfig} for the given table
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param tableName
* the table name for which to fetch the table query config
* @return the table query config for the given table name (if it exists) and null if it does not
* @since 1.6.0
*/
public static InputTableConfig getInputTableConfig(Class<?> implementingClass, Configuration conf, String tableName) {
Map<String,InputTableConfig> queryConfigs = getInputTableConfigs(implementingClass, conf);
return queryConfigs.get(tableName);
}
/**
* Initializes an Accumulo {@link TabletLocator} based on the configuration.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param tableId
* The table id for which to initialize the {@link TabletLocator}
* @return an Accumulo tablet locator
* @throws TableNotFoundException
* if the table name set on the configuration doesn't exist
* @since 1.5.0
*/
public static TabletLocator getTabletLocator(Class<?> implementingClass, Configuration conf, String tableId) throws TableNotFoundException {
String instanceType = conf.get(enumToConfKey(implementingClass, InstanceOpts.TYPE));
if ("MockInstance".equals(instanceType))
return new MockTabletLocator();
Instance instance = getInstance(implementingClass, conf);
return TabletLocator.getLocator(instance, new Text(tableId));
}
// InputFormat doesn't have the equivalent of OutputFormat's checkOutputSpecs(JobContext job)
/**
* Check whether a configuration is fully configured to be used with an Accumulo {@link org.apache.hadoop.mapreduce.InputFormat}.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @throws IOException
* if the context is improperly configured
* @since 1.5.0
*/
public static void validateOptions(Class<?> implementingClass, Configuration conf) throws IOException {
Map<String,InputTableConfig> inputTableConfigs = getInputTableConfigs(implementingClass, conf);
if (!isConnectorInfoSet(implementingClass, conf))
throw new IOException("Input info has not been set.");
String instanceKey = conf.get(enumToConfKey(implementingClass, InstanceOpts.TYPE));
if (!"MockInstance".equals(instanceKey) && !"ZooKeeperInstance".equals(instanceKey))
throw new IOException("Instance info has not been set.");
// validate that we can connect as configured
Instance inst = getInstance(implementingClass, conf);
try {
String principal = getPrincipal(implementingClass, conf);
AuthenticationToken token = getAuthenticationToken(implementingClass, conf);
Connector c = inst.getConnector(principal, token);
if (!c.securityOperations().authenticateUser(principal, token))
throw new IOException("Unable to authenticate user");
if (getInputTableConfigs(implementingClass, conf).size() == 0)
throw new IOException("No table set.");
for (Map.Entry<String,InputTableConfig> tableConfig : inputTableConfigs.entrySet()) {
if (!c.securityOperations().hasTablePermission(getPrincipal(implementingClass, conf), tableConfig.getKey(), TablePermission.READ))
throw new IOException("Unable to access table");
}
for (Map.Entry<String,InputTableConfig> tableConfigEntry : inputTableConfigs.entrySet()) {
InputTableConfig tableConfig = tableConfigEntry.getValue();
if (!tableConfig.shouldUseLocalIterators()) {
if (tableConfig.getIterators() != null) {
for (IteratorSetting iter : tableConfig.getIterators()) {
if (!c.tableOperations().testClassLoad(tableConfigEntry.getKey(), iter.getIteratorClass(), SortedKeyValueIterator.class.getName()))
throw new AccumuloException("Servers are unable to load " + iter.getIteratorClass() + " as a " + SortedKeyValueIterator.class.getName());
}
}
}
}
} catch (AccumuloException e) {
throw new IOException(e);
} catch (AccumuloSecurityException e) {
throw new IOException(e);
} catch (TableNotFoundException e) {
throw new IOException(e);
} finally {
inst.close();
}
}
/**
* Returns the {@link org.apache.accumulo.core.client.mapreduce.InputTableConfig} for the configuration based on the properties set using the single-table
* input methods.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop instance for which to retrieve the configuration
* @return the config object built from the single input table properties set on the job
* @since 1.6.0
*/
protected static Map.Entry<String,InputTableConfig> getDefaultInputTableConfig(Class<?> implementingClass, Configuration conf) {
String tableName = getInputTableName(implementingClass, conf);
if (tableName != null) {
InputTableConfig queryConfig = new InputTableConfig();
List<IteratorSetting> itrs = getIterators(implementingClass, conf);
if (itrs != null)
queryConfig.setIterators(itrs);
Set<Pair<Text,Text>> columns = getFetchedColumns(implementingClass, conf);
if (columns != null)
queryConfig.fetchColumns(columns);
List<Range> ranges = null;
try {
ranges = getRanges(implementingClass, conf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (ranges != null)
queryConfig.setRanges(ranges);
queryConfig.setAutoAdjustRanges(getAutoAdjustRanges(implementingClass, conf)).setUseIsolatedScanners(isIsolated(implementingClass, conf))
.setUseLocalIterators(usesLocalIterators(implementingClass, conf)).setOfflineScan(isOfflineScan(implementingClass, conf));
return Maps.immutableEntry(tableName, queryConfig);
}
return null;
}
public static Map<String,Map<KeyExtent,List<Range>>> binOffline(String tableId, List<Range> ranges, Instance instance, Connector conn)
throws AccumuloException, TableNotFoundException {
Map<String,Map<KeyExtent,List<Range>>> binnedRanges = new HashMap<String,Map<KeyExtent,List<Range>>>();
if (Tables.getTableState(instance, tableId) != TableState.OFFLINE) {
Tables.clearCache(instance);
if (Tables.getTableState(instance, tableId) != TableState.OFFLINE) {
throw new AccumuloException("Table is online tableId:" + tableId + " cannot scan table in offline mode ");
}
}
for (Range range : ranges) {
Text startRow;
if (range.getStartKey() != null)
startRow = range.getStartKey().getRow();
else
startRow = new Text();
Range metadataRange = new Range(new KeyExtent(new Text(tableId), startRow, null).getMetadataEntry(), true, null, false);
Scanner scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
MetadataSchema.TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.fetch(scanner);
scanner.fetchColumnFamily(MetadataSchema.TabletsSection.LastLocationColumnFamily.NAME);
scanner.fetchColumnFamily(MetadataSchema.TabletsSection.CurrentLocationColumnFamily.NAME);
scanner.fetchColumnFamily(MetadataSchema.TabletsSection.FutureLocationColumnFamily.NAME);
scanner.setRange(metadataRange);
RowIterator rowIter = new RowIterator(scanner);
KeyExtent lastExtent = null;
while (rowIter.hasNext()) {
Iterator<Map.Entry<Key,Value>> row = rowIter.next();
String last = "";
KeyExtent extent = null;
String location = null;
while (row.hasNext()) {
Map.Entry<Key,Value> entry = row.next();
Key key = entry.getKey();
if (key.getColumnFamily().equals(MetadataSchema.TabletsSection.LastLocationColumnFamily.NAME)) {
last = entry.getValue().toString();
}
if (key.getColumnFamily().equals(MetadataSchema.TabletsSection.CurrentLocationColumnFamily.NAME)
|| key.getColumnFamily().equals(MetadataSchema.TabletsSection.FutureLocationColumnFamily.NAME)) {
location = entry.getValue().toString();
}
if (MetadataSchema.TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.hasColumns(key)) {
extent = new KeyExtent(key.getRow(), entry.getValue());
}
}
if (location != null)
return null;
if (!extent.getTableId().toString().equals(tableId)) {
throw new AccumuloException("Saw unexpected table Id " + tableId + " " + extent);
}
if (lastExtent != null && !extent.isPreviousExtent(lastExtent)) {
throw new AccumuloException(" " + lastExtent + " is not previous extent " + extent);
}
Map<KeyExtent,List<Range>> tabletRanges = binnedRanges.get(last);
if (tabletRanges == null) {
tabletRanges = new HashMap<KeyExtent,List<Range>>();
binnedRanges.put(last, tabletRanges);
}
List<Range> rangeList = tabletRanges.get(extent);
if (rangeList == null) {
rangeList = new ArrayList<Range>();
tabletRanges.put(extent, rangeList);
}
rangeList.add(range);
if (extent.getEndRow() == null || range.afterEndKey(new Key(extent.getEndRow()).followingKey(PartialKey.ROW))) {
break;
}
lastExtent = extent;
}
}
return binnedRanges;
}
}
| core/src/main/java/org/apache/accumulo/core/client/mapreduce/lib/util/InputConfigurator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.client.mapreduce.lib.util;
import static org.apache.accumulo.core.util.ArgumentChecker.notNull;
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.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.ClientSideIteratorScanner;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.IsolatedScanner;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.RowIterator;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.impl.Tables;
import org.apache.accumulo.core.client.impl.TabletLocator;
import org.apache.accumulo.core.client.mapreduce.InputTableConfig;
import org.apache.accumulo.core.client.mock.MockTabletLocator;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.PartialKey;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.TextUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.StringUtils;
import com.google.common.collect.Maps;
/**
* @since 1.5.0
*/
public class InputConfigurator extends ConfiguratorBase {
/**
* Configuration keys for {@link Scanner}.
*
* @since 1.5.0
*/
public static enum ScanOpts {
TABLE_NAME, AUTHORIZATIONS, RANGES, COLUMNS, ITERATORS, TABLE_CONFIGS
}
/**
* Configuration keys for various features.
*
* @since 1.5.0
*/
public static enum Features {
AUTO_ADJUST_RANGES, SCAN_ISOLATION, USE_LOCAL_ITERATORS, SCAN_OFFLINE
}
/**
* Sets the name of the input table, over which this job will scan.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param tableName
* the table to use when the tablename is null in the write call
* @since 1.5.0
*/
public static void setInputTableName(Class<?> implementingClass, Configuration conf, String tableName) {
notNull(tableName);
conf.set(enumToConfKey(implementingClass, ScanOpts.TABLE_NAME), tableName);
}
/**
* Sets the name of the input table, over which this job will scan.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @since 1.5.0
*/
public static String getInputTableName(Class<?> implementingClass, Configuration conf) {
return conf.get(enumToConfKey(implementingClass, ScanOpts.TABLE_NAME));
}
/**
* Sets the {@link Authorizations} used to scan. Must be a subset of the user's authorization. Defaults to the empty set.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param auths
* the user's authorizations
* @since 1.5.0
*/
public static void setScanAuthorizations(Class<?> implementingClass, Configuration conf, Authorizations auths) {
if (auths != null && !auths.isEmpty())
conf.set(enumToConfKey(implementingClass, ScanOpts.AUTHORIZATIONS), auths.serialize());
}
/**
* Gets the authorizations to set for the scans from the configuration.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return the Accumulo scan authorizations
* @since 1.5.0
* @see #setScanAuthorizations(Class, Configuration, Authorizations)
*/
public static Authorizations getScanAuthorizations(Class<?> implementingClass, Configuration conf) {
String authString = conf.get(enumToConfKey(implementingClass, ScanOpts.AUTHORIZATIONS));
return authString == null ? Authorizations.EMPTY : new Authorizations(authString.getBytes());
}
/**
* Sets the input ranges to scan on all input tables for this job. If not set, the entire table will be scanned.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param ranges
* the ranges that will be mapped over
* @throws IllegalArgumentException
* if the ranges cannot be encoded into base 64
* @since 1.5.0
*/
public static void setRanges(Class<?> implementingClass, Configuration conf, Collection<Range> ranges) {
notNull(ranges);
ArrayList<String> rangeStrings = new ArrayList<String>(ranges.size());
try {
for (Range r : ranges) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
r.write(new DataOutputStream(baos));
rangeStrings.add(new String(Base64.encodeBase64(baos.toByteArray())));
}
conf.setStrings(enumToConfKey(implementingClass, ScanOpts.RANGES), rangeStrings.toArray(new String[0]));
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to encode ranges to Base64", ex);
}
}
/**
* Gets the ranges to scan over from a job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return the ranges
* @throws IOException
* if the ranges have been encoded improperly
* @since 1.5.0
* @see #setRanges(Class, Configuration, Collection)
*/
public static List<Range> getRanges(Class<?> implementingClass, Configuration conf) throws IOException {
Collection<String> encodedRanges = conf.getStringCollection(enumToConfKey(implementingClass, ScanOpts.RANGES));
List<Range> ranges = new ArrayList<Range>();
for (String rangeString : encodedRanges) {
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(rangeString.getBytes()));
Range range = new Range();
range.readFields(new DataInputStream(bais));
ranges.add(range);
}
return ranges;
}
/**
* Gets a list of the iterator settings (for iterators to apply to a scanner) from this configuration.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return a list of iterators
* @since 1.5.0
* @see #addIterator(Class, Configuration, IteratorSetting)
*/
public static List<IteratorSetting> getIterators(Class<?> implementingClass, Configuration conf) {
String iterators = conf.get(enumToConfKey(implementingClass, ScanOpts.ITERATORS));
// If no iterators are present, return an empty list
if (iterators == null || iterators.isEmpty())
return new ArrayList<IteratorSetting>();
// Compose the set of iterators encoded in the job configuration
StringTokenizer tokens = new StringTokenizer(iterators, StringUtils.COMMA_STR);
List<IteratorSetting> list = new ArrayList<IteratorSetting>();
try {
while (tokens.hasMoreTokens()) {
String itstring = tokens.nextToken();
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(itstring.getBytes()));
list.add(new IteratorSetting(new DataInputStream(bais)));
bais.close();
}
} catch (IOException e) {
throw new IllegalArgumentException("couldn't decode iterator settings");
}
return list;
}
/**
* Restricts the columns that will be mapped over for the single input table on this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param columnFamilyColumnQualifierPairs
* a pair of {@link Text} objects corresponding to column family and column qualifier. If the column qualifier is null, the entire column family is
* selected. An empty set is the default and is equivalent to scanning the all columns.
* @throws IllegalArgumentException
* if the column family is null
* @since 1.5.0
*/
public static void fetchColumns(Class<?> implementingClass, Configuration conf, Collection<Pair<Text,Text>> columnFamilyColumnQualifierPairs) {
notNull(columnFamilyColumnQualifierPairs);
String[] columnStrings = serializeColumns(columnFamilyColumnQualifierPairs);
conf.setStrings(enumToConfKey(implementingClass, ScanOpts.COLUMNS), columnStrings);
}
public static String[] serializeColumns(Collection<Pair<Text,Text>> columnFamilyColumnQualifierPairs) {
notNull(columnFamilyColumnQualifierPairs);
ArrayList<String> columnStrings = new ArrayList<String>(columnFamilyColumnQualifierPairs.size());
for (Pair<Text,Text> column : columnFamilyColumnQualifierPairs) {
if (column.getFirst() == null)
throw new IllegalArgumentException("Column family can not be null");
String col = new String(Base64.encodeBase64(TextUtil.getBytes(column.getFirst())), Constants.UTF8);
if (column.getSecond() != null)
col += ":" + new String(Base64.encodeBase64(TextUtil.getBytes(column.getSecond())), Constants.UTF8);
columnStrings.add(col);
}
return columnStrings.toArray(new String[0]);
}
/**
* Gets the columns to be mapped over from this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return a set of columns
* @since 1.5.0
* @see #fetchColumns(Class, Configuration, Collection)
*/
public static Set<Pair<Text,Text>> getFetchedColumns(Class<?> implementingClass, Configuration conf) {
notNull(conf);
return deserializeFetchedColumns(conf.getStringCollection(enumToConfKey(implementingClass, ScanOpts.COLUMNS)));
}
public static Set<Pair<Text,Text>> deserializeFetchedColumns(Collection<String> serialized) {
Set<Pair<Text,Text>> columns = new HashSet<Pair<Text,Text>>();
if (null == serialized) {
return columns;
}
for (String col : serialized) {
int idx = col.indexOf(":");
Text cf = new Text(idx < 0 ? Base64.decodeBase64(col.getBytes(Constants.UTF8)) : Base64.decodeBase64(col.substring(0, idx).getBytes(Constants.UTF8)));
Text cq = idx < 0 ? null : new Text(Base64.decodeBase64(col.substring(idx + 1).getBytes()));
columns.add(new Pair<Text,Text>(cf, cq));
}
return columns;
}
/**
* Encode an iterator on the input for the single input table associated with this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param cfg
* the configuration of the iterator
* @throws IllegalArgumentException
* if the iterator can't be serialized into the configuration
* @since 1.5.0
*/
public static void addIterator(Class<?> implementingClass, Configuration conf, IteratorSetting cfg) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String newIter;
try {
cfg.write(new DataOutputStream(baos));
newIter = new String(Base64.encodeBase64(baos.toByteArray()), Constants.UTF8);
baos.close();
} catch (IOException e) {
throw new IllegalArgumentException("unable to serialize IteratorSetting");
}
String confKey = enumToConfKey(implementingClass, ScanOpts.ITERATORS);
String iterators = conf.get(confKey);
// No iterators specified yet, create a new string
if (iterators == null || iterators.isEmpty()) {
iterators = newIter;
} else {
// append the next iterator & reset
iterators = iterators.concat(StringUtils.COMMA_STR + newIter);
}
// Store the iterators w/ the job
conf.set(confKey, iterators);
}
/**
* Controls the automatic adjustment of ranges for this job. This feature merges overlapping ranges, then splits them to align with tablet boundaries.
* Disabling this feature will cause exactly one Map task to be created for each specified range. The default setting is enabled. *
*
* <p>
* By default, this feature is <b>enabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @see #setRanges(Class, Configuration, Collection)
* @since 1.5.0
*/
public static void setAutoAdjustRanges(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.AUTO_ADJUST_RANGES), enableFeature);
}
/**
* Determines whether a configuration has auto-adjust ranges enabled.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return false if the feature is disabled, true otherwise
* @since 1.5.0
* @see #setAutoAdjustRanges(Class, Configuration, boolean)
*/
public static Boolean getAutoAdjustRanges(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.AUTO_ADJUST_RANGES), true);
}
/**
* Controls the use of the {@link IsolatedScanner} in this job.
*
* <p>
* By default, this feature is <b>disabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @since 1.5.0
*/
public static void setScanIsolation(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.SCAN_ISOLATION), enableFeature);
}
/**
* Determines whether a configuration has isolation enabled.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return true if the feature is enabled, false otherwise
* @since 1.5.0
* @see #setScanIsolation(Class, Configuration, boolean)
*/
public static Boolean isIsolated(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.SCAN_ISOLATION), false);
}
/**
* Controls the use of the {@link ClientSideIteratorScanner} in this job. Enabling this feature will cause the iterator stack to be constructed within the Map
* task, rather than within the Accumulo TServer. To use this feature, all classes needed for those iterators must be available on the classpath for the task.
*
* <p>
* By default, this feature is <b>disabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @since 1.5.0
*/
public static void setLocalIterators(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.USE_LOCAL_ITERATORS), enableFeature);
}
/**
* Determines whether a configuration uses local iterators.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return true if the feature is enabled, false otherwise
* @since 1.5.0
* @see #setLocalIterators(Class, Configuration, boolean)
*/
public static Boolean usesLocalIterators(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.USE_LOCAL_ITERATORS), false);
}
/**
* <p>
* Enable reading offline tables. By default, this feature is disabled and only online tables are scanned. This will make the map reduce job directly read the
* table's files. If the table is not offline, then the job will fail. If the table comes online during the map reduce job, it is likely that the job will
* fail.
*
* <p>
* To use this option, the map reduce user will need access to read the Accumulo directory in HDFS.
*
* <p>
* Reading the offline table will create the scan time iterator stack in the map process. So any iterators that are configured for the table will need to be
* on the mapper's classpath. The accumulo-site.xml may need to be on the mapper's classpath if HDFS or the Accumulo directory in HDFS are non-standard.
*
* <p>
* One way to use this feature is to clone a table, take the clone offline, and use the clone as the input table for a map reduce job. If you plan to map
* reduce over the data many times, it may be better to the compact the table, clone it, take it offline, and use the clone for all map reduce jobs. The
* reason to do this is that compaction will reduce each tablet in the table to one file, and it is faster to read from one file.
*
* <p>
* There are two possible advantages to reading a tables file directly out of HDFS. First, you may see better read performance. Second, it will support
* speculative execution better. When reading an online table speculative execution can put more load on an already slow tablet server.
*
* <p>
* By default, this feature is <b>disabled</b>.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param enableFeature
* the feature is enabled if true, disabled otherwise
* @since 1.5.0
*/
public static void setOfflineTableScan(Class<?> implementingClass, Configuration conf, boolean enableFeature) {
conf.setBoolean(enumToConfKey(implementingClass, Features.SCAN_OFFLINE), enableFeature);
}
/**
* Determines whether a configuration has the offline table scan feature enabled.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return true if the feature is enabled, false otherwise
* @since 1.5.0
* @see #setOfflineTableScan(Class, Configuration, boolean)
*/
public static Boolean isOfflineScan(Class<?> implementingClass, Configuration conf) {
return conf.getBoolean(enumToConfKey(implementingClass, Features.SCAN_OFFLINE), false);
}
/**
* Sets configurations for multiple tables at a time.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param configs
* an array of {@link InputTableConfig} objects to associate with the job
* @since 1.6.0
*/
public static void setInputTableConfigs(Class<?> implementingClass, Configuration conf, Map<String,InputTableConfig> configs) {
MapWritable mapWritable = new MapWritable();
for (Map.Entry<String,InputTableConfig> tableConfig : configs.entrySet())
mapWritable.put(new Text(tableConfig.getKey()), tableConfig.getValue());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
mapWritable.write(new DataOutputStream(baos));
} catch (IOException e) {
throw new IllegalStateException("Table configuration could not be serialized.");
}
String confKey = enumToConfKey(implementingClass, ScanOpts.TABLE_CONFIGS);
conf.set(confKey, new String(Base64.encodeBase64(baos.toByteArray())));
}
/**
* Returns all {@link InputTableConfig} objects associated with this job.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @return all of the table query configs for the job
* @since 1.6.0
*/
public static Map<String,InputTableConfig> getInputTableConfigs(Class<?> implementingClass, Configuration conf) {
Map<String,InputTableConfig> configs = new HashMap<String,InputTableConfig>();
Map.Entry<String,InputTableConfig> defaultConfig = getDefaultInputTableConfig(implementingClass, conf);
if (defaultConfig != null)
configs.put(defaultConfig.getKey(), defaultConfig.getValue());
String configString = conf.get(enumToConfKey(implementingClass, ScanOpts.TABLE_CONFIGS));
MapWritable mapWritable = new MapWritable();
if (configString != null) {
try {
byte[] bytes = Base64.decodeBase64(configString.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
mapWritable.readFields(new DataInputStream(bais));
bais.close();
} catch (IOException e) {
throw new IllegalStateException("The table query configurations could not be deserialized from the given configuration");
}
}
for (Map.Entry<Writable,Writable> entry : mapWritable.entrySet())
configs.put(((Text) entry.getKey()).toString(), (InputTableConfig) entry.getValue());
return configs;
}
/**
* Returns the {@link InputTableConfig} for the given table
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param tableName
* the table name for which to fetch the table query config
* @return the table query config for the given table name (if it exists) and null if it does not
* @since 1.6.0
*/
public static InputTableConfig getInputTableConfig(Class<?> implementingClass, Configuration conf, String tableName) {
Map<String,InputTableConfig> queryConfigs = getInputTableConfigs(implementingClass, conf);
return queryConfigs.get(tableName);
}
/**
* Initializes an Accumulo {@link TabletLocator} based on the configuration.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @param tableId
* The table id for which to initialize the {@link TabletLocator}
* @return an Accumulo tablet locator
* @throws TableNotFoundException
* if the table name set on the configuration doesn't exist
* @since 1.5.0
*/
public static TabletLocator getTabletLocator(Class<?> implementingClass, Configuration conf, String tableId) throws TableNotFoundException {
String instanceType = conf.get(enumToConfKey(implementingClass, InstanceOpts.TYPE));
if ("MockInstance".equals(instanceType))
return new MockTabletLocator();
Instance instance = getInstance(implementingClass, conf);
try {
return TabletLocator.getLocator(instance, new Text(tableId));
} finally {
instance.close();
}
}
// InputFormat doesn't have the equivalent of OutputFormat's checkOutputSpecs(JobContext job)
/**
* Check whether a configuration is fully configured to be used with an Accumulo {@link org.apache.hadoop.mapreduce.InputFormat}.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop configuration object to configure
* @throws IOException
* if the context is improperly configured
* @since 1.5.0
*/
public static void validateOptions(Class<?> implementingClass, Configuration conf) throws IOException {
Map<String,InputTableConfig> inputTableConfigs = getInputTableConfigs(implementingClass, conf);
if (!isConnectorInfoSet(implementingClass, conf))
throw new IOException("Input info has not been set.");
String instanceKey = conf.get(enumToConfKey(implementingClass, InstanceOpts.TYPE));
if (!"MockInstance".equals(instanceKey) && !"ZooKeeperInstance".equals(instanceKey))
throw new IOException("Instance info has not been set.");
// validate that we can connect as configured
Instance inst = getInstance(implementingClass, conf);
try {
String principal = getPrincipal(implementingClass, conf);
AuthenticationToken token = getAuthenticationToken(implementingClass, conf);
Connector c = inst.getConnector(principal, token);
if (!c.securityOperations().authenticateUser(principal, token))
throw new IOException("Unable to authenticate user");
if (getInputTableConfigs(implementingClass, conf).size() == 0)
throw new IOException("No table set.");
for (Map.Entry<String,InputTableConfig> tableConfig : inputTableConfigs.entrySet()) {
if (!c.securityOperations().hasTablePermission(getPrincipal(implementingClass, conf), tableConfig.getKey(), TablePermission.READ))
throw new IOException("Unable to access table");
}
for (Map.Entry<String,InputTableConfig> tableConfigEntry : inputTableConfigs.entrySet()) {
InputTableConfig tableConfig = tableConfigEntry.getValue();
if (!tableConfig.shouldUseLocalIterators()) {
if (tableConfig.getIterators() != null) {
for (IteratorSetting iter : tableConfig.getIterators()) {
if (!c.tableOperations().testClassLoad(tableConfigEntry.getKey(), iter.getIteratorClass(), SortedKeyValueIterator.class.getName()))
throw new AccumuloException("Servers are unable to load " + iter.getIteratorClass() + " as a " + SortedKeyValueIterator.class.getName());
}
}
}
}
} catch (AccumuloException e) {
throw new IOException(e);
} catch (AccumuloSecurityException e) {
throw new IOException(e);
} catch (TableNotFoundException e) {
throw new IOException(e);
} finally {
inst.close();
}
}
/**
* Returns the {@link org.apache.accumulo.core.client.mapreduce.InputTableConfig} for the configuration based on the properties set using the single-table
* input methods.
*
* @param implementingClass
* the class whose name will be used as a prefix for the property configuration key
* @param conf
* the Hadoop instance for which to retrieve the configuration
* @return the config object built from the single input table properties set on the job
* @since 1.6.0
*/
protected static Map.Entry<String,InputTableConfig> getDefaultInputTableConfig(Class<?> implementingClass, Configuration conf) {
String tableName = getInputTableName(implementingClass, conf);
if (tableName != null) {
InputTableConfig queryConfig = new InputTableConfig();
List<IteratorSetting> itrs = getIterators(implementingClass, conf);
if (itrs != null)
queryConfig.setIterators(itrs);
Set<Pair<Text,Text>> columns = getFetchedColumns(implementingClass, conf);
if (columns != null)
queryConfig.fetchColumns(columns);
List<Range> ranges = null;
try {
ranges = getRanges(implementingClass, conf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (ranges != null)
queryConfig.setRanges(ranges);
queryConfig.setAutoAdjustRanges(getAutoAdjustRanges(implementingClass, conf)).setUseIsolatedScanners(isIsolated(implementingClass, conf))
.setUseLocalIterators(usesLocalIterators(implementingClass, conf)).setOfflineScan(isOfflineScan(implementingClass, conf));
return Maps.immutableEntry(tableName, queryConfig);
}
return null;
}
public static Map<String,Map<KeyExtent,List<Range>>> binOffline(String tableId, List<Range> ranges, Instance instance, Connector conn)
throws AccumuloException, TableNotFoundException {
Map<String,Map<KeyExtent,List<Range>>> binnedRanges = new HashMap<String,Map<KeyExtent,List<Range>>>();
if (Tables.getTableState(instance, tableId) != TableState.OFFLINE) {
Tables.clearCache(instance);
if (Tables.getTableState(instance, tableId) != TableState.OFFLINE) {
throw new AccumuloException("Table is online tableId:" + tableId + " cannot scan table in offline mode ");
}
}
for (Range range : ranges) {
Text startRow;
if (range.getStartKey() != null)
startRow = range.getStartKey().getRow();
else
startRow = new Text();
Range metadataRange = new Range(new KeyExtent(new Text(tableId), startRow, null).getMetadataEntry(), true, null, false);
Scanner scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
MetadataSchema.TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.fetch(scanner);
scanner.fetchColumnFamily(MetadataSchema.TabletsSection.LastLocationColumnFamily.NAME);
scanner.fetchColumnFamily(MetadataSchema.TabletsSection.CurrentLocationColumnFamily.NAME);
scanner.fetchColumnFamily(MetadataSchema.TabletsSection.FutureLocationColumnFamily.NAME);
scanner.setRange(metadataRange);
RowIterator rowIter = new RowIterator(scanner);
KeyExtent lastExtent = null;
while (rowIter.hasNext()) {
Iterator<Map.Entry<Key,Value>> row = rowIter.next();
String last = "";
KeyExtent extent = null;
String location = null;
while (row.hasNext()) {
Map.Entry<Key,Value> entry = row.next();
Key key = entry.getKey();
if (key.getColumnFamily().equals(MetadataSchema.TabletsSection.LastLocationColumnFamily.NAME)) {
last = entry.getValue().toString();
}
if (key.getColumnFamily().equals(MetadataSchema.TabletsSection.CurrentLocationColumnFamily.NAME)
|| key.getColumnFamily().equals(MetadataSchema.TabletsSection.FutureLocationColumnFamily.NAME)) {
location = entry.getValue().toString();
}
if (MetadataSchema.TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.hasColumns(key)) {
extent = new KeyExtent(key.getRow(), entry.getValue());
}
}
if (location != null)
return null;
if (!extent.getTableId().toString().equals(tableId)) {
throw new AccumuloException("Saw unexpected table Id " + tableId + " " + extent);
}
if (lastExtent != null && !extent.isPreviousExtent(lastExtent)) {
throw new AccumuloException(" " + lastExtent + " is not previous extent " + extent);
}
Map<KeyExtent,List<Range>> tabletRanges = binnedRanges.get(last);
if (tabletRanges == null) {
tabletRanges = new HashMap<KeyExtent,List<Range>>();
binnedRanges.put(last, tabletRanges);
}
List<Range> rangeList = tabletRanges.get(extent);
if (rangeList == null) {
rangeList = new ArrayList<Range>();
tabletRanges.put(extent, rangeList);
}
rangeList.add(range);
if (extent.getEndRow() == null || range.afterEndKey(new Key(extent.getEndRow()).followingKey(PartialKey.ROW))) {
break;
}
lastExtent = extent;
}
}
return binnedRanges;
}
}
| ACCUMULO-2105 cannot close instance
| core/src/main/java/org/apache/accumulo/core/client/mapreduce/lib/util/InputConfigurator.java | ACCUMULO-2105 cannot close instance | <ide><path>ore/src/main/java/org/apache/accumulo/core/client/mapreduce/lib/util/InputConfigurator.java
<ide> if ("MockInstance".equals(instanceType))
<ide> return new MockTabletLocator();
<ide> Instance instance = getInstance(implementingClass, conf);
<del> try {
<del> return TabletLocator.getLocator(instance, new Text(tableId));
<del> } finally {
<del> instance.close();
<del> }
<add> return TabletLocator.getLocator(instance, new Text(tableId));
<ide> }
<ide>
<ide> // InputFormat doesn't have the equivalent of OutputFormat's checkOutputSpecs(JobContext job) |
|
Java | apache-2.0 | becb342d525bd624f8408d262ad27a56b8b3fc88 | 0 | b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl | /*
* Copyright 2018-2021 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.reasoner.request;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.exceptions.BadRequestException;
import com.b2international.commons.exceptions.LockedException;
import com.b2international.snowowl.core.authorization.BranchAccessControl;
import com.b2international.snowowl.core.branch.Branch;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.domain.TransactionContext;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.core.events.bulk.BulkRequest;
import com.b2international.snowowl.core.events.bulk.BulkRequestBuilder;
import com.b2international.snowowl.core.identity.Permission;
import com.b2international.snowowl.core.identity.User;
import com.b2international.snowowl.core.internal.locks.DatastoreLockContextDescriptions;
import com.b2international.snowowl.core.locks.Locks;
import com.b2international.snowowl.core.plugin.Extensions;
import com.b2international.snowowl.core.repository.RepositoryRequests;
import com.b2international.snowowl.core.request.CommitResult;
import com.b2international.snowowl.core.request.SearchResourceRequestIterator;
import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.core.domain.*;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
import com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration;
import com.b2international.snowowl.snomed.datastore.id.assigner.SnomedNamespaceAndModuleAssigner;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedRelationshipIndexEntry;
import com.b2international.snowowl.snomed.datastore.request.IdRequest;
import com.b2international.snowowl.snomed.datastore.request.SnomedDescriptionCreateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRefSetMemberCreateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRefSetMemberUpdateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRelationshipCreateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRelationshipUpdateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRequests;
import com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker;
import com.b2international.snowowl.snomed.reasoner.domain.*;
import com.b2international.snowowl.snomed.reasoner.equivalence.IEquivalentConceptMerger;
import com.b2international.snowowl.snomed.reasoner.exceptions.ReasonerApiException;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
/**
* Represents a request that saves pre-recorded changes of a classification,
* usually running in a remote job.
*
* @since 7.0
*/
final class SaveJobRequest implements Request<BranchContext, Boolean>, BranchAccessControl {
private static final Logger LOG = LoggerFactory.getLogger("reasoner");
private static final int SCROLL_LIMIT = 10_000;
@NotEmpty
private String classificationId;
private String userId;
@NotNull
private String parentLockContext;
@NotEmpty
private String commitComment;
@NotEmpty
private String moduleId;
@NotNull
private String namespace;
private String assignerType;
private boolean fixEquivalences;
private boolean handleConcreteDomains;
SaveJobRequest() {}
void setClassificationId(final String classificationId) {
this.classificationId = classificationId;
}
void setUserId(final String userId) {
this.userId = userId;
}
void setParentLockContext(final String parentLockContext) {
this.parentLockContext = parentLockContext;
}
void setCommitComment(final String commitComment) {
this.commitComment = commitComment;
}
void setModuleId(final String moduleId) {
this.moduleId = moduleId;
}
void setNamespace(final String namespace) {
this.namespace = namespace;
}
void setAssignerType(final String assignerType) {
this.assignerType = assignerType;
}
void setFixEquivalences(final boolean fixEquivalences) {
this.fixEquivalences = fixEquivalences;
}
void setHandleConcreteDomains(final boolean handleConcreteDomains) {
this.handleConcreteDomains = handleConcreteDomains;
}
@Override
public Boolean execute(final BranchContext context) {
final IProgressMonitor monitor = context.service(IProgressMonitor.class);
final ClassificationTracker tracker = context.service(ClassificationTracker.class);
final String user = !Strings.isNullOrEmpty(userId) ? userId : context.service(User.class).getUsername();
try (Locks locks = Locks.on(context)
.user(user)
.lock(DatastoreLockContextDescriptions.SAVE_CLASSIFICATION_RESULTS, parentLockContext)) {
return persistChanges(context, monitor);
} catch (final LockedException e) {
tracker.classificationFailed(classificationId);
throw new ReasonerApiException("Couldn't acquire exclusive access to terminology store for persisting classification changes; %s", e.getMessage(), e);
} catch (final Exception e) {
LOG.error("Unexpected error while persisting classification changes.", e);
tracker.classificationSaveFailed(classificationId);
throw new ReasonerApiException("Error while persisting classification changes on '%s'.", context.path(), e);
} finally {
monitor.done();
}
}
private Boolean persistChanges(final BranchContext context, final IProgressMonitor monitor) {
// Repeat the same checks as in ClassificationSaveRequest, now within the lock
final ClassificationTask classification = ClassificationRequests.prepareGetClassification(classificationId)
.build()
.execute(context);
final String branchPath = classification.getBranch();
final Branch branch = RepositoryRequests.branching()
.prepareGet(branchPath)
.build()
.execute(context);
if (!ClassificationSaveRequest.SAVEABLE_STATUSES.contains(classification.getStatus())) {
throw new BadRequestException("Classification '%s' is not in the expected state to start saving changes.", classificationId);
}
if (classification.getTimestamp() < branch.headTimestamp()) {
throw new BadRequestException("Classification '%s' on branch '%s' is stale (classification timestamp: %s, head timestamp: %s).",
classificationId,
branchPath,
classification.getTimestamp(),
branch.headTimestamp());
}
final ClassificationTracker classificationTracker = context.service(ClassificationTracker.class);
// Signal the state change
classificationTracker.classificationSaving(classificationId);
final SubMonitor subMonitor = SubMonitor.convert(monitor, "Persisting changes", 6);
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder = BulkRequest.create();
applyChanges(subMonitor, context, bulkRequestBuilder);
final Request<BranchContext, CommitResult> commitRequest = SnomedRequests.prepareCommit()
.setBody(bulkRequestBuilder)
.setCommitComment(commitComment)
.setParentContextDescription(DatastoreLockContextDescriptions.SAVE_CLASSIFICATION_RESULTS)
.setAuthor(userId)
.build();
final CommitResult commitResult = new IdRequest<>(commitRequest)
.execute(context);
classificationTracker.classificationSaved(classificationId, commitResult.getCommitTimestamp());
return Boolean.TRUE;
}
private void applyChanges(final SubMonitor subMonitor,
final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder) {
final SnomedNamespaceAndModuleAssigner assigner = createNamespaceAndModuleAssigner(context);
final Set<String> conceptIdsToSkip = mergeEquivalentConcepts(context, bulkRequestBuilder, assigner);
applyRelationshipChanges(context, bulkRequestBuilder, assigner, conceptIdsToSkip);
if (handleConcreteDomains) {
// CD member support in configuration overrides the flag on the save request
final SnomedCoreConfiguration snomedCoreConfiguration = context.service(SnomedCoreConfiguration.class);
if (snomedCoreConfiguration.isConcreteDomainSupported()) {
applyConcreteDomainChanges(context, bulkRequestBuilder, assigner, conceptIdsToSkip);
}
}
}
private void applyRelationshipChanges(final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final Set<String> conceptIdsToSkip) {
final RelationshipChangeSearchRequestBuilder relationshipRequestBuilder = ClassificationRequests.prepareSearchRelationshipChange()
.setLimit(SCROLL_LIMIT)
.setExpand("relationship(inferredOnly:true)")
.filterByClassificationId(classificationId);
final SearchResourceRequestIterator<RelationshipChangeSearchRequestBuilder, RelationshipChanges> relationshipIterator =
new SearchResourceRequestIterator<>(relationshipRequestBuilder,
r -> r.build().execute(context));
while (relationshipIterator.hasNext()) {
final RelationshipChanges nextChanges = relationshipIterator.next();
final Set<String> conceptIds = nextChanges.stream()
.map(RelationshipChange::getRelationship)
.map(ReasonerRelationship::getSourceId)
.collect(Collectors.toSet());
final Set<String> originRelationshipIds = nextChanges.stream()
.filter(change -> ChangeNature.NEW.equals(change.getChangeNature())
|| ChangeNature.UPDATED.equals(change.getChangeNature()))
.map(RelationshipChange::getRelationship)
.map(ReasonerRelationship::getOriginId)
.filter(id -> id != null)
.collect(Collectors.toSet());
final Map<String, String> originSourceIds = SnomedRequests.prepareSearchRelationship()
.setLimit(originRelationshipIds.size())
.filterByIds(originRelationshipIds)
.setFields(SnomedRelationshipIndexEntry.Fields.ID, SnomedRelationshipIndexEntry.Fields.SOURCE_ID)
.build()
.execute(context)
.stream()
.collect(Collectors.toMap(
SnomedRelationship::getId, // keys: ID of the "origin" relationship
SnomedRelationship::getSourceId)); // values: source concept ID of the "origin" relationship
conceptIds.removeAll(conceptIdsToSkip);
namespaceAndModuleAssigner.collectRelationshipNamespacesAndModules(conceptIds, context);
for (final RelationshipChange change : nextChanges) {
final ReasonerRelationship relationship = change.getRelationship();
// Relationship changes related to merged concepts should not be applied
if (conceptIdsToSkip.contains(relationship.getSourceId()) || conceptIdsToSkip.contains(relationship.getDestinationId())) {
continue;
}
switch (change.getChangeNature()) {
case NEW: {
/*
* Do not "infer" any relationship that is passed down from a concept that was
* already merged by the equivalent concept merging step
*/
final String originSourceId = originSourceIds.get(relationship.getOriginId());
if (!conceptIdsToSkip.contains(originSourceId)) {
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner, relationship);
}
}
break;
case UPDATED: {
final String originSourceId = originSourceIds.get(relationship.getOriginId());
if (!conceptIdsToSkip.contains(originSourceId)) {
updateComponent(bulkRequestBuilder, namespaceAndModuleAssigner, relationship);
}
}
break;
case REDUNDANT:
removeOrDeactivate(bulkRequestBuilder, namespaceAndModuleAssigner, relationship);
break;
default:
throw new IllegalStateException(String.format("Unexpected relationship change '%s' found with SCTID '%s'.",
change.getChangeNature(),
change.getRelationship().getOriginId()));
}
}
}
namespaceAndModuleAssigner.clear();
}
private void applyConcreteDomainChanges(final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final Set<String> conceptIdsToSkip) {
final ConcreteDomainChangeSearchRequestBuilder concreteDomainRequestBuilder = ClassificationRequests.prepareSearchConcreteDomainChange()
.setLimit(SCROLL_LIMIT)
.setExpand("concreteDomainMember(inferredOnly:true)")
.filterByClassificationId(classificationId);
final SearchResourceRequestIterator<ConcreteDomainChangeSearchRequestBuilder, ConcreteDomainChanges> concreteDomainIterator =
new SearchResourceRequestIterator<>(concreteDomainRequestBuilder,
r -> r.build().execute(context));
while (concreteDomainIterator.hasNext()) {
final ConcreteDomainChanges nextChanges = concreteDomainIterator.next();
final Set<String> conceptIds = nextChanges.stream()
.map(ConcreteDomainChange::getConcreteDomainMember)
.map(m -> m.getReferencedComponentId())
.collect(Collectors.toSet());
final Set<String> originMemberIds = nextChanges.stream()
.filter(change -> ChangeNature.NEW.equals(change.getChangeNature())
|| ChangeNature.UPDATED.equals(change.getChangeNature()))
.map(ConcreteDomainChange::getConcreteDomainMember)
.map(ReasonerConcreteDomainMember::getOriginMemberId)
.filter(id -> id != null)
.collect(Collectors.toSet());
final Map<String, String> originReferencedComponentIds = SnomedRequests.prepareSearchMember()
.setLimit(originMemberIds.size())
.filterByIds(originMemberIds)
.build()
.execute(context)
.stream()
.collect(Collectors.toMap(
m -> m.getId(), // keys: ID of the "origin" CD member
m -> m.getReferencedComponent().getId())); // values: referenced component ID of the "origin" CD member
// Concepts which will be inactivated as part of equivalent concept merging should be excluded
conceptIds.removeAll(conceptIdsToSkip);
namespaceAndModuleAssigner.collectConcreteDomainModules(conceptIds, context);
for (final ConcreteDomainChange change : nextChanges) {
final ReasonerConcreteDomainMember referenceSetMember = change.getConcreteDomainMember();
// CD member changes related to merged concepts should not be applied
if (conceptIdsToSkip.contains(referenceSetMember.getReferencedComponentId())) {
continue;
}
switch (change.getChangeNature()) {
case NEW: {
/*
* Do not "infer" any CD member that is passed down from a concept that was
* already merged by the equivalent concept merging step
*/
final String originReferencedComponentId = originReferencedComponentIds.get(referenceSetMember.getOriginMemberId());
if (!conceptIdsToSkip.contains(originReferencedComponentId)) {
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner, referenceSetMember);
}
}
break;
case UPDATED: {
final String originReferencedComponentId = originReferencedComponentIds.get(referenceSetMember.getOriginMemberId());
if (!conceptIdsToSkip.contains(originReferencedComponentId)) {
updateComponent(bulkRequestBuilder, namespaceAndModuleAssigner, referenceSetMember);
}
}
break;
case REDUNDANT:
removeOrDeactivate(bulkRequestBuilder, namespaceAndModuleAssigner, referenceSetMember);
break;
default:
throw new IllegalStateException(String.format("Unexpected CD member change '%s' found with UUID '%s'.",
change.getChangeNature(),
change.getConcreteDomainMember().getOriginMemberId()));
}
}
}
namespaceAndModuleAssigner.clear();
}
private Set<String> mergeEquivalentConcepts(final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner assigner) {
if (!fixEquivalences) {
return Collections.emptySet();
}
// XXX: Restrict merging to active components only
final String expand = "equivalentConcepts(expand("
+ "descriptions(active:true),"
+ "relationships(active:true),"
+ "inboundRelationships(active:true),"
+ "members(active:true)))";
final EquivalentConceptSetSearchRequestBuilder equivalentConceptRequest = ClassificationRequests.prepareSearchEquivalentConceptSet()
.setLimit(SCROLL_LIMIT)
.setExpand(expand)
.filterByClassificationId(classificationId);
final SearchResourceRequestIterator<EquivalentConceptSetSearchRequestBuilder, EquivalentConceptSets> equivalentConceptIterator =
new SearchResourceRequestIterator<>(equivalentConceptRequest,
r -> r.build().execute(context));
// Are there any equivalent concepts present?
if (!equivalentConceptIterator.hasNext()) {
return Collections.emptySet();
}
final Multimap<SnomedConcept, SnomedConcept> equivalentConcepts = HashMultimap.create();
while (equivalentConceptIterator.hasNext()) {
final EquivalentConceptSets nextBatch = equivalentConceptIterator.next();
for (final EquivalentConceptSet equivalentSet : nextBatch) {
if (equivalentSet.isUnsatisfiable()) {
continue;
}
final List<SnomedConcept> conceptsToRemove = newArrayList(equivalentSet.getEquivalentConcepts());
final SnomedConcept conceptToKeep = conceptsToRemove.remove(0);
equivalentConcepts.putAll(conceptToKeep, conceptsToRemove);
}
}
// Were all equivalent concepts unsatisfiable?
if (equivalentConcepts.isEmpty()) {
return Collections.emptySet();
}
IEquivalentConceptMerger merger = Extensions.getFirstPriorityExtension(
IEquivalentConceptMerger.EXTENSION_POINT,
IEquivalentConceptMerger.class);
if (merger == null) {
merger = new IEquivalentConceptMerger.Default();
}
final String mergerName = merger.getClass().getSimpleName();
LOG.info("Reasoner service will use {} for equivalent concept merging.", mergerName);
final Set<String> conceptIdsToSkip = merger.merge(equivalentConcepts);
final Set<String> conceptIdsToKeep = equivalentConcepts.keySet()
.stream()
.map(SnomedConcept::getId)
.collect(Collectors.toSet());
// Prepare to provide namespace-module for inbound relationship source concepts as well
final Set<String> relationshipChangeConceptIds = newHashSet(conceptIdsToKeep);
// Add source concepts on new/about to be inactivated inbound relationships, pointing to "kept" concepts
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedRelationship relationship : conceptToKeep.getInboundRelationships()) {
if (relationship.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
relationshipChangeConceptIds.add(relationship.getSourceId());
} else if (!relationship.isActive()) {
relationshipChangeConceptIds.add(relationship.getSourceId());
}
}
}
assigner.collectRelationshipNamespacesAndModules(relationshipChangeConceptIds, context);
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedRelationship relationship : conceptToKeep.getInboundRelationships()) {
// Already handled as another concept's outbound relationship
if (relationship.getId() == null) {
continue;
}
if (relationship.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
relationship.setId(null);
addComponent(bulkRequestBuilder, assigner, relationship);
} else if (!relationship.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, relationship);
}
}
for (final SnomedRelationship relationship : conceptToKeep.getRelationships()) {
// Already handled as another concept's inbound relationship
if (relationship.getId() == null) {
continue;
}
if (relationship.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
relationship.setId(null);
addComponent(bulkRequestBuilder, assigner, relationship);
} else if (!relationship.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, relationship);
}
}
}
// CD members are always "outbound", however, so the concept SCTID set can be reduced
assigner.clear();
assigner.collectConcreteDomainModules(conceptIdsToKeep, context);
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedReferenceSetMember member : conceptToKeep.getMembers()) {
if (member.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
member.setId(null);
addComponent(bulkRequestBuilder, assigner, member);
} else if (member.getId().startsWith(IEquivalentConceptMerger.PREFIX_UPDATED)) {
// Trim the prefix from the ID to restore its original form
member.setId(member.getId().substring(IEquivalentConceptMerger.PREFIX_UPDATED.length()));
bulkRequestBuilder.add(member.toUpdateRequest());
} else if (!member.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, member);
}
}
}
// Descriptions are also "outbound"
assigner.clear();
assigner.collectRelationshipNamespacesAndModules(conceptIdsToKeep, context);
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedDescription description : conceptToKeep.getDescriptions()) {
if (description.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
description.setId(null);
addComponent(bulkRequestBuilder, assigner, description);
} else if (description.getId().startsWith(IEquivalentConceptMerger.PREFIX_UPDATED)) {
// Trim the prefix from the ID to restore its original form
description.setId(description.getId().substring(IEquivalentConceptMerger.PREFIX_UPDATED.length()));
bulkRequestBuilder.add(description.toUpdateRequest());
} else if (!description.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, description);
}
}
}
// Inactivation of "removed" concepts also requires modules to be collected according to the assigner rules
assigner.clear();
assigner.collectRelationshipNamespacesAndModules(conceptIdsToSkip, context);
for (final SnomedConcept conceptToRemove : equivalentConcepts.values()) {
// Check if the concept needs to be removed or deactivated
if (!conceptToRemove.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, conceptToRemove);
}
}
assigner.clear();
return conceptIdsToSkip;
}
private SnomedNamespaceAndModuleAssigner createNamespaceAndModuleAssigner(final BranchContext context) {
// Override assigner type if given
final String selectedType;
if (assignerType != null) {
selectedType = assignerType;
} else {
final SnomedCoreConfiguration configuration = context.service(SnomedCoreConfiguration.class);
selectedType = configuration.getNamespaceModuleAssigner();
}
final SnomedNamespaceAndModuleAssigner assigner = SnomedNamespaceAndModuleAssigner.create(context, selectedType, moduleId, namespace);
LOG.info("Reasoner service will use {} for relationship/concrete domain namespace and module assignment.", assigner);
return assigner;
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner, final SnomedConcept concept) {
final Request<TransactionContext, Boolean> request;
if (concept.isReleased()) {
request = SnomedRequests
.prepareUpdateConcept(concept.getId())
.setModuleId(namespaceAndModuleAssigner.getRelationshipModuleId(concept.getId()))
.setActive(false)
.setInactivationProperties(new InactivationProperties("" /*RETIRED*/, Collections.emptyList()))
.build();
} else {
request = SnomedRequests
.prepareDeleteConcept(concept.getId())
.build();
}
bulkRequestBuilder.add(request);
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedRelationship relationship) {
removeOrDeactivateRelationship(bulkRequestBuilder, namespaceAndModuleAssigner, relationship.isReleased(), relationship.getId(), relationship.getSourceId());
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerRelationship relationship) {
removeOrDeactivateRelationship(bulkRequestBuilder, namespaceAndModuleAssigner, relationship.isReleased(), relationship.getOriginId(), relationship.getSourceId());
}
private void removeOrDeactivateRelationship(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final boolean released, final String relationshipId, String sourceId) {
final Request<TransactionContext, Boolean> request;
if (released) {
request = SnomedRequests
.prepareUpdateRelationship(relationshipId)
.setActive(false)
.setModuleId(namespaceAndModuleAssigner.getRelationshipModuleId(sourceId))
.build();
} else {
request = SnomedRequests
.prepareDeleteRelationship(relationshipId)
.build();
}
bulkRequestBuilder.add(request);
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedReferenceSetMember member) {
removeOrDeactivateMember(bulkRequestBuilder, namespaceAndModuleAssigner, member.isReleased(), member.getId(), member.getReferencedComponent().getId());
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerConcreteDomainMember member) {
removeOrDeactivateMember(bulkRequestBuilder, namespaceAndModuleAssigner, member.isReleased(), member.getOriginMemberId(), member.getReferencedComponentId());
}
private void removeOrDeactivateMember(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final boolean released, final String memberId, String referencedComponentId) {
final Request<TransactionContext, Boolean> request;
if (released) {
request = SnomedRequests
.prepareUpdateMember(memberId)
.setSource(ImmutableMap.<String, Object>builder()
.put(SnomedRf2Headers.FIELD_ACTIVE, false)
.put(SnomedRf2Headers.FIELD_MODULE_ID, namespaceAndModuleAssigner.getConcreteDomainModuleId(referencedComponentId))
.build())
.build();
} else {
request = SnomedRequests
.prepareDeleteMember(memberId)
.build();
}
bulkRequestBuilder.add(request);
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedDescription description) {
final Request<TransactionContext, Boolean> request;
if (description.isReleased()) {
request = SnomedRequests
.prepareUpdateDescription(description.getId())
.setActive(false)
.setAcceptability(ImmutableMap.of())
.build();
} else {
request = SnomedRequests
.prepareDeleteDescription(description.getId())
.build();
}
bulkRequestBuilder.add(request);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerRelationship relationship) {
final String sourceId = relationship.getSourceId();
final String typeId = relationship.getTypeId();
final String destinationId = relationship.getDestinationId();
final boolean destinationNegated = relationship.isDestinationNegated();
final RelationshipValue value = relationship.getValueAsObject();
final String characteristicTypeId = relationship.getCharacteristicTypeId();
final int group = relationship.getGroup();
final int unionGroup = relationship.getUnionGroup();
final String modifier = relationship.getModifierId();
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
sourceId, typeId, destinationId, destinationNegated, value,
characteristicTypeId, group, unionGroup, modifier);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedRelationship relationship) {
final String sourceId = relationship.getSourceId();
final String typeId = relationship.getTypeId();
final String destinationId = relationship.getDestinationId();
final boolean destinationNegated = relationship.isDestinationNegated();
final RelationshipValue value = relationship.getValueAsObject();
final String characteristicTypeId = relationship.getCharacteristicTypeId();
final int group = relationship.getGroup();
final int unionGroup = relationship.getUnionGroup();
final String modifier = relationship.getModifierId();
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
sourceId, typeId, destinationId, destinationNegated, value,
characteristicTypeId, group, unionGroup, modifier);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final String sourceId,
final String typeId,
final String destinationId,
final boolean destinationNegated,
final RelationshipValue value,
final String characteristicTypeId,
final int group,
final int unionGroup,
final String modifier) {
final String moduleId = namespaceAndModuleAssigner.getRelationshipModuleId(sourceId);
final String namespace = namespaceAndModuleAssigner.getRelationshipNamespace(sourceId);
final SnomedRelationshipCreateRequestBuilder createRequest = SnomedRequests.prepareNewRelationship()
.setIdFromNamespace(namespace)
.setTypeId(typeId)
.setActive(true)
.setCharacteristicTypeId(characteristicTypeId)
.setSourceId(sourceId)
.setDestinationId(destinationId)
.setDestinationNegated(destinationNegated)
.setValue(value)
.setGroup(group)
.setUnionGroup(unionGroup)
.setModifierId(modifier)
.setModuleId(moduleId);
bulkRequestBuilder.add(createRequest);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerConcreteDomainMember member) {
final String referencedComponentId = member.getReferencedComponentId();
final String referenceSetId = member.getReferenceSetId();
final String typeId = member.getTypeId();
final String serializedValue = member.getSerializedValue();
final int group = member.getGroup();
final String characteristicTypeId = member.getCharacteristicTypeId();
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
referencedComponentId, referenceSetId, typeId,
serializedValue, group, characteristicTypeId);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedReferenceSetMember member) {
final String referencedComponentId = member.getReferencedComponent().getId();
final String referenceSetId = member.getReferenceSetId();
final String typeId = (String) member.getProperties().get(SnomedRf2Headers.FIELD_TYPE_ID);
final String serializedValue = (String) member.getProperties().get(SnomedRf2Headers.FIELD_VALUE);
final int group = (Integer) member.getProperties().get(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP);
final String characteristicTypeId = (String) member.getProperties().get(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID);
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
referencedComponentId, referenceSetId, typeId,
serializedValue, group, characteristicTypeId);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final String referencedComponentId,
final String referenceSetId,
final String typeId,
final String serializedValue,
final int group,
final String characteristicTypeId) {
final String moduleId = namespaceAndModuleAssigner.getConcreteDomainModuleId(referencedComponentId);
final SnomedRefSetMemberCreateRequestBuilder createRequest = SnomedRequests.prepareNewMember()
.setActive(true)
.setModuleId(moduleId)
.setReferencedComponentId(referencedComponentId)
.setReferenceSetId(referenceSetId)
.setProperties(ImmutableMap.of(
SnomedRf2Headers.FIELD_TYPE_ID, typeId,
SnomedRf2Headers.FIELD_VALUE, serializedValue,
SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP, group,
SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID, characteristicTypeId));
bulkRequestBuilder.add(createRequest);
}
private void addComponent(BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
SnomedDescription description) {
final String moduleId = namespaceAndModuleAssigner.getRelationshipModuleId(description.getConceptId());
final String namespace = namespaceAndModuleAssigner.getRelationshipNamespace(description.getConceptId());
final SnomedDescriptionCreateRequestBuilder createRequest = SnomedRequests.prepareNewDescription()
.setIdFromNamespace(namespace)
.setAcceptability(description.getAcceptabilityMap())
.setActive(true)
.setCaseSignificanceId(description.getCaseSignificanceId())
.setConceptId(description.getConceptId())
.setLanguageCode(description.getLanguageCode())
.setModuleId(moduleId)
.setTerm(description.getTerm())
.setTypeId(description.getTypeId());
bulkRequestBuilder.add(createRequest);
}
private void updateComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerRelationship relationship) {
final SnomedRelationshipUpdateRequestBuilder updateRequest = SnomedRequests
.prepareUpdateRelationship(relationship.getOriginId())
.setModuleId(namespaceAndModuleAssigner.getRelationshipModuleId(relationship.getSourceId()))
.setGroup(relationship.getGroup());
bulkRequestBuilder.add(updateRequest);
}
private void updateComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerConcreteDomainMember referenceSetMember) {
final SnomedRefSetMemberUpdateRequestBuilder updateRequest = SnomedRequests
.prepareUpdateMember(referenceSetMember.getOriginMemberId())
.setSource(ImmutableMap.<String,Object>of(
SnomedRf2Headers.FIELD_VALUE, referenceSetMember.getSerializedValue(),
SnomedRf2Headers.FIELD_MODULE_ID, namespaceAndModuleAssigner.getConcreteDomainModuleId(referenceSetMember.getReferencedComponentId())
));
bulkRequestBuilder.add(updateRequest);
}
@Override
public String getOperation() {
return Permission.OPERATION_CLASSIFY;
}
}
| snomed/com.b2international.snowowl.snomed.reasoner/src/com/b2international/snowowl/snomed/reasoner/request/SaveJobRequest.java | /*
* Copyright 2018-2021 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.reasoner.request;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.exceptions.BadRequestException;
import com.b2international.commons.exceptions.LockedException;
import com.b2international.snowowl.core.authorization.BranchAccessControl;
import com.b2international.snowowl.core.branch.Branch;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.domain.TransactionContext;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.core.events.bulk.BulkRequest;
import com.b2international.snowowl.core.events.bulk.BulkRequestBuilder;
import com.b2international.snowowl.core.identity.Permission;
import com.b2international.snowowl.core.identity.User;
import com.b2international.snowowl.core.internal.locks.DatastoreLockContextDescriptions;
import com.b2international.snowowl.core.locks.Locks;
import com.b2international.snowowl.core.plugin.Extensions;
import com.b2international.snowowl.core.repository.RepositoryRequests;
import com.b2international.snowowl.core.request.CommitResult;
import com.b2international.snowowl.core.request.SearchResourceRequestIterator;
import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.core.domain.InactivationProperties;
import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
import com.b2international.snowowl.snomed.core.domain.SnomedDescription;
import com.b2international.snowowl.snomed.core.domain.SnomedRelationship;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
import com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration;
import com.b2international.snowowl.snomed.datastore.id.assigner.SnomedNamespaceAndModuleAssigner;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedRelationshipIndexEntry;
import com.b2international.snowowl.snomed.datastore.request.IdRequest;
import com.b2international.snowowl.snomed.datastore.request.SnomedDescriptionCreateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRefSetMemberCreateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRefSetMemberUpdateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRelationshipCreateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRelationshipUpdateRequestBuilder;
import com.b2international.snowowl.snomed.datastore.request.SnomedRequests;
import com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker;
import com.b2international.snowowl.snomed.reasoner.domain.*;
import com.b2international.snowowl.snomed.reasoner.equivalence.IEquivalentConceptMerger;
import com.b2international.snowowl.snomed.reasoner.exceptions.ReasonerApiException;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
/**
* Represents a request that saves pre-recorded changes of a classification,
* usually running in a remote job.
*
* @since 7.0
*/
final class SaveJobRequest implements Request<BranchContext, Boolean>, BranchAccessControl {
private static final Logger LOG = LoggerFactory.getLogger("reasoner");
private static final int SCROLL_LIMIT = 10_000;
@NotEmpty
private String classificationId;
private String userId;
@NotNull
private String parentLockContext;
@NotEmpty
private String commitComment;
@NotEmpty
private String moduleId;
@NotNull
private String namespace;
private String assignerType;
private boolean fixEquivalences;
private boolean handleConcreteDomains;
SaveJobRequest() {}
void setClassificationId(final String classificationId) {
this.classificationId = classificationId;
}
void setUserId(final String userId) {
this.userId = userId;
}
void setParentLockContext(final String parentLockContext) {
this.parentLockContext = parentLockContext;
}
void setCommitComment(final String commitComment) {
this.commitComment = commitComment;
}
void setModuleId(final String moduleId) {
this.moduleId = moduleId;
}
void setNamespace(final String namespace) {
this.namespace = namespace;
}
void setAssignerType(final String assignerType) {
this.assignerType = assignerType;
}
void setFixEquivalences(final boolean fixEquivalences) {
this.fixEquivalences = fixEquivalences;
}
void setHandleConcreteDomains(final boolean handleConcreteDomains) {
this.handleConcreteDomains = handleConcreteDomains;
}
@Override
public Boolean execute(final BranchContext context) {
final IProgressMonitor monitor = context.service(IProgressMonitor.class);
final ClassificationTracker tracker = context.service(ClassificationTracker.class);
final String user = !Strings.isNullOrEmpty(userId) ? userId : context.service(User.class).getUsername();
try (Locks locks = Locks.on(context)
.user(user)
.lock(DatastoreLockContextDescriptions.SAVE_CLASSIFICATION_RESULTS, parentLockContext)) {
return persistChanges(context, monitor);
} catch (final LockedException e) {
tracker.classificationFailed(classificationId);
throw new ReasonerApiException("Couldn't acquire exclusive access to terminology store for persisting classification changes; %s", e.getMessage(), e);
} catch (final Exception e) {
LOG.error("Unexpected error while persisting classification changes.", e);
tracker.classificationSaveFailed(classificationId);
throw new ReasonerApiException("Error while persisting classification changes on '%s'.", context.path(), e);
} finally {
monitor.done();
}
}
private Boolean persistChanges(final BranchContext context, final IProgressMonitor monitor) {
// Repeat the same checks as in ClassificationSaveRequest, now within the lock
final ClassificationTask classification = ClassificationRequests.prepareGetClassification(classificationId)
.build()
.execute(context);
final String branchPath = classification.getBranch();
final Branch branch = RepositoryRequests.branching()
.prepareGet(branchPath)
.build()
.execute(context);
if (!ClassificationSaveRequest.SAVEABLE_STATUSES.contains(classification.getStatus())) {
throw new BadRequestException("Classification '%s' is not in the expected state to start saving changes.", classificationId);
}
if (classification.getTimestamp() < branch.headTimestamp()) {
throw new BadRequestException("Classification '%s' on branch '%s' is stale (classification timestamp: %s, head timestamp: %s).",
classificationId,
branchPath,
classification.getTimestamp(),
branch.headTimestamp());
}
final ClassificationTracker classificationTracker = context.service(ClassificationTracker.class);
// Signal the state change
classificationTracker.classificationSaving(classificationId);
final SubMonitor subMonitor = SubMonitor.convert(monitor, "Persisting changes", 6);
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder = BulkRequest.create();
applyChanges(subMonitor, context, bulkRequestBuilder);
final Request<BranchContext, CommitResult> commitRequest = SnomedRequests.prepareCommit()
.setBody(bulkRequestBuilder)
.setCommitComment(commitComment)
.setParentContextDescription(DatastoreLockContextDescriptions.SAVE_CLASSIFICATION_RESULTS)
.setAuthor(userId)
.build();
final CommitResult commitResult = new IdRequest<>(commitRequest)
.execute(context);
classificationTracker.classificationSaved(classificationId, commitResult.getCommitTimestamp());
return Boolean.TRUE;
}
private void applyChanges(final SubMonitor subMonitor,
final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder) {
final SnomedNamespaceAndModuleAssigner assigner = createNamespaceAndModuleAssigner(context);
final Set<String> conceptIdsToSkip = mergeEquivalentConcepts(context, bulkRequestBuilder, assigner);
applyRelationshipChanges(context, bulkRequestBuilder, assigner, conceptIdsToSkip);
if (handleConcreteDomains) {
// CD member support in configuration overrides the flag on the save request
final SnomedCoreConfiguration snomedCoreConfiguration = context.service(SnomedCoreConfiguration.class);
if (snomedCoreConfiguration.isConcreteDomainSupported()) {
applyConcreteDomainChanges(context, bulkRequestBuilder, assigner, conceptIdsToSkip);
}
}
}
private void applyRelationshipChanges(final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final Set<String> conceptIdsToSkip) {
final RelationshipChangeSearchRequestBuilder relationshipRequestBuilder = ClassificationRequests.prepareSearchRelationshipChange()
.setLimit(SCROLL_LIMIT)
.setExpand("relationship(inferredOnly:true)")
.filterByClassificationId(classificationId);
final SearchResourceRequestIterator<RelationshipChangeSearchRequestBuilder, RelationshipChanges> relationshipIterator =
new SearchResourceRequestIterator<>(relationshipRequestBuilder,
r -> r.build().execute(context));
while (relationshipIterator.hasNext()) {
final RelationshipChanges nextChanges = relationshipIterator.next();
final Set<String> conceptIds = nextChanges.stream()
.map(RelationshipChange::getRelationship)
.map(ReasonerRelationship::getSourceId)
.collect(Collectors.toSet());
final Set<String> originRelationshipIds = nextChanges.stream()
.filter(change -> ChangeNature.NEW.equals(change.getChangeNature())
|| ChangeNature.UPDATED.equals(change.getChangeNature()))
.map(RelationshipChange::getRelationship)
.map(ReasonerRelationship::getOriginId)
.filter(id -> id != null)
.collect(Collectors.toSet());
final Map<String, String> originSourceIds = SnomedRequests.prepareSearchRelationship()
.setLimit(originRelationshipIds.size())
.filterByIds(originRelationshipIds)
.setFields(SnomedRelationshipIndexEntry.Fields.ID, SnomedRelationshipIndexEntry.Fields.SOURCE_ID)
.build()
.execute(context)
.stream()
.collect(Collectors.toMap(
SnomedRelationship::getId, // keys: ID of the "origin" relationship
SnomedRelationship::getSourceId)); // values: source concept ID of the "origin" relationship
conceptIds.removeAll(conceptIdsToSkip);
namespaceAndModuleAssigner.collectRelationshipNamespacesAndModules(conceptIds, context);
for (final RelationshipChange change : nextChanges) {
final ReasonerRelationship relationship = change.getRelationship();
// Relationship changes related to merged concepts should not be applied
if (conceptIdsToSkip.contains(relationship.getSourceId()) || conceptIdsToSkip.contains(relationship.getDestinationId())) {
continue;
}
switch (change.getChangeNature()) {
case NEW: {
/*
* Do not "infer" any relationship that is passed down from a concept that was
* already merged by the equivalent concept merging step
*/
final String originSourceId = originSourceIds.get(relationship.getOriginId());
if (!conceptIdsToSkip.contains(originSourceId)) {
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner, relationship);
}
}
break;
case UPDATED: {
final String originSourceId = originSourceIds.get(relationship.getOriginId());
if (!conceptIdsToSkip.contains(originSourceId)) {
updateComponent(bulkRequestBuilder, namespaceAndModuleAssigner, relationship);
}
}
break;
case REDUNDANT:
removeOrDeactivate(bulkRequestBuilder, namespaceAndModuleAssigner, relationship);
break;
default:
throw new IllegalStateException(String.format("Unexpected relationship change '%s' found with SCTID '%s'.",
change.getChangeNature(),
change.getRelationship().getOriginId()));
}
}
}
namespaceAndModuleAssigner.clear();
}
private void applyConcreteDomainChanges(final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final Set<String> conceptIdsToSkip) {
final ConcreteDomainChangeSearchRequestBuilder concreteDomainRequestBuilder = ClassificationRequests.prepareSearchConcreteDomainChange()
.setLimit(SCROLL_LIMIT)
.setExpand("concreteDomainMember(inferredOnly:true)")
.filterByClassificationId(classificationId);
final SearchResourceRequestIterator<ConcreteDomainChangeSearchRequestBuilder, ConcreteDomainChanges> concreteDomainIterator =
new SearchResourceRequestIterator<>(concreteDomainRequestBuilder,
r -> r.build().execute(context));
while (concreteDomainIterator.hasNext()) {
final ConcreteDomainChanges nextChanges = concreteDomainIterator.next();
final Set<String> conceptIds = nextChanges.stream()
.map(ConcreteDomainChange::getConcreteDomainMember)
.map(m -> m.getReferencedComponentId())
.collect(Collectors.toSet());
final Set<String> originMemberIds = nextChanges.stream()
.filter(change -> ChangeNature.NEW.equals(change.getChangeNature())
|| ChangeNature.UPDATED.equals(change.getChangeNature()))
.map(ConcreteDomainChange::getConcreteDomainMember)
.map(ReasonerConcreteDomainMember::getOriginMemberId)
.filter(id -> id != null)
.collect(Collectors.toSet());
final Map<String, String> originReferencedComponentIds = SnomedRequests.prepareSearchMember()
.setLimit(originMemberIds.size())
.filterByIds(originMemberIds)
.build()
.execute(context)
.stream()
.collect(Collectors.toMap(
m -> m.getId(), // keys: ID of the "origin" CD member
m -> m.getReferencedComponent().getId())); // values: referenced component ID of the "origin" CD member
// Concepts which will be inactivated as part of equivalent concept merging should be excluded
conceptIds.removeAll(conceptIdsToSkip);
namespaceAndModuleAssigner.collectConcreteDomainModules(conceptIds, context);
for (final ConcreteDomainChange change : nextChanges) {
final ReasonerConcreteDomainMember referenceSetMember = change.getConcreteDomainMember();
// CD member changes related to merged concepts should not be applied
if (conceptIdsToSkip.contains(referenceSetMember.getReferencedComponentId())) {
continue;
}
switch (change.getChangeNature()) {
case NEW: {
/*
* Do not "infer" any CD member that is passed down from a concept that was
* already merged by the equivalent concept merging step
*/
final String originReferencedComponentId = originReferencedComponentIds.get(referenceSetMember.getOriginMemberId());
if (!conceptIdsToSkip.contains(originReferencedComponentId)) {
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner, referenceSetMember);
}
}
break;
case UPDATED: {
final String originReferencedComponentId = originReferencedComponentIds.get(referenceSetMember.getOriginMemberId());
if (!conceptIdsToSkip.contains(originReferencedComponentId)) {
updateComponent(bulkRequestBuilder, namespaceAndModuleAssigner, referenceSetMember);
}
}
break;
case REDUNDANT:
removeOrDeactivate(bulkRequestBuilder, namespaceAndModuleAssigner, referenceSetMember);
break;
default:
throw new IllegalStateException(String.format("Unexpected CD member change '%s' found with UUID '%s'.",
change.getChangeNature(),
change.getConcreteDomainMember().getOriginMemberId()));
}
}
}
namespaceAndModuleAssigner.clear();
}
private Set<String> mergeEquivalentConcepts(final BranchContext context,
final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner assigner) {
if (!fixEquivalences) {
return Collections.emptySet();
}
// XXX: Restrict merging to active components only
final String expand = "equivalentConcepts(expand("
+ "descriptions(active:true),"
+ "relationships(active:true),"
+ "inboundRelationships(active:true),"
+ "members(active:true)))";
final EquivalentConceptSetSearchRequestBuilder equivalentConceptRequest = ClassificationRequests.prepareSearchEquivalentConceptSet()
.setLimit(SCROLL_LIMIT)
.setExpand(expand)
.filterByClassificationId(classificationId);
final SearchResourceRequestIterator<EquivalentConceptSetSearchRequestBuilder, EquivalentConceptSets> equivalentConceptIterator =
new SearchResourceRequestIterator<>(equivalentConceptRequest,
r -> r.build().execute(context));
// Are there any equivalent concepts present?
if (!equivalentConceptIterator.hasNext()) {
return Collections.emptySet();
}
final Multimap<SnomedConcept, SnomedConcept> equivalentConcepts = HashMultimap.create();
while (equivalentConceptIterator.hasNext()) {
final EquivalentConceptSets nextBatch = equivalentConceptIterator.next();
for (final EquivalentConceptSet equivalentSet : nextBatch) {
if (equivalentSet.isUnsatisfiable()) {
continue;
}
final List<SnomedConcept> conceptsToRemove = newArrayList(equivalentSet.getEquivalentConcepts());
final SnomedConcept conceptToKeep = conceptsToRemove.remove(0);
equivalentConcepts.putAll(conceptToKeep, conceptsToRemove);
}
}
// Were all equivalent concepts unsatisfiable?
if (equivalentConcepts.isEmpty()) {
return Collections.emptySet();
}
IEquivalentConceptMerger merger = Extensions.getFirstPriorityExtension(
IEquivalentConceptMerger.EXTENSION_POINT,
IEquivalentConceptMerger.class);
if (merger == null) {
merger = new IEquivalentConceptMerger.Default();
}
final String mergerName = merger.getClass().getSimpleName();
LOG.info("Reasoner service will use {} for equivalent concept merging.", mergerName);
final Set<String> conceptIdsToSkip = merger.merge(equivalentConcepts);
final Set<String> conceptIdsToKeep = equivalentConcepts.keySet()
.stream()
.map(SnomedConcept::getId)
.collect(Collectors.toSet());
// Prepare to provide namespace-module for inbound relationship source concepts as well
final Set<String> relationshipChangeConceptIds = newHashSet(conceptIdsToKeep);
// Add source concepts on new/about to be inactivated inbound relationships, pointing to "kept" concepts
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedRelationship relationship : conceptToKeep.getInboundRelationships()) {
if (relationship.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
relationshipChangeConceptIds.add(relationship.getSourceId());
} else if (!relationship.isActive()) {
relationshipChangeConceptIds.add(relationship.getSourceId());
}
}
}
assigner.collectRelationshipNamespacesAndModules(relationshipChangeConceptIds, context);
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedRelationship relationship : conceptToKeep.getInboundRelationships()) {
// Already handled as another concept's outbound relationship
if (relationship.getId() == null) {
continue;
}
if (relationship.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
relationship.setId(null);
addComponent(bulkRequestBuilder, assigner, relationship);
} else if (!relationship.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, relationship);
}
}
for (final SnomedRelationship relationship : conceptToKeep.getRelationships()) {
// Already handled as another concept's inbound relationship
if (relationship.getId() == null) {
continue;
}
if (relationship.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
relationship.setId(null);
addComponent(bulkRequestBuilder, assigner, relationship);
} else if (!relationship.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, relationship);
}
}
}
// CD members are always "outbound", however, so the concept SCTID set can be reduced
assigner.clear();
assigner.collectConcreteDomainModules(conceptIdsToKeep, context);
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedReferenceSetMember member : conceptToKeep.getMembers()) {
if (member.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
member.setId(null);
addComponent(bulkRequestBuilder, assigner, member);
} else if (member.getId().startsWith(IEquivalentConceptMerger.PREFIX_UPDATED)) {
// Trim the prefix from the ID to restore its original form
member.setId(member.getId().substring(IEquivalentConceptMerger.PREFIX_UPDATED.length()));
bulkRequestBuilder.add(member.toUpdateRequest());
} else if (!member.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, member);
}
}
}
// Descriptions are also "outbound"
assigner.clear();
assigner.collectRelationshipNamespacesAndModules(conceptIdsToKeep, context);
for (final SnomedConcept conceptToKeep : equivalentConcepts.keySet()) {
for (final SnomedDescription description : conceptToKeep.getDescriptions()) {
if (description.getId().startsWith(IEquivalentConceptMerger.PREFIX_NEW)) {
description.setId(null);
addComponent(bulkRequestBuilder, assigner, description);
} else if (description.getId().startsWith(IEquivalentConceptMerger.PREFIX_UPDATED)) {
// Trim the prefix from the ID to restore its original form
description.setId(description.getId().substring(IEquivalentConceptMerger.PREFIX_UPDATED.length()));
bulkRequestBuilder.add(description.toUpdateRequest());
} else if (!description.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, description);
}
}
}
// Inactivation of "removed" concepts also requires modules to be collected according to the assigner rules
assigner.clear();
assigner.collectRelationshipNamespacesAndModules(conceptIdsToSkip, context);
for (final SnomedConcept conceptToRemove : equivalentConcepts.values()) {
// Check if the concept needs to be removed or deactivated
if (!conceptToRemove.isActive()) {
removeOrDeactivate(bulkRequestBuilder, assigner, conceptToRemove);
}
}
assigner.clear();
return conceptIdsToSkip;
}
private SnomedNamespaceAndModuleAssigner createNamespaceAndModuleAssigner(final BranchContext context) {
// Override assigner type if given
final String selectedType;
if (assignerType != null) {
selectedType = assignerType;
} else {
final SnomedCoreConfiguration configuration = context.service(SnomedCoreConfiguration.class);
selectedType = configuration.getNamespaceModuleAssigner();
}
final SnomedNamespaceAndModuleAssigner assigner = SnomedNamespaceAndModuleAssigner.create(context, selectedType, moduleId, namespace);
LOG.info("Reasoner service will use {} for relationship/concrete domain namespace and module assignment.", assigner);
return assigner;
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner, final SnomedConcept concept) {
final Request<TransactionContext, Boolean> request;
if (concept.isReleased()) {
request = SnomedRequests
.prepareUpdateConcept(concept.getId())
.setModuleId(namespaceAndModuleAssigner.getRelationshipModuleId(concept.getId()))
.setActive(false)
.setInactivationProperties(new InactivationProperties("" /*RETIRED*/, Collections.emptyList()))
.build();
} else {
request = SnomedRequests
.prepareDeleteConcept(concept.getId())
.build();
}
bulkRequestBuilder.add(request);
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedRelationship relationship) {
removeOrDeactivateRelationship(bulkRequestBuilder, namespaceAndModuleAssigner, relationship.isReleased(), relationship.getId(), relationship.getSourceId());
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerRelationship relationship) {
removeOrDeactivateRelationship(bulkRequestBuilder, namespaceAndModuleAssigner, relationship.isReleased(), relationship.getOriginId(), relationship.getSourceId());
}
private void removeOrDeactivateRelationship(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final boolean released, final String relationshipId, String sourceId) {
final Request<TransactionContext, Boolean> request;
if (released) {
request = SnomedRequests
.prepareUpdateRelationship(relationshipId)
.setActive(false)
.setModuleId(namespaceAndModuleAssigner.getRelationshipModuleId(sourceId))
.build();
} else {
request = SnomedRequests
.prepareDeleteRelationship(relationshipId)
.build();
}
bulkRequestBuilder.add(request);
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedReferenceSetMember member) {
removeOrDeactivateMember(bulkRequestBuilder, namespaceAndModuleAssigner, member.isReleased(), member.getId(), member.getReferencedComponent().getId());
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerConcreteDomainMember member) {
removeOrDeactivateMember(bulkRequestBuilder, namespaceAndModuleAssigner, member.isReleased(), member.getOriginMemberId(), member.getReferencedComponentId());
}
private void removeOrDeactivateMember(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final boolean released, final String memberId, String referencedComponentId) {
final Request<TransactionContext, Boolean> request;
if (released) {
request = SnomedRequests
.prepareUpdateMember(memberId)
.setSource(ImmutableMap.<String, Object>builder()
.put(SnomedRf2Headers.FIELD_ACTIVE, false)
.put(SnomedRf2Headers.FIELD_MODULE_ID, namespaceAndModuleAssigner.getConcreteDomainModuleId(referencedComponentId))
.build())
.build();
} else {
request = SnomedRequests
.prepareDeleteMember(memberId)
.build();
}
bulkRequestBuilder.add(request);
}
private void removeOrDeactivate(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedDescription description) {
final Request<TransactionContext, Boolean> request;
if (description.isReleased()) {
request = SnomedRequests
.prepareUpdateDescription(description.getId())
.setActive(false)
.setAcceptability(ImmutableMap.of())
.build();
} else {
request = SnomedRequests
.prepareDeleteDescription(description.getId())
.build();
}
bulkRequestBuilder.add(request);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerRelationship relationship) {
final String sourceId = relationship.getSourceId();
final String typeId = relationship.getTypeId();
final String destinationId = relationship.getDestinationId();
final boolean destinationNegated = relationship.isDestinationNegated();
final String characteristicTypeId = relationship.getCharacteristicTypeId();
final int group = relationship.getGroup();
final int unionGroup = relationship.getUnionGroup();
final String modifier = relationship.getModifierId();
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
sourceId, typeId, destinationId, destinationNegated,
characteristicTypeId, group, unionGroup, modifier);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedRelationship relationship) {
final String sourceId = relationship.getSourceId();
final String typeId = relationship.getTypeId();
final String destinationId = relationship.getDestinationId();
final boolean destinationNegated = relationship.isDestinationNegated();
final String characteristicTypeId = relationship.getCharacteristicTypeId();
final int group = relationship.getGroup();
final int unionGroup = relationship.getUnionGroup();
final String modifier = relationship.getModifierId();
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
sourceId, typeId, destinationId, destinationNegated,
characteristicTypeId, group, unionGroup, modifier);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final String sourceId,
final String typeId,
final String destinationId,
final boolean destinationNegated,
final String characteristicTypeId,
final int group,
final int unionGroup,
final String modifier) {
final String moduleId = namespaceAndModuleAssigner.getRelationshipModuleId(sourceId);
final String namespace = namespaceAndModuleAssigner.getRelationshipNamespace(sourceId);
final SnomedRelationshipCreateRequestBuilder createRequest = SnomedRequests.prepareNewRelationship()
.setIdFromNamespace(namespace)
.setTypeId(typeId)
.setActive(true)
.setCharacteristicTypeId(characteristicTypeId)
.setSourceId(sourceId)
.setDestinationId(destinationId)
.setDestinationNegated(destinationNegated)
.setGroup(group)
.setUnionGroup(unionGroup)
.setModifierId(modifier)
.setModuleId(moduleId);
bulkRequestBuilder.add(createRequest);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerConcreteDomainMember member) {
final String referencedComponentId = member.getReferencedComponentId();
final String referenceSetId = member.getReferenceSetId();
final String typeId = member.getTypeId();
final String serializedValue = member.getSerializedValue();
final int group = member.getGroup();
final String characteristicTypeId = member.getCharacteristicTypeId();
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
referencedComponentId, referenceSetId, typeId,
serializedValue, group, characteristicTypeId);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final SnomedReferenceSetMember member) {
final String referencedComponentId = member.getReferencedComponent().getId();
final String referenceSetId = member.getReferenceSetId();
final String typeId = (String) member.getProperties().get(SnomedRf2Headers.FIELD_TYPE_ID);
final String serializedValue = (String) member.getProperties().get(SnomedRf2Headers.FIELD_VALUE);
final int group = (Integer) member.getProperties().get(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP);
final String characteristicTypeId = (String) member.getProperties().get(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID);
addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
referencedComponentId, referenceSetId, typeId,
serializedValue, group, characteristicTypeId);
}
private void addComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final String referencedComponentId,
final String referenceSetId,
final String typeId,
final String serializedValue,
final int group,
final String characteristicTypeId) {
final String moduleId = namespaceAndModuleAssigner.getConcreteDomainModuleId(referencedComponentId);
final SnomedRefSetMemberCreateRequestBuilder createRequest = SnomedRequests.prepareNewMember()
.setActive(true)
.setModuleId(moduleId)
.setReferencedComponentId(referencedComponentId)
.setReferenceSetId(referenceSetId)
.setProperties(ImmutableMap.of(
SnomedRf2Headers.FIELD_TYPE_ID, typeId,
SnomedRf2Headers.FIELD_VALUE, serializedValue,
SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP, group,
SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID, characteristicTypeId));
bulkRequestBuilder.add(createRequest);
}
private void addComponent(BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
SnomedDescription description) {
final String moduleId = namespaceAndModuleAssigner.getRelationshipModuleId(description.getConceptId());
final String namespace = namespaceAndModuleAssigner.getRelationshipNamespace(description.getConceptId());
final SnomedDescriptionCreateRequestBuilder createRequest = SnomedRequests.prepareNewDescription()
.setIdFromNamespace(namespace)
.setAcceptability(description.getAcceptabilityMap())
.setActive(true)
.setCaseSignificanceId(description.getCaseSignificanceId())
.setConceptId(description.getConceptId())
.setLanguageCode(description.getLanguageCode())
.setModuleId(moduleId)
.setTerm(description.getTerm())
.setTypeId(description.getTypeId());
bulkRequestBuilder.add(createRequest);
}
private void updateComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerRelationship relationship) {
final SnomedRelationshipUpdateRequestBuilder updateRequest = SnomedRequests
.prepareUpdateRelationship(relationship.getOriginId())
.setModuleId(namespaceAndModuleAssigner.getRelationshipModuleId(relationship.getSourceId()))
.setGroup(relationship.getGroup());
bulkRequestBuilder.add(updateRequest);
}
private void updateComponent(final BulkRequestBuilder<TransactionContext> bulkRequestBuilder,
final SnomedNamespaceAndModuleAssigner namespaceAndModuleAssigner,
final ReasonerConcreteDomainMember referenceSetMember) {
final SnomedRefSetMemberUpdateRequestBuilder updateRequest = SnomedRequests
.prepareUpdateMember(referenceSetMember.getOriginMemberId())
.setSource(ImmutableMap.<String,Object>of(
SnomedRf2Headers.FIELD_VALUE, referenceSetMember.getSerializedValue(),
SnomedRf2Headers.FIELD_MODULE_ID, namespaceAndModuleAssigner.getConcreteDomainModuleId(referenceSetMember.getReferencedComponentId())
));
bulkRequestBuilder.add(updateRequest);
}
@Override
public String getOperation() {
return Permission.OPERATION_CLASSIFY;
}
}
| feat(snomed): Create inferred relationships with value in SaveJobRequest | snomed/com.b2international.snowowl.snomed.reasoner/src/com/b2international/snowowl/snomed/reasoner/request/SaveJobRequest.java | feat(snomed): Create inferred relationships with value in SaveJobRequest | <ide><path>nomed/com.b2international.snowowl.snomed.reasoner/src/com/b2international/snowowl/snomed/reasoner/request/SaveJobRequest.java
<ide> import com.b2international.snowowl.core.request.CommitResult;
<ide> import com.b2international.snowowl.core.request.SearchResourceRequestIterator;
<ide> import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
<del>import com.b2international.snowowl.snomed.core.domain.InactivationProperties;
<del>import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
<del>import com.b2international.snowowl.snomed.core.domain.SnomedDescription;
<del>import com.b2international.snowowl.snomed.core.domain.SnomedRelationship;
<add>import com.b2international.snowowl.snomed.core.domain.*;
<ide> import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
<ide> import com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration;
<ide> import com.b2international.snowowl.snomed.datastore.id.assigner.SnomedNamespaceAndModuleAssigner;
<ide> final String typeId = relationship.getTypeId();
<ide> final String destinationId = relationship.getDestinationId();
<ide> final boolean destinationNegated = relationship.isDestinationNegated();
<add> final RelationshipValue value = relationship.getValueAsObject();
<ide> final String characteristicTypeId = relationship.getCharacteristicTypeId();
<ide> final int group = relationship.getGroup();
<ide> final int unionGroup = relationship.getUnionGroup();
<ide> final String modifier = relationship.getModifierId();
<ide>
<ide> addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
<del> sourceId, typeId, destinationId, destinationNegated,
<add> sourceId, typeId, destinationId, destinationNegated, value,
<ide> characteristicTypeId, group, unionGroup, modifier);
<ide> }
<ide>
<ide> final String typeId = relationship.getTypeId();
<ide> final String destinationId = relationship.getDestinationId();
<ide> final boolean destinationNegated = relationship.isDestinationNegated();
<add> final RelationshipValue value = relationship.getValueAsObject();
<ide> final String characteristicTypeId = relationship.getCharacteristicTypeId();
<ide> final int group = relationship.getGroup();
<ide> final int unionGroup = relationship.getUnionGroup();
<ide> final String modifier = relationship.getModifierId();
<ide>
<ide> addComponent(bulkRequestBuilder, namespaceAndModuleAssigner,
<del> sourceId, typeId, destinationId, destinationNegated,
<add> sourceId, typeId, destinationId, destinationNegated, value,
<ide> characteristicTypeId, group, unionGroup, modifier);
<ide> }
<ide>
<ide> final String typeId,
<ide> final String destinationId,
<ide> final boolean destinationNegated,
<add> final RelationshipValue value,
<ide> final String characteristicTypeId,
<ide> final int group,
<ide> final int unionGroup,
<ide> .setSourceId(sourceId)
<ide> .setDestinationId(destinationId)
<ide> .setDestinationNegated(destinationNegated)
<add> .setValue(value)
<ide> .setGroup(group)
<ide> .setUnionGroup(unionGroup)
<ide> .setModifierId(modifier) |
|
JavaScript | apache-2.0 | 7a1682ef20e70969c9a20a9f528e28958bc5b3c8 | 0 | nroutasuo/level13,nroutasuo/level13 | // A class that checks raw user input from the DOM and passes game-related actions to PlayerActionFunctions
define(['ash',
'core/ExceptionHandler',
'game/GameGlobals',
'game/GlobalSignals',
'game/constants/GameConstants',
'game/constants/CampConstants',
'game/constants/UIConstants',
'game/constants/ItemConstants',
'game/constants/PlayerActionConstants',
'game/constants/PositionConstants',
'game/helpers/ui/UIPopupManager',
'game/vos/ResourcesVO',
'utils/MathUtils',
],
function (Ash, ExceptionHandler, GameGlobals, GlobalSignals, GameConstants, CampConstants, UIConstants, ItemConstants, PlayerActionConstants, PositionConstants, UIPopupManager, ResourcesVO, MathUtils) {
// TODO separate generic utils and tabs handling to a different file
var UIFunctions = Ash.Class.extend({
context: "UIFunctions",
popupManager: null,
elementIDs: {
tabs: {
bag: "switch-bag",
followers: "switch-followers",
projects: "switch-projects",
map: "switch-map",
trade: "switch-trade",
in: "switch-in",
out: "switch-out",
upgrades: "switch-upgrades",
blueprints: "switch-blueprints",
world: "switch-world",
embark: "switch-embark"
},
},
names: {
resources: {
stamina: "stamina",
resource_metal: "metal",
resource_fuel: "fuel",
resource_rubber: "rubber",
resource_rope: "rope",
resource_food: "food",
resource_water: "water",
resource_concrete: "concrete",
resource_herbs: "herbs",
resource_medicine: "medicine",
resource_tools: "tools",
item_exploration_1: "lock pick",
rumours: "rumours",
evidence: "evidence",
}
},
constructor: function () {
this.popupManager = new UIPopupManager(this);
},
init: function () {
this.generateElements();
this.hideElements();
this.registerListeners();
this.registerGlobalMouseEvents();
},
registerListeners: function () {
var elementIDs = this.elementIDs;
var uiFunctions = this;
$(window).resize(this.onResize);
// Switch tabs
var onTabClicked = this.onTabClicked;
$.each($("#switch-tabs li"), function () {
$(this).click(function () {
if (!($(this).hasClass("disabled"))) {
onTabClicked(this.id, GameGlobals.gameState, uiFunctions);
}
});
});
// Collapsible divs
this.registerCollapsibleContainerListeners("");
// Steppers and stepper buttons
this.registerStepperListeners("");
// Action buttons buttons
this.registerActionButtonListeners("");
// Meta/non-action buttons
$("#btn-save").click(function (e) {
GlobalSignals.saveGameSignal.dispatch(true);
});
$("#btn-restart").click(function (e) {
uiFunctions.showConfirmation(
"Do you want to restart the game? Your progress will be lost.",
function () {
uiFunctions.restart();
});
});
$("#btn-more").click(function (e) {
var wasVisible = $("#game-options-extended").is(":visible");
$("#game-options-extended").toggle();
$(this).text(wasVisible ? "more" : "less");
GlobalSignals.elementToggledSignal.dispatch($(this), !wasVisible);
});
$("#btn-importexport").click(function (e) {
gtag('event', 'screen_view', {
'screen_name': "popup-manage-save"
});
uiFunctions.showManageSave();
});
$("#btn-info").click(function (e) {
gtag('event', 'screen_view', {
'screen_name': "popup-game-info"
});
uiFunctions.showInfoPopup("Level 13", uiFunctions.getGameInfoDiv());
});
$("#in-assign-workers input.amount").change(function (e) {
var assignment = {};
for (var key in CampConstants.workerTypes) {
assignment[key] = parseInt($("#stepper-" + key + " input").val());
}
GameGlobals.playerActionFunctions.assignWorkers(null, assignment);
});
// Buttons: In: Other
$("#btn-header-rename").click(function (e) {
var prevCampName = GameGlobals.playerActionFunctions.getNearestCampName();
uiFunctions.showInput(
"Rename Camp",
"Give your camp a new name",
prevCampName,
true,
function (input) {
GameGlobals.playerActionFunctions.setNearestCampName(input);
}
);
});
$(document).on("keyup", this.onKeyUp);
},
registerGlobalMouseEvents: function () {
GameGlobals.gameState.uiStatus.mouseDown = false;
GameGlobals.gameState.uiStatus.mouseDownElement = null;
$(document).on('mouseleave', function (e) {
GameGlobals.gameState.uiStatus.mouseDown = false;
GameGlobals.gameState.uiStatus.mouseDownElement = null;
});
$(document).on('mouseup', function (e) {
GameGlobals.gameState.uiStatus.mouseDown = false;
GameGlobals.gameState.uiStatus.mouseDownElement = null;
});
$(document).on('mousedown', function (e) {
GameGlobals.gameState.uiStatus.mouseDown = true;
GameGlobals.gameState.uiStatus.mouseDownElement = e.target;
});
},
registerActionButtonListeners: function (scope) {
var uiFunctions = this;
var gameState = GameGlobals.gameState;
// All action buttons
$.each($(scope + " button.action"), function () {
var $element = $(this);
if ($element.hasClass("click-bound")) {
log.w("trying to bind click twice! id: " + $element.attr("id"));
return;
}
if ($element.hasClass("action-manual-trigger")) {
return;
}
$element.addClass("click-bound");
$element.click(ExceptionHandler.wrapClick(function (e) {
var action = $(this).attr("action");
if (!action) {
log.w("No action mapped for button.");
return;
}
GlobalSignals.actionButtonClickedSignal.dispatch(action);
var param = null;
var actionIDParam = GameGlobals.playerActionsHelper.getActionIDParam(action);
if (actionIDParam) param = actionIDParam;
var isProject = $(this).hasClass("action-level-project");
if (isProject) param = $(this).attr("sector");
var locationKey = uiFunctions.getLocationKey(action);
var isStarted = GameGlobals.playerActionFunctions.startAction(action, param);
if (!isStarted)
return;
var baseId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var duration = PlayerActionConstants.getDuration(baseId);
if (duration > 0) {
GameGlobals.gameState.setActionDuration(action, locationKey, duration);
uiFunctions.startButtonDuration($(this), duration);
}
}));
});
// Special actions
$(scope + "#out-action-fight-confirm").click(function (e) {
GameGlobals.fightHelper.startFight();
});
$(scope + "#out-action-fight-close").click(function (e) {
GameGlobals.fightHelper.endFight(false);
});
$(scope + "#out-action-fight-continue").click(function (e) {
GameGlobals.fightHelper.endFight(false);
});
$(scope + "#out-action-fight-takeselected").click(function (e) {
GameGlobals.fightHelper.endFight(false);
});
$(scope + "#out-action-fight-takeall").click(function (e) {
GameGlobals.fightHelper.endFight(true);
});
$(scope + "#out-action-fight-cancel").click(function (e) {
GameGlobals.fightHelper.endFight(false);
GameGlobals.playerActionFunctions.flee();
});
$(scope + "#inn-popup-btn-cancel").click(function (e) {
uiFunctions.popupManager.closePopup("inn-popup");
});
$(scope + "#incoming-caravan-popup-cancel").click(function (e) {
uiFunctions.popupManager.closePopup("incoming-caravan-popup");
});
$(scope + " button[action='leave_camp']").click(function (e) {
gameState.uiStatus.leaveCampItems = {};
gameState.uiStatus.leaveCampRes = {};
var selectedResVO = new ResourcesVO();
$.each($("#embark-resources tr"), function () {
var resourceName = $(this).attr("id").split("-")[2];
var selectedVal = parseInt($(this).children("td").children(".stepper").children("input").val());
selectedResVO.setResource(resourceName, selectedVal);
});
var selectedItems = {};
$.each($("#embark-items tr"), function () {
var itemID = $(this).attr("id").split("-")[2];
var selectedVal = parseInt($(this).children("td").children(".stepper").children("input").val());
selectedItems[itemID] = selectedVal;
});
GameGlobals.playerActionFunctions.updateCarriedItems(selectedItems);
GameGlobals.playerActionFunctions.moveResFromCampToBag(selectedResVO);
GameGlobals.playerActionFunctions.leaveCamp();
});
// Buttons: Bag: Item details
// some in UIOoutBagSystem
},
registerCustomButtonListeners: function (scope, btnClass, fn) {
$.each($(scope + " button." + btnClass), function () {
var $element = $(this);
if ($element.hasClass("click-bound")) {
log.w("trying to bind click twice! id: " + $element.attr("id"));
return;
}
$element.addClass("click-bound");
$element.click(ExceptionHandler.wrapClick(fn));
});
},
updateButtonCooldowns: function (scope) {
scope = scope || "";
let updates = false;
let sys = this;
$.each($(scope + " button.action"), function () {
var action = $(this).attr("action");
if (action) {
sys.updateButtonCooldown($(this), action);
updates = true;
}
});
return updates;
},
registerCollapsibleContainerListeners: function (scope) {
var sys = this;
$(scope + " .collapsible-header").click(function () {
var wasVisible = $(this).next(".collapsible-content").is(":visible");
sys.toggleCollapsibleContainer($(this), !wasVisible);
});
$.each($(scope + " .collapsible-header"), function () {
sys.toggleCollapsibleContainer($(this), false);
});
},
registerStepperListeners: function (scope) {
var sys = this;
$(scope + " .stepper button").click(function (e) {
sys.onStepperButtonClicked(this, e);
});
$(scope + ' .stepper input.amount').change(function () {
sys.onStepperInputChanged(this)
});
$(scope + " .stepper input.amount").focusin(function () {
$(this).data('oldValue', $(this).val());
});
$(scope + ' .stepper input.amount').trigger("change");
// All number inputs
$(scope + " input.amount").keydown(this.onNumberInputKeyDown);
},
generateElements: function () {
this.generateTabBubbles();
this.generateResourceIndicators();
this.generateSteppers("body");
this.generateButtonOverlays("body");
this.generateCallouts("body");
// equipment stats labels
for (var bonusKey in ItemConstants.itemBonusTypes) {
var bonusType = ItemConstants.itemBonusTypes[bonusKey];
if (bonusType == ItemConstants.itemBonusTypes.fight_speed) continue;
var div = "<div id='stats-equipment-" + bonusKey + "' class='stats-indicator stats-indicator-secondary'>";
div += "<span class='label'>" + UIConstants.getItemBonusName(bonusType).replace(" ", "<br/>") + "</span>";
div += "<br/>";
div += "<span class='value'/></div>";
$("#container-equipment-stats").append(div);
}
},
hideElements: function () {
this.toggle($(".hidden-by-default"), false);
},
generateTabBubbles: function () {
$("#switch li").append("<div class='bubble' style='display:none'>1</div>");
},
generateResourceIndicators: function () {
for (var key in resourceNames) {
var name = resourceNames[key];
var isSupplies = name === resourceNames.food || name === resourceNames.water;
$("#statsbar-resources").append(UIConstants.createResourceIndicator(name, false, "resources-" + name, true, true));
$("#bag-resources").append(UIConstants.createResourceIndicator(name, false, "resources-bag-" + name, true, true));
}
},
generateCallouts: function (scope) {
// Info callouts
$.each($(scope + " .info-callout-target"), function () {
var $target = $(this);
var generated = $target.data("callout-generated");
if (generated) {
log.w("Info callout already generated! id: " + $target.attr("id") + ", scope: " + scope);
log.i($target);
return;
}
$target.wrap('<div class="callout-container"></div>');
$target.after(function () {
var description = $(this).attr("description");
var content = description;
content = '<div class="callout-arrow-up"></div><div class="info-callout-content">' + content + "</div>";
return '<div class="info-callout">' + content + '</div>'
});
$target.data("callout-generated", true);
});
// Button callouts
// TODO performance bottleneck - detach elements to edit
var uiFunctions = this;
$.each($(scope + " div.container-btn-action"), function () {
var $container = $(this);
var generated = $container.data("callout-generated");
if (generated) {
{
log.w("Button callout already generated!");
log.i($container);
}
return;
}
$container.data("callout-generated", true);
$container.wrap('<div class="callout-container"></div>');
$container.after(function () {
var button = $(this).children("button")[0];
var action = $(button).attr("action");
if (!action) {
log.w("Action button with no action ");
log.i($(button))
return "";
}
if (action === "take_all" || action === "accept_inventory" || action === "use_in_inn_cancel" || action === "fight")
return "";
return uiFunctions.generateActionButtonCallout(action);
});
});
GlobalSignals.calloutsGeneratedSignal.dispatch();
},
updateCallouts: function (scope) {
$.each($(scope + " .callout-container"), function () {
var description = $(this).children(".info-callout-target").attr("description");
$(this).find(".info-callout-content").html(description);
});
},
generateActionButtonCallout: function (action) {
var baseActionId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var content = "";
var enabledContent = "";
var disabledContent = "";
/*
var ordinal = GameGlobals.playerActionsHelper.getActionOrdinal(action);
content += "<span>" + action + " " + ordinal + "</span>"
*/
// always visible: description
var description = GameGlobals.playerActionsHelper.getDescription(action);
if (description) {
content += "<span class='action-description'>" + description + "</span>";
}
// visible if button is enabled: costs, special requirements, & risks
var costs = GameGlobals.playerActionsHelper.getCosts(action);
var hasCosts = action && costs && Object.keys(costs).length > 0;
if (hasCosts) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
for (var key in costs) {
var itemName = key.replace("item_", "");
var item = ItemConstants.getItemByID(itemName);
var name = (this.names.resources[key] ? this.names.resources[key] : item !== null ? item.name : key).toLowerCase();
var value = costs[key];
enabledContent += "<span class='action-cost action-cost-" + key + "'>" + name + ": <span class='action-cost-value'>" + UIConstants.getDisplayValue(value) + "</span><br/></span>";
}
}
var duration = PlayerActionConstants.getDuration(baseActionId);
if (duration > 0) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
enabledContent += "<span class='action-duration'>duration: " + Math.round(duration * 100) / 100 + "s</span>";
}
let specialReqs = GameGlobals.playerActionsHelper.getSpecialReqs(action);
if (specialReqs) {
let s = this.getSpecialReqsText(action);
if (s.length > 0) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
enabledContent += "<span class='action-special-reqs'>" + s + "</span>";
}
}
var encounterFactor = GameGlobals.playerActionsHelper.getEncounterFactor(action);
var injuryRiskMax = PlayerActionConstants.getInjuryProbability(action, 0);
var inventoryRiskMax = PlayerActionConstants.getLoseInventoryProbability(action, 0);
var fightRiskMax = PlayerActionConstants.getRandomEncounterProbability(baseActionId, 0, 1, encounterFactor);
var fightRiskMin = PlayerActionConstants.getRandomEncounterProbability(baseActionId, 100, 1, encounterFactor);
if (injuryRiskMax > 0 || inventoryRiskMax > 0 || fightRiskMax > 0) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
var inventoryRiskLabel = action === "despair" ? "lose items" : "lose item";
if (injuryRiskMax > 0)
enabledContent += "<span class='action-risk action-risk-injury warning'>injury: <span class='action-risk-value'></span>%</span>";
if (inventoryRiskMax > 0)
enabledContent += "<span class='action-risk action-risk-inventory warning'>" + inventoryRiskLabel + ": <span class='action-risk-value'></span>%</span>";
if (fightRiskMax > 0)
enabledContent += "<span class='action-risk action-risk-fight warning'>fight: <span class='action-risk-value'></span>%</span>";
}
// visible if button is disabled: disabled reason
if (content.length > 0 || enabledContent.length > 0) {
if (content.length > 0) disabledContent += "<hr/>";
disabledContent += "<span class='btn-disabled-reason action-cost-blocker'></span>";
}
if (enabledContent.length > 0) {
content += "<span class='btn-callout-content-enabled'>" + enabledContent + "</span>";
}
if (disabledContent.length > 0) {
content += "<span class='btn-callout-content-disabled' style='display:none'>" + disabledContent + "</span>";
}
if (content.length > 0) {
return '<div class="btn-callout"><div class="callout-arrow-up"></div><div class="btn-callout-content">' + content + '</div></div>';
} else {
log.w("No callout could be created for action button with action " + action + ". No content for callout.");
return "";
}
},
getSpecialReqsText: function (action) {
var position = GameGlobals.playerActionFunctions.playerPositionNodes.head ? GameGlobals.playerActionFunctions.playerPositionNodes.head.position : {};
let s = "";
let specialReqs = GameGlobals.playerActionsHelper.getSpecialReqs(action);
if (specialReqs) {
for (let key in specialReqs) {
switch (key) {
case "improvementsOnLevel":
let actionImprovementName = GameGlobals.playerActionsHelper.getImprovementNameForAction(action);
for (let improvementID in specialReqs[key]) {
let range = specialReqs[key][improvementID];
let count = GameGlobals.playerActionsHelper.getCurrentImprovementCountOnLevel(position.level, improvementID);
let rangeText = UIConstants.getRangeText(range);
let displayName = GameGlobals.playerActionsHelper.getImprovementDisplayName(improvementID);
if (actionImprovementName == displayName) {
displayName = "";
}
s += rangeText + " " + displayName + " on level (" + count + ")";
}
break;
default:
s += key + ": " + specialReqs[key];
log.w("unknown special req: " + key);
break;
}
}
}
s.trim();
return s;
},
generateSteppers: function (scope) {
$(scope + " .stepper").append("<button type='button' class='btn-glyph' data-type='minus' data-field=''>-</button>");
$(scope + " .stepper").append("<input class='amount' type='text' min='0' max='100' autocomplete='false' value='0' name='' tabindex='1'></input>");
$(scope + " .stepper").append("<button type='button' class='btn-glyph' data-type='plus' data-field=''>+</button>");
$(scope + " .stepper button").attr("data-field", function (i, val) {
return $(this).parent().attr("id") + "-input";
});
$(scope + " .stepper button").attr("action", function (i, val) {
return $(this).parent().attr("id") + "-" + $(this).attr("data-type");
});
$(scope + " .stepper input").attr("name", function (i, val) {
return $(this).parent().attr("id") + "-input";
});
},
generateButtonOverlays: function (scope) {
$.each($(scope + " button.action"), function () {
let $btn = $(this);
let text = $btn.text();
$btn.text("");
$btn.append("<span class='btn-label'>" + text + "</span>");
});
$(scope + " button.action").append("<div class='cooldown-action' style='display:none' />");
$(scope + " button.action").append("<div class='cooldown-duration' style='display:none' />");
$(scope + " button.action").wrap("<div class='container-btn-action' />");
$.each($(scope + " div.container-btn-action"), function () {
let $container = $(this);
if ($container.find(".cooldown-reqs")) {
log.w("generating double button overlays: " + scope);
} else {
$container.append("<div class='cooldown-reqs' />");
}
});
},
startGame: function () {
log.i("Starting game..");
var startTab = this.elementIDs.tabs.out;
var playerPos = GameGlobals.playerActionFunctions.playerPositionNodes.head.position;
if (playerPos.inCamp) startTab = this.elementIDs.tabs.in;
this.showTab(startTab);
},
/**
* Resets cooldown for an action. Should be called directly after an action is completed and any relevant popup is closed.
* @param {type} action action
*/
completeAction: function (action) {
var baseId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var cooldown = PlayerActionConstants.getCooldown(baseId);
if (cooldown > 0) {
var locationKey = this.getLocationKey(action);
GameGlobals.gameState.setActionCooldown(action, locationKey, cooldown);
if (!GameGlobals.gameState.isAutoPlaying) {
var button = $("button[action='" + action + "']");
this.startButtonCooldown($(button), cooldown);
}
}
},
showGame: function () {
this.hideGameCounter = this.hideGameCounter || 1;
this.hideGameCounter--;
if (this.hideGameCounter > 0) return;
this.setGameOverlay(false, false);
this.setGameElementsVisibility(true);
this.setUIStatus(false, false);
GlobalSignals.gameShownSignal.dispatch();
},
hideGame: function (showLoading, showThinking) {
this.hideGameCounter = this.hideGameCounter || 0;
this.hideGameCounter++;
showThinking = showThinking && !showLoading;
this.setGameOverlay(showLoading, showThinking);
this.setGameElementsVisibility(showThinking);
this.setUIStatus(true, true);
},
blockGame: function () {
this.setUIStatus(GameGlobals.gameState.uiStatus.isHidden, true);
},
unblockGame: function () {
this.setUIStatus(GameGlobals.gameState.uiStatus.isHidden, false);
},
setUIStatus: function (isHidden, isBlocked) {
isBlocked = isBlocked || isHidden;
GameGlobals.gameState.uiStatus.isHidden = isHidden;
GameGlobals.gameState.uiStatus.isBlocked = isBlocked;
},
setGameOverlay: function (isLoading, isThinking) {
isThinking = isThinking && !isLoading;
$(".loading-content").css("display", isLoading ? "block" : "none");
$(".thinking-content").css("display", isThinking ? "block" : "none");
},
setGameElementsVisibility: function (visible) {
$(".sticky-footer").css("display", visible ? "block" : "none");
$("#grid-main").css("display", visible ? "block" : "none");
$("#unit-main").css("display", visible ? "block" : "none");
},
restart: function () {
$("#log ul").empty();
this.onTabClicked(this.elementIDs.tabs.out, GameGlobals.gameState, this);
GlobalSignals.restartGameSignal.dispatch(true);
},
onResize: function () {
GlobalSignals.windowResizedSignal.dispatch();
},
getGameInfoDiv: function () {
var html = "";
html += "<span id='changelog-version'>version " + GameGlobals.changeLogHelper.getCurrentVersionNumber() + "<br/>updated " + GameGlobals.changeLogHelper.getCurrentVersionDate() + "</span>";
html += "<p>Note that this game is still in development and many features are incomplete and unbalanced. Updates might break saves. Feedback and bug reports are appreciated!</p>";
html += "<p>Feedback:<br/>" + GameConstants.getFeedbackLinksHTML() + "</p>";
html += "<p>More info:<br/><a href='faq.html' target='faq'>faq</a> | <a href='changelog.html' target='changelog'>changelog</a></p>";
return html;
},
onTabClicked: function (tabID, gameState, uiFunctions, tabProps) {
$("#switch-tabs li").removeClass("selected");
$("#switch-tabs li#" + tabID).addClass("selected");
$("#tab-header h2").text(tabID);
gtag('event', 'screen_view', {
'screen_name': tabID
});
var transition = !(gameState.uiStatus.currentTab === tabID);
var transitionTime = transition ? 200 : 0;
gameState.uiStatus.currentTab = tabID;
$.each($(".tabelement"), function () {
uiFunctions.slideToggleIf($(this), null, $(this).attr("data-tab") === tabID, transitionTime, 200);
});
$.each($(".tabbutton"), function () {
uiFunctions.slideToggleIf($(this), null, $(this).attr("data-tab") === tabID, transitionTime, 200);
});
GlobalSignals.tabChangedSignal.dispatch(tabID, tabProps);
},
onStepperButtonClicked: function (button, e) {
e.preventDefault();
var fieldName = $(button).attr('data-field');
var type = $(button).attr('data-type');
var input = $("input[name='" + fieldName + "']");
var currentVal = parseInt(input.val());
if (!isNaN(currentVal)) {
if (type == 'minus') {
var min = input.attr('min');
if (currentVal > min) {
input.val(currentVal - 1).change();
}
} else if (type == 'plus') {
var max = input.attr('max');
if (currentVal < max) {
input.val(currentVal + 1).change();
}
}
} else {
log.w("invalid stepper input value [" + fieldName + "]");
input.val(0);
}
},
onStepperInputChanged: function (input) {
var minValue = parseInt($(input).attr('min'));
var maxValue = parseInt($(input).attr('max'));
var valueCurrent = parseInt($(input).val());
var name = $(input).attr('name');
if (isNaN(valueCurrent)) {
$(this).val($(this).data('oldValue'));
return;
}
this.updateStepperButtons("#" + $(input).parent().attr("id"));
},
onKeyUp: function (e) {
var playerPos = GameGlobals.playerActionFunctions.playerPositionNodes.head.position;
if (!e.shiftKey && !playerPos.inCamp) {
if (e.keyCode == 65) {
GameGlobals.playerActionFunctions.startAction("move_sector_west");
}
if (e.keyCode == 87) {
GameGlobals.playerActionFunctions.startAction("move_sector_north");
}
if (e.keyCode == 83) {
GameGlobals.playerActionFunctions.startAction("move_sector_south")
}
if (e.keyCode == 68) {
GameGlobals.playerActionFunctions.startAction("move_sector_east")
}
if (e.keyCode == 81) {
GameGlobals.playerActionFunctions.startAction("move_sector_nw")
}
if (e.keyCode == 69) {
GameGlobals.playerActionFunctions.startAction("move_sector_ne")
}
if (e.keyCode == 90) {
GameGlobals.playerActionFunctions.startAction("move_sector_sw")
}
if (e.keyCode == 67) {
GameGlobals.playerActionFunctions.startAction("move_sector_se")
}
}
},
onNumberInputKeyDown: function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
return;
}
// Ensure that it's a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
},
onTextInputKeyDown: function (e) {
// Allow: backspace, delete, tab, escape and enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
},
onTextInputKeyUp: function (e) {
var value = $(e.target).val();
value = value.replace(/[&\/\\#,+()$~%.'":*?<>{}\[\]=]/g, '_');
$(e.target).val(value);
},
onPlayerMoved: function () {
if (GameGlobals.gameState.uiStatus.isHidden) return;
var updates = false;
updates = this.updateButtonCooldowns("") || updates;
if (updates)
GlobalSignals.updateButtonsSignal.dispatch();
},
slideToggleIf: function (element, replacement, show, durationIn, durationOut, cb) {
var visible = this.isElementToggled(element);
var toggling = ($(element).attr("data-toggling") == "true");
var sys = this;
if (show && (visible == false || visible == null) && !toggling) {
if (replacement) sys.toggle(replacement, false);
$(element).attr("data-toggling", "true");
$(element).slideToggle(durationIn, function () {
sys.toggle(element, true);
$(element).attr("data-toggling", "false");
if (cb) cb();
});
} else if (!show && (visible == true || visible == null) && !toggling) {
$(element).attr("data-toggling", "true");
$(element).slideToggle(durationOut, function () {
if (replacement) sys.toggle(replacement, true);
sys.toggle(element, false);
$(element).attr("data-toggling", "false");
if (cb) cb();
});
}
},
toggleCollapsibleContainer: function (element, show) {
var $element = typeof (element) === "string" ? $(element) : element;
if (show) {
var group = $element.parents(".collapsible-container-group");
if (group.length > 0) {
var sys = this;
$.each($(group).find(".collapsible-header"), function () {
var $child = $(this);
if ($child[0] !== $element[0]) {
sys.toggleCollapsibleContainer($child, false);
}
});
}
}
$element.toggleClass("collapsible-collapsed", !show);
$element.toggleClass("collapsible-open", show);
this.slideToggleIf($element.next(".collapsible-content"), null, show, 300, 200);
GlobalSignals.elementToggledSignal.dispatch($element, show);
},
tabToggleIf: function (element, replacement, show, durationIn, durationOut) {
var visible = $(element).is(":visible");
var toggling = ($(element).attr("data-toggling") == "true");
var sys = this;
if (show && !visible && !toggling) {
if (replacement) sys.toggle(replacement, false);
$(element).attr("data-toggling", "true");
$(element).fadeToggle(durationIn, function () {
sys.toggle(element, true);
$(element).attr("data-toggling", "false");
});
} else if (!show && visible && !toggling) {
$(element).attr("data-toggling", "true");
$(element).fadeToggle(durationOut, function () {
if (replacement) sys.toggle(replacement, true);
sys.toggle(element, false);
$(element).attr("data-toggling", "false");
});
}
},
toggle: function (element, show, signalParams) {
var $element = typeof (element) === "string" ? $(element) : element;
if (($element).length === 0)
return;
if (typeof (show) === "undefined")
show = false;
if (show === null)
show = false;
if (!show)
show = false;
if (this.isElementToggled($element) === show)
return;
$element.attr("data-visible", show);
$element.toggle(show);
// NOTE: For some reason the element isn't immediately :visible for checks in UIOutElementsSystem without the timeout
setTimeout(function () {
GlobalSignals.elementToggledSignal.dispatch(element, show, signalParams);
}, 1);
},
toggleContainer: function (element, show, signalParams) {
var $element = typeof (element) === "string" ? $(element) : element;
this.toggle($element, show, signalParams);
this.toggle($element.children("button"), show, signalParams);
},
isElementToggled: function (element) {
var $element = typeof (element) === "string" ? $(element) : element;
if (($element).length === 0)
return false;
// if several elements, return their value if all agree, otherwise null
if (($element).length > 1) {
var previousIsToggled = null;
var currentIsToggled = null;
for (var i = 0; i < ($element).length; i++) {
previousIsToggled = currentIsToggled;
currentIsToggled = this.isElementToggled($(($element)[i]));
if (i > 0 && previousIsToggled !== currentIsToggled) return null;
}
return currentIsToggled;
}
var visible = true;
var visibletag = ($element.attr("data-visible"));
if (typeof visibletag !== typeof undefined) {
visible = (visibletag == "true");
} else {
visible = null;
}
return visible;
},
isElementVisible: function (element) {
var $element = typeof (element) === "string" ? $(element) : element;
var toggled = this.isElementToggled($element);
if (toggled === false)
return false;
var $e = $element.parent();
while ($e && $e.length > 0) {
if (!$e.hasClass("collapsible-content")) {
var parentToggled = this.isElementToggled($e);
if (parentToggled === false) {
return false;
}
}
$e = $e.parent();
}
return (($element).is(":visible"));
},
stopButtonCooldown: function (button) {
$(button).children(".cooldown-action").stop(true, true);
$(button).attr("data-hasCooldown", "false");
$(button).children(".cooldown-action").css("display", "none");
$(button).children(".cooldown-action").css("width", "100%");
GlobalSignals.updateButtonsSignal.dispatch();
},
updateButtonCooldown: function (button, action) {
var baseId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var locationKey = this.getLocationKey(action);
cooldownTotal = PlayerActionConstants.getCooldown(baseId);
cooldownLeft = Math.min(cooldownTotal, GameGlobals.gameState.getActionCooldown(action, locationKey, cooldownTotal) / 1000);
durationTotal = PlayerActionConstants.getDuration(baseId);
durationLeft = Math.min(durationTotal, GameGlobals.gameState.getActionDuration(action, locationKey, durationTotal) / 1000);
if (cooldownLeft > 0) this.startButtonCooldown(button, cooldownTotal, cooldownLeft);
else this.stopButtonCooldown(button);
if (durationLeft > 0) this.startButtonDuration(button, cooldownTotal, durationLeft);
},
startButtonCooldown: function (button, cooldown, cooldownLeft) {
if (GameGlobals.gameState.uiStatus.isHidden) return;
var action = $(button).attr("action");
if (!GameGlobals.playerActionsHelper.isRequirementsMet(action)) return;
if (!cooldownLeft) cooldownLeft = cooldown;
var uiFunctions = this;
var startingWidth = (cooldownLeft / cooldown * 100);
$(button).attr("data-hasCooldown", "true");
$(button).children(".cooldown-action").stop(true, false).css("display", "inherit").css("width", startingWidth + "%").animate({
width: 0
},
cooldownLeft * 1000,
'linear',
function () {
uiFunctions.stopButtonCooldown($(this).parent());
}
);
},
stopButtonDuration: function (button) {
$(button).children(".cooldown-duration").stop(true, true);
$(button).children(".cooldown-duration").css("display", "none");
$(button).children(".cooldown-duration").css("width", "0%");
$(button).attr("data-isInProgress", "false");
},
startButtonDuration: function (button, duration, durationLeft) {
if (!durationLeft) durationLeft = duration;
var uiFunctions = this;
var startingWidth = (1 - durationLeft / duration) * 100;
$(button).attr("data-isInProgress", "true");
$(button).children(".cooldown-duration").stop(true, false).css("display", "inherit").css("width", startingWidth + "%").animate({
width: '100%'
},
durationLeft * 1000,
'linear',
function () {
uiFunctions.stopButtonDuration($(this).parent());
}
);
},
getLocationKey: function (action) {
var isLocationAction = PlayerActionConstants.isLocationAction(action);
var playerPos = GameGlobals.playerActionFunctions.playerPositionNodes.head.position;
return GameGlobals.gameState.getActionLocationKey(isLocationAction, playerPos);
},
updateStepper: function (id, val, min, max) {
var $input = $(id + " input");
var oldVal = parseInt($input.val());
var oldMin = parseInt($input.attr('min'));
var oldMax = parseInt($input.attr('max'));
if (oldVal === val && oldMin === min && oldMax === max) return;
$input.attr("min", min);
$input.attr("max", max);
$input.val(val)
this.updateStepperButtons(id);
},
updateStepperButtons: function (id) {
var $input = $(id + " input");
var name = $input.attr('name');
var minValue = parseInt($input.attr('min'));
var maxValue = parseInt($input.attr('max'));
var valueCurrent = MathUtils.clamp(parseInt($input.val()), minValue, maxValue);
var decEnabled = false;
var incEnabled = false;
if (valueCurrent > minValue) {
decEnabled = true;
} else {
$input.val(minValue);
}
if (valueCurrent < maxValue) {
incEnabled = true;
} else {
$input.val(maxValue);
}
var decBtn = $(".btn-glyph[data-type='minus'][data-field='" + name + "']");
decBtn.toggleClass("btn-disabled", !decEnabled);
decBtn.toggleClass("btn-disabled-basic", !decEnabled);
decBtn.attr("disabled", !decEnabled);
var incBtn = $(".btn-glyph[data-type='plus'][data-field='" + name + "']");
incBtn.toggleClass("btn-disabled", !incEnabled);
incBtn.toggleClass("btn-disabled-basic", !incEnabled);
incBtn.attr("disabled", !incEnabled);
},
registerLongTap: function (element, callback) {
var $element = typeof (element) === "string" ? $(element) : element;
var minTime = 1000;
var intervalTime = 200;
var cancelLongTap = function () {
mouseDown = false;
var timer = $(this).attr("data-long-tap-timeout");
var interval = $(this).attr("data-long-tap-interval");
if (!timer && !interval) return;
clearTimeout(timer);
clearInterval(interval);
$(this).attr("data-long-tap-interval", 0);
$(this).attr("data-long-tap-timeout", 0);
};
$element.on('mousedown', function (e) {
var target = e.target;
var $target = $(this);
cancelLongTap()
var timer = setTimeout(function () {
cancelLongTap()
var interval = setInterval(function () {
if (GameGlobals.gameState.uiStatus.mouseDown && GameGlobals.gameState.uiStatus.mouseDownElement == target) {
callback.apply($target, e);
} else {
cancelLongTap();
}
}, intervalTime);
$(this).attr("data-long-tap-interval", interval);
}, minTime);
$(this).attr("data-long-tap-timeout", timer);
});
$element.on('mouseleave', function (e) {
cancelLongTap();
});
$element.on('mousemove', function (e) {
cancelLongTap();
});
$element.on('mouseout', function (e) {
cancelLongTap();
});
$element.on('mouseup', function (e) {
cancelLongTap();
});
},
showTab: function (tabID, tabProps) {
this.onTabClicked(tabID, GameGlobals.gameState, this, tabProps);
},
showFight: function () {
if (GameGlobals.gameState.uiStatus.isHidden) return;
this.showSpecialPopup("fight-popup");
},
showInnPopup: function (availableFollowers) {
this.showSpecialPopup("inn-popup");
},
showIncomingCaravanPopup: function () {
this.showSpecialPopup("incoming-caravan-popup");
},
showManageSave: function () {
this.showSpecialPopup("manage-save-popup");
},
showSpecialPopup: function (popupID) {
if ($("#" + popupID).is(":visible")) return;
$("#" + popupID).wrap("<div class='popup-overlay popup-overlay-ingame' style='display:none'></div>");
var uiFunctions = this;
$(".popup-overlay").fadeIn(200, function () {
uiFunctions.popupManager.repositionPopups();
GlobalSignals.popupOpenedSignal.dispatch(popupID);
GameGlobals.gameState.isPaused = true;
$("#" + popupID).fadeIn(200, function () {
uiFunctions.toggle("#" + popupID, true);
uiFunctions.popupManager.repositionPopups();
});
GlobalSignals.elementToggledSignal.dispatch(("#" + popupID), true);
});
this.generateCallouts("#" + popupID);
},
showInfoPopup: function (title, msg, buttonLabel, resultVO, callback, isMeta) {
if (!buttonLabel) buttonLabel = "Continue";
this.popupManager.showPopup(title, msg, buttonLabel, false, resultVO, callback, null, isMeta);
},
showResultPopup: function (title, msg, resultVO, callback) {
this.popupManager.showPopup(title, msg, "Continue", false, resultVO, callback);
},
showConfirmation: function (msg, callback) {
var uiFunctions = this;
var okCallback = function (e) {
uiFunctions.popupManager.closePopup("common-popup");
callback();
};
var cancelCallback = function () {
uiFunctions.popupManager.closePopup("common-popup");
};
this.popupManager.showPopup("Confirmation", msg, "Confirm", "Cancel", null, okCallback, cancelCallback);
},
showQuestionPopup: function (title, msg, buttonLabel, cancelButtonLabel, callbackOK, callbackNo, isMeta) {
var uiFunctions = this;
var okCallback = function (e) {
uiFunctions.popupManager.closePopup("common-popup");
callbackOK();
};
var cancelCallback = function () {
uiFunctions.popupManager.closePopup("common-popup");
if (callbackNo) callbackNo();
};
this.popupManager.showPopup(title, msg, buttonLabel, cancelButtonLabel, null, okCallback, cancelCallback, isMeta);
},
showInput: function (title, msg, defaultValue, allowCancel, confirmCallback, inputCallback) {
// TODO improve input validation (check and show feedback on input, not just on confirm)
var okCallback = function () {
let input = $("#common-popup input").val();
let ok = inputCallback ? inputCallback(input) : true;
if (ok) {
confirmCallback(input);
return true;
} else {
log.w("invalid input: " + input);
return false;
}
};
let cancelButtonLabel = allowCancel ? "Cancel" : null;
this.popupManager.showPopup(title, msg, "Confirm", cancelButtonLabel, null, okCallback);
var uiFunctions = this;
var maxChar = 40;
this.toggle("#common-popup-input-container", true);
$("#common-popup-input-container input").attr("maxlength", maxChar);
$("#common-popup input").val(defaultValue);
$("#common-popup input").keydown(uiFunctions.onTextInputKeyDown);
$("#common-popup input").keyup(uiFunctions.onTextInputKeyUp);
},
});
return UIFunctions;
});
| src/game/UIFunctions.js | // A class that checks raw user input from the DOM and passes game-related actions to PlayerActionFunctions
define(['ash',
'core/ExceptionHandler',
'game/GameGlobals',
'game/GlobalSignals',
'game/constants/GameConstants',
'game/constants/CampConstants',
'game/constants/UIConstants',
'game/constants/ItemConstants',
'game/constants/PlayerActionConstants',
'game/constants/PositionConstants',
'game/helpers/ui/UIPopupManager',
'game/vos/ResourcesVO',
'utils/MathUtils',
],
function (Ash, ExceptionHandler, GameGlobals, GlobalSignals, GameConstants, CampConstants, UIConstants, ItemConstants, PlayerActionConstants, PositionConstants, UIPopupManager, ResourcesVO, MathUtils) {
// TODO separate generic utils and tabs handling to a different file
var UIFunctions = Ash.Class.extend({
context: "UIFunctions",
popupManager: null,
elementIDs: {
tabs: {
bag: "switch-bag",
followers: "switch-followers",
projects: "switch-projects",
map: "switch-map",
trade: "switch-trade",
in: "switch-in",
out: "switch-out",
upgrades: "switch-upgrades",
blueprints: "switch-blueprints",
world: "switch-world",
embark: "switch-embark"
},
},
names: {
resources: {
stamina: "stamina",
resource_metal: "metal",
resource_fuel: "fuel",
resource_rubber: "rubber",
resource_rope: "rope",
resource_food: "food",
resource_water: "water",
resource_concrete: "concrete",
resource_herbs: "herbs",
resource_medicine: "medicine",
resource_tools: "tools",
item_exploration_1: "lock pick",
rumours: "rumours",
evidence: "evidence",
}
},
constructor: function () {
this.popupManager = new UIPopupManager(this);
},
init: function () {
this.generateElements();
this.hideElements();
this.registerListeners();
this.registerGlobalMouseEvents();
},
registerListeners: function () {
var elementIDs = this.elementIDs;
var uiFunctions = this;
$(window).resize(this.onResize);
// Switch tabs
var onTabClicked = this.onTabClicked;
$.each($("#switch-tabs li"), function () {
$(this).click(function () {
if (!($(this).hasClass("disabled"))) {
onTabClicked(this.id, GameGlobals.gameState, uiFunctions);
}
});
});
// Collapsible divs
this.registerCollapsibleContainerListeners("");
// Steppers and stepper buttons
this.registerStepperListeners("");
// Action buttons buttons
this.registerActionButtonListeners("");
// Meta/non-action buttons
$("#btn-save").click(function (e) {
GlobalSignals.saveGameSignal.dispatch(true);
});
$("#btn-restart").click(function (e) {
uiFunctions.showConfirmation(
"Do you want to restart the game? Your progress will be lost.",
function () {
uiFunctions.restart();
});
});
$("#btn-more").click(function (e) {
var wasVisible = $("#game-options-extended").is(":visible");
$("#game-options-extended").toggle();
$(this).text(wasVisible ? "more" : "less");
GlobalSignals.elementToggledSignal.dispatch($(this), !wasVisible);
});
$("#btn-importexport").click(function (e) {
gtag('event', 'screen_view', {
'screen_name': "popup-manage-save"
});
uiFunctions.showManageSave();
});
$("#btn-info").click(function (e) {
gtag('event', 'screen_view', {
'screen_name': "popup-game-info"
});
uiFunctions.showInfoPopup("Level 13", uiFunctions.getGameInfoDiv());
});
$("#in-assign-workers input.amount").change(function (e) {
var assignment = {};
for (var key in CampConstants.workerTypes) {
assignment[key] = parseInt($("#stepper-" + key + " input").val());
}
GameGlobals.playerActionFunctions.assignWorkers(null, assignment);
});
// Buttons: In: Other
$("#btn-header-rename").click(function (e) {
var prevCampName = GameGlobals.playerActionFunctions.getNearestCampName();
uiFunctions.showInput(
"Rename Camp",
"Give your camp a new name",
prevCampName,
true,
function (input) {
GameGlobals.playerActionFunctions.setNearestCampName(input);
}
);
});
$(document).on("keyup", this.onKeyUp);
},
registerGlobalMouseEvents: function () {
GameGlobals.gameState.uiStatus.mouseDown = false;
GameGlobals.gameState.uiStatus.mouseDownElement = null;
$(document).on('mouseleave', function (e) {
GameGlobals.gameState.uiStatus.mouseDown = false;
GameGlobals.gameState.uiStatus.mouseDownElement = null;
});
$(document).on('mouseup', function (e) {
GameGlobals.gameState.uiStatus.mouseDown = false;
GameGlobals.gameState.uiStatus.mouseDownElement = null;
});
$(document).on('mousedown', function (e) {
GameGlobals.gameState.uiStatus.mouseDown = true;
GameGlobals.gameState.uiStatus.mouseDownElement = e.target;
});
},
registerActionButtonListeners: function (scope) {
var uiFunctions = this;
var gameState = GameGlobals.gameState;
// All action buttons
$.each($(scope + " button.action"), function () {
var $element = $(this);
if ($element.hasClass("click-bound")) {
log.w("trying to bind click twice! id: " + $element.attr("id"));
return;
}
if ($element.hasClass("action-manual-trigger")) {
return;
}
$element.addClass("click-bound");
$element.click(ExceptionHandler.wrapClick(function (e) {
var action = $(this).attr("action");
if (!action) {
log.w("No action mapped for button.");
return;
}
GlobalSignals.actionButtonClickedSignal.dispatch(action);
var param = null;
var actionIDParam = GameGlobals.playerActionsHelper.getActionIDParam(action);
if (actionIDParam) param = actionIDParam;
var isProject = $(this).hasClass("action-level-project");
if (isProject) param = $(this).attr("sector");
var locationKey = uiFunctions.getLocationKey(action);
var isStarted = GameGlobals.playerActionFunctions.startAction(action, param);
if (!isStarted)
return;
var baseId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var duration = PlayerActionConstants.getDuration(baseId);
if (duration > 0) {
GameGlobals.gameState.setActionDuration(action, locationKey, duration);
uiFunctions.startButtonDuration($(this), duration);
}
}));
});
// Special actions
$(scope + "#out-action-fight-confirm").click(function (e) {
GameGlobals.fightHelper.startFight();
});
$(scope + "#out-action-fight-close").click(function (e) {
GameGlobals.fightHelper.endFight(false);
});
$(scope + "#out-action-fight-continue").click(function (e) {
GameGlobals.fightHelper.endFight(false);
});
$(scope + "#out-action-fight-takeselected").click(function (e) {
GameGlobals.fightHelper.endFight(false);
});
$(scope + "#out-action-fight-takeall").click(function (e) {
GameGlobals.fightHelper.endFight(true);
});
$(scope + "#out-action-fight-cancel").click(function (e) {
GameGlobals.fightHelper.endFight(false);
GameGlobals.playerActionFunctions.flee();
});
$(scope + "#inn-popup-btn-cancel").click(function (e) {
uiFunctions.popupManager.closePopup("inn-popup");
});
$(scope + "#incoming-caravan-popup-cancel").click(function (e) {
uiFunctions.popupManager.closePopup("incoming-caravan-popup");
});
$(scope + " button[action='leave_camp']").click(function (e) {
gameState.uiStatus.leaveCampItems = {};
gameState.uiStatus.leaveCampRes = {};
var selectedResVO = new ResourcesVO();
$.each($("#embark-resources tr"), function () {
var resourceName = $(this).attr("id").split("-")[2];
var selectedVal = parseInt($(this).children("td").children(".stepper").children("input").val());
selectedResVO.setResource(resourceName, selectedVal);
});
var selectedItems = {};
$.each($("#embark-items tr"), function () {
var itemID = $(this).attr("id").split("-")[2];
var selectedVal = parseInt($(this).children("td").children(".stepper").children("input").val());
selectedItems[itemID] = selectedVal;
});
GameGlobals.playerActionFunctions.updateCarriedItems(selectedItems);
GameGlobals.playerActionFunctions.moveResFromCampToBag(selectedResVO);
GameGlobals.playerActionFunctions.leaveCamp();
});
// Buttons: Bag: Item details
// some in UIOoutBagSystem
},
registerCustomButtonListeners: function (scope, btnClass, fn) {
$.each($(scope + " button." + btnClass), function () {
var $element = $(this);
if ($element.hasClass("click-bound")) {
log.w("trying to bind click twice! id: " + $element.attr("id"));
return;
}
$element.addClass("click-bound");
$element.click(ExceptionHandler.wrapClick(fn));
});
},
updateButtonCooldowns: function (scope) {
scope = scope || "";
let updates = false;
let sys = this;
$.each($(scope + " button.action"), function () {
var action = $(this).attr("action");
if (action) {
sys.updateButtonCooldown($(this), action);
updates = true;
}
});
return updates;
},
registerCollapsibleContainerListeners: function (scope) {
var sys = this;
$(scope + " .collapsible-header").click(function () {
var wasVisible = $(this).next(".collapsible-content").is(":visible");
sys.toggleCollapsibleContainer($(this), !wasVisible);
});
$.each($(scope + " .collapsible-header"), function () {
sys.toggleCollapsibleContainer($(this), false);
});
},
registerStepperListeners: function (scope) {
var sys = this;
$(scope + " .stepper button").click(function (e) {
sys.onStepperButtonClicked(this, e);
});
$(scope + ' .stepper input.amount').change(function () {
sys.onStepperInputChanged(this)
});
$(scope + " .stepper input.amount").focusin(function () {
$(this).data('oldValue', $(this).val());
});
$(scope + ' .stepper input.amount').trigger("change");
// All number inputs
$(scope + " input.amount").keydown(this.onNumberInputKeyDown);
},
generateElements: function () {
this.generateTabBubbles();
this.generateResourceIndicators();
this.generateSteppers("body");
this.generateButtonOverlays("body");
this.generateCallouts("body");
// equipment stats labels
for (var bonusKey in ItemConstants.itemBonusTypes) {
var bonusType = ItemConstants.itemBonusTypes[bonusKey];
if (bonusType == ItemConstants.itemBonusTypes.fight_speed) continue;
var div = "<div id='stats-equipment-" + bonusKey + "' class='stats-indicator stats-indicator-secondary'>";
div += "<span class='label'>" + UIConstants.getItemBonusName(bonusType).replace(" ", "<br/>") + "</span>";
div += "<br/>";
div += "<span class='value'/></div>";
$("#container-equipment-stats").append(div);
}
},
hideElements: function () {
this.toggle($(".hidden-by-default"), false);
},
generateTabBubbles: function () {
$("#switch li").append("<div class='bubble' style='display:none'>1</div>");
},
generateResourceIndicators: function () {
for (var key in resourceNames) {
var name = resourceNames[key];
var isSupplies = name === resourceNames.food || name === resourceNames.water;
$("#statsbar-resources").append(UIConstants.createResourceIndicator(name, false, "resources-" + name, true, true));
$("#bag-resources").append(UIConstants.createResourceIndicator(name, false, "resources-bag-" + name, true, true));
}
},
generateCallouts: function (scope) {
// Info callouts
$.each($(scope + " .info-callout-target"), function () {
var $target = $(this);
var generated = $target.data("callout-generated");
if (generated) {
log.w("Info callout already generated! id: " + $target.attr("id") + ", scope: " + scope);
log.i($target);
return;
}
$target.wrap('<div class="callout-container"></div>');
$target.after(function () {
var description = $(this).attr("description");
var content = description;
content = '<div class="callout-arrow-up"></div><div class="info-callout-content">' + content + "</div>";
return '<div class="info-callout">' + content + '</div>'
});
$target.data("callout-generated", true);
});
// Button callouts
// TODO performance bottleneck - detach elements to edit
var uiFunctions = this;
$.each($(scope + " div.container-btn-action"), function () {
var $container = $(this);
var generated = $container.data("callout-generated");
if (generated) {
{
log.w("Button callout already generated!");
log.i($container);
}
return;
}
$container.data("callout-generated", true);
$container.wrap('<div class="callout-container"></div>');
$container.after(function () {
var button = $(this).children("button")[0];
var action = $(button).attr("action");
if (!action) {
log.w("Action button with no action ");
log.i($(button))
return "";
}
if (action === "take_all" || action === "accept_inventory" || action === "use_in_inn_cancel" || action === "fight")
return "";
return uiFunctions.generateActionButtonCallout(action);
});
});
GlobalSignals.calloutsGeneratedSignal.dispatch();
},
updateCallouts: function (scope) {
$.each($(scope + " .callout-container"), function () {
var description = $(this).children(".info-callout-target").attr("description");
$(this).find(".info-callout-content").html(description);
});
},
generateActionButtonCallout: function (action) {
var baseActionId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var content = "";
var enabledContent = "";
var disabledContent = "";
/*
var ordinal = GameGlobals.playerActionsHelper.getActionOrdinal(action);
content += "<span>" + action + " " + ordinal + "</span>"
*/
// always visible: description
var description = GameGlobals.playerActionsHelper.getDescription(action);
if (description) {
content += "<span class='action-description'>" + description + "</span>";
}
// visible if button is enabled: costs, special requirements, & risks
var costs = GameGlobals.playerActionsHelper.getCosts(action);
var hasCosts = action && costs && Object.keys(costs).length > 0;
if (hasCosts) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
for (var key in costs) {
var itemName = key.replace("item_", "");
var item = ItemConstants.getItemByID(itemName);
var name = (this.names.resources[key] ? this.names.resources[key] : item !== null ? item.name : key).toLowerCase();
var value = costs[key];
enabledContent += "<span class='action-cost action-cost-" + key + "'>" + name + ": <span class='action-cost-value'>" + UIConstants.getDisplayValue(value) + "</span><br/></span>";
}
}
var duration = PlayerActionConstants.getDuration(baseActionId);
if (duration > 0) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
enabledContent += "<span class='action-duration'>duration: " + Math.round(duration * 100) / 100 + "s</span>";
}
let specialReqs = GameGlobals.playerActionsHelper.getSpecialReqs(action);
if (specialReqs) {
let s = this.getSpecialReqsText(action);
if (s.length > 0) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
enabledContent += "<span class='action-special-reqs'>" + s + "</span>";
}
}
var encounterFactor = GameGlobals.playerActionsHelper.getEncounterFactor(action);
var injuryRiskMax = PlayerActionConstants.getInjuryProbability(action, 0);
var inventoryRiskMax = PlayerActionConstants.getLoseInventoryProbability(action, 0);
var fightRiskMax = PlayerActionConstants.getRandomEncounterProbability(baseActionId, 0, 1, encounterFactor);
var fightRiskMin = PlayerActionConstants.getRandomEncounterProbability(baseActionId, 100, 1, encounterFactor);
if (injuryRiskMax > 0 || inventoryRiskMax > 0 || fightRiskMax > 0) {
if (content.length > 0 || enabledContent.length) enabledContent += "<hr/>";
var inventoryRiskLabel = action === "despair" ? "lose items" : "lose item";
if (injuryRiskMax > 0)
enabledContent += "<span class='action-risk action-risk-injury warning'>injury: <span class='action-risk-value'></span>%</span>";
if (inventoryRiskMax > 0)
enabledContent += "<span class='action-risk action-risk-inventory warning'>" + inventoryRiskLabel + ": <span class='action-risk-value'></span>%</span>";
if (fightRiskMax > 0)
enabledContent += "<span class='action-risk action-risk-fight warning'>fight: <span class='action-risk-value'></span>%</span>";
}
// visible if button is disabled: disabled reason
if (content.length > 0 || enabledContent.length > 0) {
if (content.length > 0) disabledContent += "<hr/>";
disabledContent += "<span class='btn-disabled-reason action-cost-blocker'></span>";
}
if (enabledContent.length > 0) {
content += "<span class='btn-callout-content-enabled'>" + enabledContent + "</span>";
}
if (disabledContent.length > 0) {
content += "<span class='btn-callout-content-disabled' style='display:none'>" + disabledContent + "</span>";
}
if (content.length > 0) {
return '<div class="btn-callout"><div class="callout-arrow-up"></div><div class="btn-callout-content">' + content + '</div></div>';
} else {
log.w("No callout could be created for action button with action " + action + ". No content for callout.");
return "";
}
},
getSpecialReqsText: function (action) {
var position = GameGlobals.playerActionFunctions.playerPositionNodes.head ? GameGlobals.playerActionFunctions.playerPositionNodes.head.position : {};
let s = "";
let specialReqs = GameGlobals.playerActionsHelper.getSpecialReqs(action);
if (specialReqs) {
for (let key in specialReqs) {
switch (key) {
case "improvementsOnLevel":
let actionImprovementName = GameGlobals.playerActionsHelper.getImprovementNameForAction(action);
for (let improvementID in specialReqs[key]) {
let range = specialReqs[key][improvementID];
let count = GameGlobals.playerActionsHelper.getCurrentImprovementCountOnLevel(position.level, improvementID);
let rangeText = UIConstants.getRangeText(range);
let displayName = GameGlobals.playerActionsHelper.getImprovementDisplayName(improvementID);
if (actionImprovementName == displayName) {
displayName = "";
}
s += rangeText + " " + displayName + " on level (" + count + ")";
}
break;
default:
s += key + ": " + specialReqs[key];
log.w("unknown special req: " + key);
break;
}
}
}
s.trim();
return s;
},
generateSteppers: function (scope) {
$(scope + " .stepper").append("<button type='button' class='btn-glyph' data-type='minus' data-field=''>-</button>");
$(scope + " .stepper").append("<input class='amount' type='text' min='0' max='100' autocomplete='false' value='0' name='' tabindex='1'></input>");
$(scope + " .stepper").append("<button type='button' class='btn-glyph' data-type='plus' data-field=''>+</button>");
$(scope + " .stepper button").attr("data-field", function (i, val) {
return $(this).parent().attr("id") + "-input";
});
$(scope + " .stepper button").attr("action", function (i, val) {
return $(this).parent().attr("id") + "-" + $(this).attr("data-type");
});
$(scope + " .stepper input").attr("name", function (i, val) {
return $(this).parent().attr("id") + "-input";
});
},
generateButtonOverlays: function (scope) {
$.each($(scope + " button.action"), function () {
$btn = $(this);
var text = $btn.text();
$btn.text("");
$btn.append("<span class='btn-label'>" + text + "</span>");
});
$(scope + " button.action").append("<div class='cooldown-action' style='display:none' />");
$(scope + " button.action").append("<div class='cooldown-duration' style='display:none' />");
$(scope + " button.action").wrap("<div class='container-btn-action' />");
$(scope + " div.container-btn-action").append("<div class='cooldown-reqs' />");
},
startGame: function () {
log.i("Starting game..");
var startTab = this.elementIDs.tabs.out;
var playerPos = GameGlobals.playerActionFunctions.playerPositionNodes.head.position;
if (playerPos.inCamp) startTab = this.elementIDs.tabs.in;
this.showTab(startTab);
},
/**
* Resets cooldown for an action. Should be called directly after an action is completed and any relevant popup is closed.
* @param {type} action action
*/
completeAction: function (action) {
var baseId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var cooldown = PlayerActionConstants.getCooldown(baseId);
if (cooldown > 0) {
var locationKey = this.getLocationKey(action);
GameGlobals.gameState.setActionCooldown(action, locationKey, cooldown);
if (!GameGlobals.gameState.isAutoPlaying) {
var button = $("button[action='" + action + "']");
this.startButtonCooldown($(button), cooldown);
}
}
},
showGame: function () {
this.hideGameCounter = this.hideGameCounter || 1;
this.hideGameCounter--;
if (this.hideGameCounter > 0) return;
this.setGameOverlay(false, false);
this.setGameElementsVisibility(true);
this.setUIStatus(false, false);
GlobalSignals.gameShownSignal.dispatch();
},
hideGame: function (showLoading, showThinking) {
this.hideGameCounter = this.hideGameCounter || 0;
this.hideGameCounter++;
showThinking = showThinking && !showLoading;
this.setGameOverlay(showLoading, showThinking);
this.setGameElementsVisibility(showThinking);
this.setUIStatus(true, true);
},
blockGame: function () {
this.setUIStatus(GameGlobals.gameState.uiStatus.isHidden, true);
},
unblockGame: function () {
this.setUIStatus(GameGlobals.gameState.uiStatus.isHidden, false);
},
setUIStatus: function (isHidden, isBlocked) {
isBlocked = isBlocked || isHidden;
GameGlobals.gameState.uiStatus.isHidden = isHidden;
GameGlobals.gameState.uiStatus.isBlocked = isBlocked;
},
setGameOverlay: function (isLoading, isThinking) {
isThinking = isThinking && !isLoading;
$(".loading-content").css("display", isLoading ? "block" : "none");
$(".thinking-content").css("display", isThinking ? "block" : "none");
},
setGameElementsVisibility: function (visible) {
$(".sticky-footer").css("display", visible ? "block" : "none");
$("#grid-main").css("display", visible ? "block" : "none");
$("#unit-main").css("display", visible ? "block" : "none");
},
restart: function () {
$("#log ul").empty();
this.onTabClicked(this.elementIDs.tabs.out, GameGlobals.gameState, this);
GlobalSignals.restartGameSignal.dispatch(true);
},
onResize: function () {
GlobalSignals.windowResizedSignal.dispatch();
},
getGameInfoDiv: function () {
var html = "";
html += "<span id='changelog-version'>version " + GameGlobals.changeLogHelper.getCurrentVersionNumber() + "<br/>updated " + GameGlobals.changeLogHelper.getCurrentVersionDate() + "</span>";
html += "<p>Note that this game is still in development and many features are incomplete and unbalanced. Updates might break saves. Feedback and bug reports are appreciated!</p>";
html += "<p>Feedback:<br/>" + GameConstants.getFeedbackLinksHTML() + "</p>";
html += "<p>More info:<br/><a href='faq.html' target='faq'>faq</a> | <a href='changelog.html' target='changelog'>changelog</a></p>";
return html;
},
onTabClicked: function (tabID, gameState, uiFunctions, tabProps) {
$("#switch-tabs li").removeClass("selected");
$("#switch-tabs li#" + tabID).addClass("selected");
$("#tab-header h2").text(tabID);
gtag('event', 'screen_view', {
'screen_name': tabID
});
var transition = !(gameState.uiStatus.currentTab === tabID);
var transitionTime = transition ? 200 : 0;
gameState.uiStatus.currentTab = tabID;
$.each($(".tabelement"), function () {
uiFunctions.slideToggleIf($(this), null, $(this).attr("data-tab") === tabID, transitionTime, 200);
});
$.each($(".tabbutton"), function () {
uiFunctions.slideToggleIf($(this), null, $(this).attr("data-tab") === tabID, transitionTime, 200);
});
GlobalSignals.tabChangedSignal.dispatch(tabID, tabProps);
},
onStepperButtonClicked: function (button, e) {
e.preventDefault();
var fieldName = $(button).attr('data-field');
var type = $(button).attr('data-type');
var input = $("input[name='" + fieldName + "']");
var currentVal = parseInt(input.val());
if (!isNaN(currentVal)) {
if (type == 'minus') {
var min = input.attr('min');
if (currentVal > min) {
input.val(currentVal - 1).change();
}
} else if (type == 'plus') {
var max = input.attr('max');
if (currentVal < max) {
input.val(currentVal + 1).change();
}
}
} else {
log.w("invalid stepper input value [" + fieldName + "]");
input.val(0);
}
},
onStepperInputChanged: function (input) {
var minValue = parseInt($(input).attr('min'));
var maxValue = parseInt($(input).attr('max'));
var valueCurrent = parseInt($(input).val());
var name = $(input).attr('name');
if (isNaN(valueCurrent)) {
$(this).val($(this).data('oldValue'));
return;
}
this.updateStepperButtons("#" + $(input).parent().attr("id"));
},
onKeyUp: function (e) {
var playerPos = GameGlobals.playerActionFunctions.playerPositionNodes.head.position;
if (!e.shiftKey && !playerPos.inCamp) {
if (e.keyCode == 65) {
GameGlobals.playerActionFunctions.startAction("move_sector_west");
}
if (e.keyCode == 87) {
GameGlobals.playerActionFunctions.startAction("move_sector_north");
}
if (e.keyCode == 83) {
GameGlobals.playerActionFunctions.startAction("move_sector_south")
}
if (e.keyCode == 68) {
GameGlobals.playerActionFunctions.startAction("move_sector_east")
}
if (e.keyCode == 81) {
GameGlobals.playerActionFunctions.startAction("move_sector_nw")
}
if (e.keyCode == 69) {
GameGlobals.playerActionFunctions.startAction("move_sector_ne")
}
if (e.keyCode == 90) {
GameGlobals.playerActionFunctions.startAction("move_sector_sw")
}
if (e.keyCode == 67) {
GameGlobals.playerActionFunctions.startAction("move_sector_se")
}
}
},
onNumberInputKeyDown: function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
return;
}
// Ensure that it's a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
},
onTextInputKeyDown: function (e) {
// Allow: backspace, delete, tab, escape and enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
},
onTextInputKeyUp: function (e) {
var value = $(e.target).val();
value = value.replace(/[&\/\\#,+()$~%.'":*?<>{}\[\]=]/g, '_');
$(e.target).val(value);
},
onPlayerMoved: function () {
if (GameGlobals.gameState.uiStatus.isHidden) return;
var updates = false;
updates = this.updateButtonCooldowns("") || updates;
if (updates)
GlobalSignals.updateButtonsSignal.dispatch();
},
slideToggleIf: function (element, replacement, show, durationIn, durationOut, cb) {
var visible = this.isElementToggled(element);
var toggling = ($(element).attr("data-toggling") == "true");
var sys = this;
if (show && (visible == false || visible == null) && !toggling) {
if (replacement) sys.toggle(replacement, false);
$(element).attr("data-toggling", "true");
$(element).slideToggle(durationIn, function () {
sys.toggle(element, true);
$(element).attr("data-toggling", "false");
if (cb) cb();
});
} else if (!show && (visible == true || visible == null) && !toggling) {
$(element).attr("data-toggling", "true");
$(element).slideToggle(durationOut, function () {
if (replacement) sys.toggle(replacement, true);
sys.toggle(element, false);
$(element).attr("data-toggling", "false");
if (cb) cb();
});
}
},
toggleCollapsibleContainer: function (element, show) {
var $element = typeof (element) === "string" ? $(element) : element;
if (show) {
var group = $element.parents(".collapsible-container-group");
if (group.length > 0) {
var sys = this;
$.each($(group).find(".collapsible-header"), function () {
var $child = $(this);
if ($child[0] !== $element[0]) {
sys.toggleCollapsibleContainer($child, false);
}
});
}
}
$element.toggleClass("collapsible-collapsed", !show);
$element.toggleClass("collapsible-open", show);
this.slideToggleIf($element.next(".collapsible-content"), null, show, 300, 200);
GlobalSignals.elementToggledSignal.dispatch($element, show);
},
tabToggleIf: function (element, replacement, show, durationIn, durationOut) {
var visible = $(element).is(":visible");
var toggling = ($(element).attr("data-toggling") == "true");
var sys = this;
if (show && !visible && !toggling) {
if (replacement) sys.toggle(replacement, false);
$(element).attr("data-toggling", "true");
$(element).fadeToggle(durationIn, function () {
sys.toggle(element, true);
$(element).attr("data-toggling", "false");
});
} else if (!show && visible && !toggling) {
$(element).attr("data-toggling", "true");
$(element).fadeToggle(durationOut, function () {
if (replacement) sys.toggle(replacement, true);
sys.toggle(element, false);
$(element).attr("data-toggling", "false");
});
}
},
toggle: function (element, show, signalParams) {
var $element = typeof (element) === "string" ? $(element) : element;
if (($element).length === 0)
return;
if (typeof (show) === "undefined")
show = false;
if (show === null)
show = false;
if (!show)
show = false;
if (this.isElementToggled($element) === show)
return;
$element.attr("data-visible", show);
$element.toggle(show);
// NOTE: For some reason the element isn't immediately :visible for checks in UIOutElementsSystem without the timeout
setTimeout(function () {
GlobalSignals.elementToggledSignal.dispatch(element, show, signalParams);
}, 1);
},
toggleContainer: function (element, show, signalParams) {
var $element = typeof (element) === "string" ? $(element) : element;
this.toggle($element, show, signalParams);
this.toggle($element.children("button"), show, signalParams);
},
isElementToggled: function (element) {
var $element = typeof (element) === "string" ? $(element) : element;
if (($element).length === 0)
return false;
// if several elements, return their value if all agree, otherwise null
if (($element).length > 1) {
var previousIsToggled = null;
var currentIsToggled = null;
for (var i = 0; i < ($element).length; i++) {
previousIsToggled = currentIsToggled;
currentIsToggled = this.isElementToggled($(($element)[i]));
if (i > 0 && previousIsToggled !== currentIsToggled) return null;
}
return currentIsToggled;
}
var visible = true;
var visibletag = ($element.attr("data-visible"));
if (typeof visibletag !== typeof undefined) {
visible = (visibletag == "true");
} else {
visible = null;
}
return visible;
},
isElementVisible: function (element) {
var $element = typeof (element) === "string" ? $(element) : element;
var toggled = this.isElementToggled($element);
if (toggled === false)
return false;
var $e = $element.parent();
while ($e && $e.length > 0) {
if (!$e.hasClass("collapsible-content")) {
var parentToggled = this.isElementToggled($e);
if (parentToggled === false) {
return false;
}
}
$e = $e.parent();
}
return (($element).is(":visible"));
},
stopButtonCooldown: function (button) {
$(button).children(".cooldown-action").stop(true, true);
$(button).attr("data-hasCooldown", "false");
$(button).children(".cooldown-action").css("display", "none");
$(button).children(".cooldown-action").css("width", "100%");
GlobalSignals.updateButtonsSignal.dispatch();
},
updateButtonCooldown: function (button, action) {
var baseId = GameGlobals.playerActionsHelper.getBaseActionID(action);
var locationKey = this.getLocationKey(action);
cooldownTotal = PlayerActionConstants.getCooldown(baseId);
cooldownLeft = Math.min(cooldownTotal, GameGlobals.gameState.getActionCooldown(action, locationKey, cooldownTotal) / 1000);
durationTotal = PlayerActionConstants.getDuration(baseId);
durationLeft = Math.min(durationTotal, GameGlobals.gameState.getActionDuration(action, locationKey, durationTotal) / 1000);
if (cooldownLeft > 0) this.startButtonCooldown(button, cooldownTotal, cooldownLeft);
else this.stopButtonCooldown(button);
if (durationLeft > 0) this.startButtonDuration(button, cooldownTotal, durationLeft);
},
startButtonCooldown: function (button, cooldown, cooldownLeft) {
if (GameGlobals.gameState.uiStatus.isHidden) return;
var action = $(button).attr("action");
if (!GameGlobals.playerActionsHelper.isRequirementsMet(action)) return;
if (!cooldownLeft) cooldownLeft = cooldown;
var uiFunctions = this;
var startingWidth = (cooldownLeft / cooldown * 100);
$(button).attr("data-hasCooldown", "true");
$(button).children(".cooldown-action").stop(true, false).css("display", "inherit").css("width", startingWidth + "%").animate({
width: 0
},
cooldownLeft * 1000,
'linear',
function () {
uiFunctions.stopButtonCooldown($(this).parent());
}
);
},
stopButtonDuration: function (button) {
$(button).children(".cooldown-duration").stop(true, true);
$(button).children(".cooldown-duration").css("display", "none");
$(button).children(".cooldown-duration").css("width", "0%");
$(button).attr("data-isInProgress", "false");
},
startButtonDuration: function (button, duration, durationLeft) {
if (!durationLeft) durationLeft = duration;
var uiFunctions = this;
var startingWidth = (1 - durationLeft / duration) * 100;
$(button).attr("data-isInProgress", "true");
$(button).children(".cooldown-duration").stop(true, false).css("display", "inherit").css("width", startingWidth + "%").animate({
width: '100%'
},
durationLeft * 1000,
'linear',
function () {
uiFunctions.stopButtonDuration($(this).parent());
}
);
},
getLocationKey: function (action) {
var isLocationAction = PlayerActionConstants.isLocationAction(action);
var playerPos = GameGlobals.playerActionFunctions.playerPositionNodes.head.position;
return GameGlobals.gameState.getActionLocationKey(isLocationAction, playerPos);
},
updateStepper: function (id, val, min, max) {
var $input = $(id + " input");
var oldVal = parseInt($input.val());
var oldMin = parseInt($input.attr('min'));
var oldMax = parseInt($input.attr('max'));
if (oldVal === val && oldMin === min && oldMax === max) return;
$input.attr("min", min);
$input.attr("max", max);
$input.val(val)
this.updateStepperButtons(id);
},
updateStepperButtons: function (id) {
var $input = $(id + " input");
var name = $input.attr('name');
var minValue = parseInt($input.attr('min'));
var maxValue = parseInt($input.attr('max'));
var valueCurrent = MathUtils.clamp(parseInt($input.val()), minValue, maxValue);
var decEnabled = false;
var incEnabled = false;
if (valueCurrent > minValue) {
decEnabled = true;
} else {
$input.val(minValue);
}
if (valueCurrent < maxValue) {
incEnabled = true;
} else {
$input.val(maxValue);
}
var decBtn = $(".btn-glyph[data-type='minus'][data-field='" + name + "']");
decBtn.toggleClass("btn-disabled", !decEnabled);
decBtn.toggleClass("btn-disabled-basic", !decEnabled);
decBtn.attr("disabled", !decEnabled);
var incBtn = $(".btn-glyph[data-type='plus'][data-field='" + name + "']");
incBtn.toggleClass("btn-disabled", !incEnabled);
incBtn.toggleClass("btn-disabled-basic", !incEnabled);
incBtn.attr("disabled", !incEnabled);
},
registerLongTap: function (element, callback) {
var $element = typeof (element) === "string" ? $(element) : element;
var minTime = 1000;
var intervalTime = 200;
var cancelLongTap = function () {
mouseDown = false;
var timer = $(this).attr("data-long-tap-timeout");
var interval = $(this).attr("data-long-tap-interval");
if (!timer && !interval) return;
clearTimeout(timer);
clearInterval(interval);
$(this).attr("data-long-tap-interval", 0);
$(this).attr("data-long-tap-timeout", 0);
};
$element.on('mousedown', function (e) {
var target = e.target;
var $target = $(this);
cancelLongTap()
var timer = setTimeout(function () {
cancelLongTap()
var interval = setInterval(function () {
if (GameGlobals.gameState.uiStatus.mouseDown && GameGlobals.gameState.uiStatus.mouseDownElement == target) {
callback.apply($target, e);
} else {
cancelLongTap();
}
}, intervalTime);
$(this).attr("data-long-tap-interval", interval);
}, minTime);
$(this).attr("data-long-tap-timeout", timer);
});
$element.on('mouseleave', function (e) {
cancelLongTap();
});
$element.on('mousemove', function (e) {
cancelLongTap();
});
$element.on('mouseout', function (e) {
cancelLongTap();
});
$element.on('mouseup', function (e) {
cancelLongTap();
});
},
showTab: function (tabID, tabProps) {
this.onTabClicked(tabID, GameGlobals.gameState, this, tabProps);
},
showFight: function () {
if (GameGlobals.gameState.uiStatus.isHidden) return;
this.showSpecialPopup("fight-popup");
},
showInnPopup: function (availableFollowers) {
this.showSpecialPopup("inn-popup");
},
showIncomingCaravanPopup: function () {
this.showSpecialPopup("incoming-caravan-popup");
},
showManageSave: function () {
this.showSpecialPopup("manage-save-popup");
},
showSpecialPopup: function (popupID) {
if ($("#" + popupID).is(":visible")) return;
$("#" + popupID).wrap("<div class='popup-overlay popup-overlay-ingame' style='display:none'></div>");
var uiFunctions = this;
$(".popup-overlay").fadeIn(200, function () {
uiFunctions.popupManager.repositionPopups();
GlobalSignals.popupOpenedSignal.dispatch(popupID);
GameGlobals.gameState.isPaused = true;
$("#" + popupID).fadeIn(200, function () {
uiFunctions.toggle("#" + popupID, true);
uiFunctions.popupManager.repositionPopups();
});
GlobalSignals.elementToggledSignal.dispatch(("#" + popupID), true);
});
this.generateCallouts("#" + popupID);
},
showInfoPopup: function (title, msg, buttonLabel, resultVO, callback, isMeta) {
if (!buttonLabel) buttonLabel = "Continue";
this.popupManager.showPopup(title, msg, buttonLabel, false, resultVO, callback, null, isMeta);
},
showResultPopup: function (title, msg, resultVO, callback) {
this.popupManager.showPopup(title, msg, "Continue", false, resultVO, callback);
},
showConfirmation: function (msg, callback) {
var uiFunctions = this;
var okCallback = function (e) {
uiFunctions.popupManager.closePopup("common-popup");
callback();
};
var cancelCallback = function () {
uiFunctions.popupManager.closePopup("common-popup");
};
this.popupManager.showPopup("Confirmation", msg, "Confirm", "Cancel", null, okCallback, cancelCallback);
},
showQuestionPopup: function (title, msg, buttonLabel, cancelButtonLabel, callbackOK, callbackNo, isMeta) {
var uiFunctions = this;
var okCallback = function (e) {
uiFunctions.popupManager.closePopup("common-popup");
callbackOK();
};
var cancelCallback = function () {
uiFunctions.popupManager.closePopup("common-popup");
if (callbackNo) callbackNo();
};
this.popupManager.showPopup(title, msg, buttonLabel, cancelButtonLabel, null, okCallback, cancelCallback, isMeta);
},
showInput: function (title, msg, defaultValue, allowCancel, confirmCallback, inputCallback) {
// TODO improve input validation (check and show feedback on input, not just on confirm)
var okCallback = function () {
let input = $("#common-popup input").val();
let ok = inputCallback ? inputCallback(input) : true;
if (ok) {
confirmCallback(input);
return true;
} else {
log.w("invalid input: " + input);
return false;
}
};
let cancelButtonLabel = allowCancel ? "Cancel" : null;
this.popupManager.showPopup(title, msg, "Confirm", cancelButtonLabel, null, okCallback);
var uiFunctions = this;
var maxChar = 40;
this.toggle("#common-popup-input-container", true);
$("#common-popup-input-container input").attr("maxlength", maxChar);
$("#common-popup input").val(defaultValue);
$("#common-popup input").keydown(uiFunctions.onTextInputKeyDown);
$("#common-popup input").keyup(uiFunctions.onTextInputKeyUp);
},
});
return UIFunctions;
});
| [qa] fix generating double button overlays
| src/game/UIFunctions.js | [qa] fix generating double button overlays | <ide><path>rc/game/UIFunctions.js
<ide>
<ide> generateButtonOverlays: function (scope) {
<ide> $.each($(scope + " button.action"), function () {
<del> $btn = $(this);
<del> var text = $btn.text();
<add> let $btn = $(this);
<add> let text = $btn.text();
<ide> $btn.text("");
<ide> $btn.append("<span class='btn-label'>" + text + "</span>");
<ide> });
<ide> $(scope + " button.action").append("<div class='cooldown-action' style='display:none' />");
<ide> $(scope + " button.action").append("<div class='cooldown-duration' style='display:none' />");
<ide> $(scope + " button.action").wrap("<div class='container-btn-action' />");
<del> $(scope + " div.container-btn-action").append("<div class='cooldown-reqs' />");
<add> $.each($(scope + " div.container-btn-action"), function () {
<add> let $container = $(this);
<add> if ($container.find(".cooldown-reqs")) {
<add> log.w("generating double button overlays: " + scope);
<add> } else {
<add> $container.append("<div class='cooldown-reqs' />");
<add> }
<add> });
<ide> },
<ide>
<ide> startGame: function () { |
|
Java | bsd-3-clause | bd556c5b3613abd616457e263fee825b03f2c381 | 0 | adamretter/j8fu | /**
* Copyright © 2016, Evolved Binary Ltd. <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.evolvedbinary.j8fu;
import com.evolvedbinary.j8fu.tuple.*;
import java.util.*;
import java.util.function.Supplier;
import static com.evolvedbinary.j8fu.Either.Left;
import static com.evolvedbinary.j8fu.Either.Right;
import static com.evolvedbinary.j8fu.tuple.Tuple.Tuple;
/**
* Functional utility methods that are missing from {@link java.util.Optional}
*
* @author <a href="mailto:[email protected]">Adam Retter</a>
*/
public class OptionalUtil {
/**
* Return the left Optional if present, else the right Optional.
*
* @param left The left of the disjunction
* @param right The right of the disjunction
*
* @return left if present, else right
*
* @param <T> The type of the Optionals
*/
public static <T> Optional<T> or(final Optional<T> left, final Optional<T> right) {
if(left.isPresent()) {
return left;
} else {
return right;
}
}
/**
* A lazy version of {@link #or(Optional, Optional)}.
*
* @param left The left of the disjunction
* @param right A lazily evaluated supplier of Optional for the right of the disjunction,
* only evaluated if the left is empty
*
* @return left if present, else the evaluation of the the right
*
* @param <T> The type of the Optionals
*/
public static <T> Optional<T> or(final Optional<T> left, final Supplier<Optional<T>> right) {
if(left.isPresent()) {
return left;
} else {
return right.get();
}
}
/**
* Constructs a Tuple if both Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2> Optional<Tuple2<T1, T2>> and(final Optional<T1> _1, final Optional<T2> _2) {
return _1.flatMap(t1 -> _2.map(t2 -> Tuple(t1, t2)));
}
/**
* Constructs a Tuple if all three Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3> Optional<Tuple3<T1, T2, T3>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.map(t3 -> Tuple(t1, t2, t3))));
}
/**
* Constructs a Tuple if all four Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
* @param _4 The fourth Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
* @param <T4> The type of the fourth value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3, T4> Optional<Tuple4<T1, T2, T3, T4>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3, final Optional<T4> _4) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.flatMap(t3 -> _4.map(t4 -> Tuple(t1, t2, t3, t4)))));
}
/**
* Constructs a Tuple if all five Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
* @param _4 The fourth Optional
* @param _5 The fifth Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
* @param <T4> The type of the fourth value
* @param <T5> The type of the fifth value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3, T4, T5> Optional<Tuple5<T1, T2, T3, T4, T5>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3, final Optional<T4> _4, final Optional<T5> _5) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.flatMap(t3 -> _4.flatMap(t4 -> _5.map(t5 -> Tuple(t1, t2, t3, t4, t5))))));
}
/**
* Constructs a Tuple if all six Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
* @param _4 The fourth Optional
* @param _5 The fifth Optional
* @param _6 The sixth Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
* @param <T4> The type of the fourth value
* @param <T5> The type of the fifth value
* @param <T6> The type of the sixth value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3, T4, T5, T6> Optional<Tuple6<T1, T2, T3, T4, T5, T6>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3, final Optional<T4> _4, final Optional<T5> _5, final Optional<T6> _6) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.flatMap(t3 -> _4.flatMap(t4 -> _5.flatMap(t5 -> _6.map(t6 -> Tuple(t1, t2, t3, t4, t5, t6)))))));
}
/**
* If the optional is present, then its value is returned as the
* right of a disjunction, otherwise the left of the disjunction is
* returned with the value {@code null}.
*
* This is basically the same as calling {@link #toRight(Object, Optional)}
* with {@code null} as the left argument.
*
* @param optional the optional to create an Either from.
* @return The disjunction.
*/
private static <L, R> Either<L,R> toEither(final Optional<R> optional) {
return toRight(null, optional);
}
/**
* If the optional is present, then its value is returned as the
* right of a disjunction, otherwise the left of the disjunction is
* returned with the value {@code Optional.empty()}.
*
* This is basically the same as calling {@link #toRight(Object, Optional)}
* with {@code Optional.empty()} as the left argument.
*
* @param optional the optional to create an Either from.
* @return The disjunction.
*/
private static <L, R> Either<Optional<L>, R> toEitherOpt(final Optional<R> optional) {
return optional.map(Either::<Optional<L>, R>Right).orElseGet(() -> Left(Optional.empty()));
}
/**
* If the optional is present, then its value is returned as the
* Left of a disjunction, otherwise the right value is returned.
*
* @param left The optional which could form the left
* @param right The value for the right, if the optional is empty
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toLeft(final Optional<L> left, final R right) {
return left.map(Either::<L, R>Left).orElseGet(() -> Right(right));
}
/**
* A lazy version of {@link #toLeft(Optional, Object)}.
*
* @param left The optional which could form the left
* @param right The value for the right, if the optional is empty
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toLeft(final Optional<L> left, final Supplier<R> right) {
return left.map(Either::<L, R>Left).orElseGet(() -> Right(right.get()));
}
/**
* If the optional is present, them its value is returned as the
* Right of a disjunction, otherwise the left value is returned.
*
* @param left The value for the left, if the optional is empty
* @param right The optional which could form the right
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toRight(final L left, final Optional<R> right) {
return right.map(Either::<L, R>Right).orElseGet(() -> Left(left));
}
/**
* A lazy version of {@link #toRight(Object, Optional)}.
*
* @param left The value for the left, if the optional is empty
* @param right The optional which could form the right
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toRight(final Supplier<L> left, final Optional<R> right) {
return right.map(Either::<L, R>Right).orElseGet(() -> Left(left.get()));
}
/**
* Creates a List from an Optional.
*
* The list will contain zero of one items.
*
* @param optional The optional to construct the list from.
*
* @return the list.
*/
public static <T> List<T> toList(final Optional<T> optional) {
return optional.map(value -> {
final List<T> list = new ArrayList<>();
list.add(value);
return list;
}).orElseGet(() -> new ArrayList<>());
}
/**
* Creates an Immutable List from an Optional.
*
* The list will contain zero of one items.
*
* @param optional The optional to construct the list from.
*
* @return the list.
*/
public static <T> List<T> toImmutableList(final Optional<T> optional) {
return optional.map(Arrays::asList)
.orElse(Collections.emptyList());
}
}
| src/main/java/com/evolvedbinary/j8fu/OptionalUtil.java | /**
* Copyright © 2016, Evolved Binary Ltd. <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.evolvedbinary.j8fu;
import com.evolvedbinary.j8fu.tuple.*;
import java.util.*;
import java.util.function.Supplier;
import static com.evolvedbinary.j8fu.Either.Left;
import static com.evolvedbinary.j8fu.Either.Right;
import static com.evolvedbinary.j8fu.tuple.Tuple.Tuple;
/**
* Functional utility methods that are missing from {@link java.util.Optional}
*
* @author <a href="mailto:[email protected]">Adam Retter</a>
*/
public class OptionalUtil {
/**
* Return the left Optional if present, else the right Optional.
*
* @param left The left of the disjunction
* @param right The right of the disjunction
*
* @return left if present, else right
*
* @param <T> The type of the Optionals
*/
public static <T> Optional<T> or(final Optional<T> left, final Optional<T> right) {
if(left.isPresent()) {
return left;
} else {
return right;
}
}
/**
* A lazy version of {@link #or(Optional, Optional)}.
*
* @param left The left of the disjunction
* @param right A lazily evaluated supplier of Optional for the right of the disjunction,
* only evaluated if the left is empty
*
* @return left if present, else the evaluation of the the right
*
* @param <T> The type of the Optionals
*/
public static <T> Optional<T> or(final Optional<T> left, final Supplier<Optional<T>> right) {
if(left.isPresent()) {
return left;
} else {
return right.get();
}
}
/**
* Constructs a Tuple if both Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2> Optional<Tuple2<T1, T2>> and(final Optional<T1> _1, final Optional<T2> _2) {
return _1.flatMap(t1 -> _2.map(t2 -> Tuple(t1, t2)));
}
/**
* Constructs a Tuple if all three Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3> Optional<Tuple3<T1, T2, T3>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.map(t3 -> Tuple(t1, t2, t3))));
}
/**
* Constructs a Tuple if all four Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
* @param _4 The fourth Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
* @param <T4> The type of the fourth value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3, T4> Optional<Tuple4<T1, T2, T3, T4>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3, final Optional<T4> _4) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.flatMap(t3 -> _4.map(t4 -> Tuple(t1, t2, t3, t4)))));
}
/**
* Constructs a Tuple if all five Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
* @param _4 The fourth Optional
* @param _5 The fifth Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
* @param <T4> The type of the fourth value
* @param <T5> The type of the fifth value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3, T4, T5> Optional<Tuple5<T1, T2, T3, T4, T5>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3, final Optional<T4> _4, final Optional<T5> _5) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.flatMap(t3 -> _4.flatMap(t4 -> _5.map(t5 -> Tuple(t1, t2, t3, t4, t5))))));
}
/**
* Constructs a Tuple if all six Optionals are present.
*
* @param _1 The first Optional
* @param _2 The second Optional
* @param _3 The third Optional
* @param _4 The fourth Optional
* @param _5 The fifth Optional
* @param _6 The sixth Optional
*
* @param <T1> The type of the first value
* @param <T2> The type of the second value
* @param <T3> The type of the third value
* @param <T4> The type of the fourth value
* @param <T5> The type of the fifth value
* @param <T6> The type of the sixth value
*
* @return An Optional Tuple, or an empty Optional.
*/
public static <T1, T2, T3, T4, T5, T6> Optional<Tuple6<T1, T2, T3, T4, T5, T6>> and(final Optional<T1> _1, final Optional<T2> _2, final Optional<T3> _3, final Optional<T4> _4, final Optional<T5> _5, final Optional<T6> _6) {
return _1.flatMap(t1 -> _2.flatMap(t2 -> _3.flatMap(t3 -> _4.flatMap(t4 -> _5.flatMap(t5 -> _6.map(t6 -> Tuple(t1, t2, t3, t4, t5, t6)))))));
}
/**
* If the optional is present, then its value is returned as the
* Left of a disjunction, otherwise the right value is returned.
*
* @param left The optional which could form the left
* @param right The value for the right, if the optional is empty
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toLeft(final Optional<L> left, final R right) {
return left.map(Either::<L, R>Left).orElseGet(() -> Right(right));
}
/**
* A lazy version of {@link #toLeft(Optional, Object)}.
*
* @param left The optional which could form the left
* @param right The value for the right, if the optional is empty
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toLeft(final Optional<L> left, final Supplier<R> right) {
return left.map(Either::<L, R>Left).orElseGet(() -> Right(right.get()));
}
/**
* If the optional is present, them its value is returned as the
* Right of a disjunction, otherwise the left value is returned.
*
* @param left The value for the left, if the optional is empty
* @param right The optional which could form the right
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toRight(final L left, final Optional<R> right) {
return right.map(Either::<L, R>Right).orElseGet(() -> Left(left));
}
/**
* A lazy version of {@link #toRight(Object, Optional)}.
*
* @param left The value for the left, if the optional is empty
* @param right The optional which could form the right
*
* @return The disjunction.
*/
private static <L, R> Either<L,R> toRight(final Supplier<L> left, final Optional<R> right) {
return right.map(Either::<L, R>Right).orElseGet(() -> Left(left.get()));
}
/**
* Creates a List from an Optional.
*
* The list will contain zero of one items.
*
* @param optional The optional to construct the list from.
*
* @return the list.
*/
public static <T> List<T> toList(final Optional<T> optional) {
return optional.map(value -> {
final List<T> list = new ArrayList<>();
list.add(value);
return list;
}).orElseGet(() -> new ArrayList<>());
}
/**
* Creates an Immutable List from an Optional.
*
* The list will contain zero of one items.
*
* @param optional The optional to construct the list from.
*
* @return the list.
*/
public static <T> List<T> toImmutableList(final Optional<T> optional) {
return optional.map(Arrays::asList)
.orElse(Collections.emptyList());
}
}
| Convenience functions for going from Optional to Either
| src/main/java/com/evolvedbinary/j8fu/OptionalUtil.java | Convenience functions for going from Optional to Either | <ide><path>rc/main/java/com/evolvedbinary/j8fu/OptionalUtil.java
<ide>
<ide> /**
<ide> * If the optional is present, then its value is returned as the
<add> * right of a disjunction, otherwise the left of the disjunction is
<add> * returned with the value {@code null}.
<add> *
<add> * This is basically the same as calling {@link #toRight(Object, Optional)}
<add> * with {@code null} as the left argument.
<add> *
<add> * @param optional the optional to create an Either from.
<add> * @return The disjunction.
<add> */
<add> private static <L, R> Either<L,R> toEither(final Optional<R> optional) {
<add> return toRight(null, optional);
<add> }
<add>
<add> /**
<add> * If the optional is present, then its value is returned as the
<add> * right of a disjunction, otherwise the left of the disjunction is
<add> * returned with the value {@code Optional.empty()}.
<add> *
<add> * This is basically the same as calling {@link #toRight(Object, Optional)}
<add> * with {@code Optional.empty()} as the left argument.
<add> *
<add> * @param optional the optional to create an Either from.
<add> * @return The disjunction.
<add> */
<add> private static <L, R> Either<Optional<L>, R> toEitherOpt(final Optional<R> optional) {
<add> return optional.map(Either::<Optional<L>, R>Right).orElseGet(() -> Left(Optional.empty()));
<add> }
<add>
<add> /**
<add> * If the optional is present, then its value is returned as the
<ide> * Left of a disjunction, otherwise the right value is returned.
<ide> *
<ide> * @param left The optional which could form the left |
|
Java | apache-2.0 | 713cc5a0e8816ce9ee947b7496f94a19f082dba3 | 0 | factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx | package de.factoryfx.server.rest.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import de.factoryfx.server.rest.client.RestClient;
import org.junit.Assert;
import org.junit.Test;
public class JettyServerTest {
@Path("/Resource1")
public static class Resource1{
@GET()
public Response get(){
return Response.ok().build();
}
}
@Path("/Resource2")
public static class Resource2{
@GET()
public Response get(){
return Response.ok().build();
}
}
@Test
public void test_multiple_resources_samepath() throws InterruptedException {
List<HttpServerConnectorCreator> connectors= new ArrayList<>();
connectors.add(new HttpServerConnectorCreator("localhost",8005));
JettyServer jettyServer = new JettyServer(connectors, Arrays.asList(new Resource1(), new Resource2()));
jettyServer.start();
// Thread.sleep(1000);
RestClient restClient = new RestClient("localhost",8005,"",false,null,null);
System.out.println(restClient.get("Resource1",String.class));
System.out.println(restClient.get("Resource2",String.class));
jettyServer.stop();
}
@Path("/Resource")
public static class Resource {
final String answer;
public Resource(String answer) {
this.answer = answer;
}
@GET()
public Response get(){
return Response.ok(answer).build();
}
}
@Test
public void test_recreate() throws InterruptedException {
List<HttpServerConnectorCreator> connectors= new ArrayList<>();
connectors.add(new HttpServerConnectorCreator("localhost",8005));
JettyServer jettyServer = new JettyServer(connectors, Arrays.asList(new Resource("Hello")));
jettyServer.start();
// Thread.sleep(1000);
RestClient restClient = new RestClient("localhost",8005,"",false,null,null);
Assert.assertEquals("Hello",restClient.get("Resource",String.class));
jettyServer = jettyServer.recreate(connectors,Arrays.asList(new Resource("World")));
Assert.assertEquals("World",restClient.get("Resource",String.class));
jettyServer.stop();
}
@Test
public void test_addRemoveConnector() throws InterruptedException {
List<HttpServerConnectorCreator> connectors= new ArrayList<>();
connectors.add(new HttpServerConnectorCreator("localhost",8005));
List<HttpServerConnectorCreator> moreConnectors= new ArrayList<>();
moreConnectors.add(new HttpServerConnectorCreator("localhost",8005));
moreConnectors.add(new HttpServerConnectorCreator("localhost",8006));
List<Object> resources = Arrays.asList(new Resource("Hello"));
JettyServer jettyServer = new JettyServer(connectors, resources);
jettyServer.start();
// Thread.sleep(1000);
RestClient restClient8005 = new RestClient("localhost",8005,"",false,null,null);
RestClient restClient8006 = new RestClient("localhost",8006,"",false,null,null);
Assert.assertEquals("Hello",restClient8005.get("Resource",String.class));
try {
restClient8006.get("Resource",String.class);
Assert.fail("Expectected exception");
} catch (Exception expected) {}
jettyServer = jettyServer.recreate(moreConnectors,resources);
Assert.assertEquals("Hello",restClient8005.get("Resource",String.class));
Assert.assertEquals("Hello",restClient8006.get("Resource",String.class));
jettyServer = jettyServer.recreate(connectors,resources);
Assert.assertEquals("Hello",restClient8005.get("Resource",String.class));
try {
restClient8006.get("Resource",String.class);
Assert.fail("Expectected exception");
} catch (Exception expected) {}
jettyServer.stop();
}
} | jettyFactory/src/test/java/de/factoryfx/server/rest/server/JettyServerTest.java | package de.factoryfx.server.rest.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import de.factoryfx.server.rest.client.RestClient;
import org.junit.Assert;
import org.junit.Test;
public class JettyServerTest {
@Path("/Resource1")
public static class Resource1{
@GET()
public Response get(){
return Response.ok().build();
}
}
@Path("/Resource2")
public static class Resource2{
@GET()
public Response get(){
return Response.ok().build();
}
}
@Test
public void test_multiple_resources_samepath() throws InterruptedException {
List<HttpServerConnectorCreator> connectors= new ArrayList<>();
connectors.add(new HttpServerConnectorCreator("localhost",8005));
JettyServer jettyServer = new JettyServer(connectors, Arrays.asList(new Resource1(), new Resource2()));
jettyServer.start();
// Thread.sleep(1000);
RestClient restClient = new RestClient("localhost",8005,"",false,null,null);
System.out.println(restClient.get("Resource1",String.class));
System.out.println(restClient.get("Resource2",String.class));
}
@Path("/Resource")
public static class Resource {
final String answer;
public Resource(String answer) {
this.answer = answer;
}
@GET()
public Response get(){
return Response.ok(answer).build();
}
}
@Test
public void test_recreate() throws InterruptedException {
List<HttpServerConnectorCreator> connectors= new ArrayList<>();
connectors.add(new HttpServerConnectorCreator("localhost",8005));
JettyServer jettyServer = new JettyServer(connectors, Arrays.asList(new Resource("Hello")));
jettyServer.start();
// Thread.sleep(1000);
RestClient restClient = new RestClient("localhost",8005,"",false,null,null);
Assert.assertEquals("Hello",restClient.get("Resource",String.class));
jettyServer.recreate(connectors,Arrays.asList(new Resource("World")));
Assert.assertEquals("World",restClient.get("Resource",String.class));
}
@Test
public void test_addRemoveConnector() throws InterruptedException {
List<HttpServerConnectorCreator> connectors= new ArrayList<>();
connectors.add(new HttpServerConnectorCreator("localhost",8005));
List<HttpServerConnectorCreator> moreConnectors= new ArrayList<>();
moreConnectors.add(new HttpServerConnectorCreator("localhost",8005));
moreConnectors.add(new HttpServerConnectorCreator("localhost",8006));
List<Object> resources = Arrays.asList(new Resource("Hello"));
JettyServer jettyServer = new JettyServer(connectors, resources);
jettyServer.start();
// Thread.sleep(1000);
RestClient restClient8005 = new RestClient("localhost",8005,"",false,null,null);
RestClient restClient8006 = new RestClient("localhost",8006,"",false,null,null);
Assert.assertEquals("Hello",restClient8005.get("Resource",String.class));
try {
restClient8006.get("Resource",String.class);
Assert.fail("Expectected exception");
} catch (Exception expected) {}
jettyServer = jettyServer.recreate(moreConnectors,resources);
Assert.assertEquals("Hello",restClient8005.get("Resource",String.class));
Assert.assertEquals("Hello",restClient8006.get("Resource",String.class));
jettyServer = jettyServer.recreate(connectors,resources);
Assert.assertEquals("Hello",restClient8005.get("Resource",String.class));
try {
restClient8006.get("Resource",String.class);
Assert.fail("Expectected exception");
} catch (Exception expected) {}
}
} | fix test
| jettyFactory/src/test/java/de/factoryfx/server/rest/server/JettyServerTest.java | fix test | <ide><path>ettyFactory/src/test/java/de/factoryfx/server/rest/server/JettyServerTest.java
<ide> RestClient restClient = new RestClient("localhost",8005,"",false,null,null);
<ide> System.out.println(restClient.get("Resource1",String.class));
<ide> System.out.println(restClient.get("Resource2",String.class));
<add> jettyServer.stop();
<ide> }
<ide>
<ide> @Path("/Resource")
<ide>
<ide> RestClient restClient = new RestClient("localhost",8005,"",false,null,null);
<ide> Assert.assertEquals("Hello",restClient.get("Resource",String.class));
<del> jettyServer.recreate(connectors,Arrays.asList(new Resource("World")));
<add> jettyServer = jettyServer.recreate(connectors,Arrays.asList(new Resource("World")));
<ide> Assert.assertEquals("World",restClient.get("Resource",String.class));
<add> jettyServer.stop();
<ide>
<ide> }
<ide>
<ide> restClient8006.get("Resource",String.class);
<ide> Assert.fail("Expectected exception");
<ide> } catch (Exception expected) {}
<add> jettyServer.stop();
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | ee513fb7f0af0ad95aaedf22ecbf10104167af52 | 0 | bitzl/openwayback,MohammedElsayyed/openwayback,JesseWeinstein/openwayback,kris-sigur/openwayback,chasehd/openwayback,kris-sigur/openwayback,kris-sigur/openwayback,efundamentals/openwayback,SpiralsSeminaire/openwayback,bitzl/openwayback,chasehd/openwayback,ukwa/openwayback,kris-sigur/openwayback,nlnwa/openwayback,bitzl/openwayback,sul-dlss/openwayback,emijrp/openwayback,nla/openwayback,zubairkhatri/openwayback,sul-dlss/openwayback,iipc/openwayback,emijrp/openwayback,sul-dlss/openwayback,nla/openwayback,MohammedElsayyed/openwayback,ukwa/openwayback,JesseWeinstein/openwayback,SpiralsSeminaire/openwayback,JesseWeinstein/openwayback,zubairkhatri/openwayback,bitzl/openwayback,nlnwa/openwayback,iipc/openwayback,zubairkhatri/openwayback,nla/openwayback,efundamentals/openwayback,zubairkhatri/openwayback,bitzl/openwayback,kris-sigur/openwayback,nla/openwayback,SpiralsSeminaire/openwayback,nla/openwayback,emijrp/openwayback,SpiralsSeminaire/openwayback,nlnwa/openwayback,iipc/openwayback,JesseWeinstein/openwayback,efundamentals/openwayback,nlnwa/openwayback,efundamentals/openwayback,SpiralsSeminaire/openwayback,ukwa/openwayback,emijrp/openwayback,JesseWeinstein/openwayback,chasehd/openwayback,MohammedElsayyed/openwayback,efundamentals/openwayback,nlnwa/openwayback,emijrp/openwayback | package org.archive.wayback.accesscontrol.robotstxt;
import org.archive.wayback.accesscontrol.ExclusionFilterFactory;
import org.archive.wayback.resourceindex.filters.ExclusionFilter;
public class RedisRobotExclusionFilterFactory implements ExclusionFilterFactory {
private RedisRobotsCache cache;
private String userAgent;
private boolean cacheFails;
public RedisRobotsCache getCache() {
return cache;
}
public void setCache(RedisRobotsCache cache) {
this.cache = cache;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public boolean isCacheFails() {
return cacheFails;
}
public void setCacheFails(boolean cacheFails) {
this.cacheFails = cacheFails;
}
@Override
public ExclusionFilter get() {
return new RedisRobotExclusionFilter(cache, userAgent, cacheFails);
}
@Override
public void shutdown() {
this.cache.shutdown();
}
}
| RedisRobotExclusionFilterFactory.java | package org.archive.wayback.accesscontrol.robotstxt;
import org.archive.wayback.accesscontrol.ExclusionFilterFactory;
import org.archive.wayback.resourceindex.filters.ExclusionFilter;
public class RedisRobotExclusionFilterFactory implements ExclusionFilterFactory {
private RedisRobotsCache cache;
private String userAgent;
private boolean cacheFails;
public RedisRobotsCache getCache() {
return cache;
}
public void setCache(RedisRobotsCache cache) {
this.cache = cache;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
@Override
public ExclusionFilter get() {
return new RedisRobotExclusionFilter(cache, userAgent, cacheFails);
}
@Override
public void shutdown() {
this.cache.shutdown();
}
}
| add missing accessor
| RedisRobotExclusionFilterFactory.java | add missing accessor | <ide><path>edisRobotExclusionFilterFactory.java
<ide> this.userAgent = userAgent;
<ide> }
<ide>
<add> public boolean isCacheFails() {
<add> return cacheFails;
<add> }
<add>
<add> public void setCacheFails(boolean cacheFails) {
<add> this.cacheFails = cacheFails;
<add> }
<add>
<ide> @Override
<ide> public ExclusionFilter get() {
<ide> return new RedisRobotExclusionFilter(cache, userAgent, cacheFails); |
|
Java | apache-2.0 | dc511007b82a1ee05267eeae3cae5a6d8c9f774d | 0 | google/exposure-notifications-private-analytics-ingestion,google/exposure-notifications-private-analytics-ingestion,google/exposure-notifications-private-analytics-ingestion | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.exposurenotification.privateanalytics.ingestion;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SimpleFunction;
import org.apache.beam.sdk.values.PCollection;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Pipeline to export Exposure Notification Private Analytics data shares from Firestore and
* translate into format usable by downstream batch processing by Health Authorities and
* Facilitators.*
*
* <p>To execute this pipeline locally, specify general pipeline configuration:
*
* <pre>{@code
* --project=YOUR_PROJECT_ID
* }</pre>
*
* <p>To change the runner, specify:
*
* <pre>{@code
* --runner=YOUR_SELECTED_RUNNER
* }</pre>
*/
public class IngestionPipeline {
private static final Logger LOG = LoggerFactory.getLogger(IngestionPipeline.class);
/**
* A Temporary SimpleFunction that converts a DataShare into a printable string.
*/
public static class FormatAsTextFn extends SimpleFunction<DataShare, String> {
@Override
public String apply(DataShare input) {
return input.toString();
}
}
/**
* A DoFn that filters documents in particular time window
*/
public static class DateFilterFn extends DoFn<DataShare, DataShare> {
private static final Logger LOG = LoggerFactory.getLogger(DateFilterFn.class);
private final Counter dateFilterIncluded = Metrics
.counter(DateFilterFn.class, "dateFilterIncluded");
private final Counter dateFilterExcluded = Metrics
.counter(DateFilterFn.class, "dateFilterExcluded");
private final ValueProvider<Long> startTime;
private final ValueProvider<Long> duration;
public DateFilterFn(ValueProvider<Long> startTime, ValueProvider<Long> duration) {
this.startTime = startTime;
this.duration = duration;
}
@ProcessElement
public void processElement(ProcessContext c) {
if (c.element().getCreated() == null || c.element().getCreated() == 0) {
// TODO: fork these documents off somewhere so that they are still deleted downstream and we don't accumulate junk
return;
}
if (c.element().getCreated() >= startTime.get() &&
c.element().getCreated() < startTime.get() + duration.get()) {
LOG.debug("Included: " + c.element());
dateFilterIncluded.inc();
c.output(c.element());
} else {
LOG.trace("Excluded: " + c.element());
dateFilterExcluded.inc();
}
}
}
static void runIngestionPipeline(IngestionPipelineOptions options) throws Exception {
Pipeline pipeline = Pipeline.create(options);
pipeline.apply(new FirestoreReader())
.apply("Filter dates",
ParDo.of(new DateFilterFn(options.getStartTime(), options.getDuration())))
// TODO: fork data shares for PHA and Facilitator
// TODO(guray): bail if not enough data shares to ensure min-k anonymity:
// https://beam.apache.org/releases/javadoc/2.0.0/org/apache/beam/sdk/transforms/Count.html#globally--
// TODO(justinowusu): s/TextIO/AvroIO/
// https://beam.apache.org/releases/javadoc/2.4.0/org/apache/beam/sdk/io/AvroIO.html
.apply("SerializeElements", MapElements.via(new FormatAsTextFn()))
.apply("WriteBatches", TextIO.write().to(options.getOutput()));
pipeline.run().waitUntilFinish();
}
public static void main(String[] args) {
PipelineOptionsFactory.register(IngestionPipelineOptions.class);
IngestionPipelineOptions options =
PipelineOptionsFactory.fromArgs(args).withValidation().as(IngestionPipelineOptions.class);
try {
runIngestionPipeline(options);
} catch (UnsupportedOperationException ignore) {
// Known issue that this can throw when generating a template:
// https://issues.apache.org/jira/browse/BEAM-9337
} catch (Exception e) {
LOG.error("Exception thrown during pipeline run.", e);
}
}
}
| src/main/java/com/google/exposurenotification/privateanalytics/ingestion/IngestionPipeline.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.exposurenotification.privateanalytics.ingestion;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SimpleFunction;
import org.apache.beam.sdk.values.PCollection;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Pipeline to export Exposure Notification Private Analytics data shares from Firestore and
* translate into format usable by downstream batch processing by Health Authorities and
* Facilitators.*
*
* <p>To execute this pipeline locally, specify general pipeline configuration:
*
* <pre>{@code
* --project=YOUR_PROJECT_ID
* }</pre>
*
* <p>To change the runner, specify:
*
* <pre>{@code
* --runner=YOUR_SELECTED_RUNNER
* }</pre>
*/
public class IngestionPipeline {
private static final Logger LOG = LoggerFactory.getLogger(IngestionPipeline.class);
/**
* A Temporary SimpleFunction that converts a DataShare into a printable string.
*/
public static class FormatAsTextFn extends SimpleFunction<DataShare, String> {
@Override
public String apply(DataShare input) {
return input.toString();
}
}
/**
* A DoFn that filters documents in particular time window
*/
public static class DateFilterFn extends DoFn<DataShare, DataShare> {
private static final Logger LOG = LoggerFactory.getLogger(DateFilterFn.class);
private final Counter dateFilterIncluded = Metrics
.counter(DateFilterFn.class, "dateFilterIncluded");
private final Counter dateFilterExcluded = Metrics
.counter(DateFilterFn.class, "dateFilterExcluded");
private final ValueProvider<Long> startTime;
private final ValueProvider<Long> duration;
public DateFilterFn(ValueProvider<Long> startTime, ValueProvider<Long> duration) {
this.startTime = startTime;
this.duration = duration;
}
@ProcessElement
public void processElement(ProcessContext c) {
if (c.element().getCreated() == null || c.element().getCreated() == 0) {
// TODO: fork these documents off somewhere so that they are still deleted downstream and we don't accumulate junk
return;
}
if (c.element().getCreated() >= startTime.get() &&
c.element().getCreated() < startTime.get() + duration.get()) {
LOG.debug("Included: " + c.element());
dateFilterIncluded.inc();
c.output(c.element());
} else {
LOG.trace("Excluded: " + c.element());
dateFilterExcluded.inc();
}
}
}
static void runIngestionPipeline(IngestionPipelineOptions options) throws Exception {
Pipeline pipeline = Pipeline.create(options);
pipeline.apply(new FirestoreReader())
.apply("Filter dates",
ParDo.of(new DateFilterFn(options.getStartTime(), options.getDuration())))
// TODO: fork data shares for PHA and Facilitator
// TODO(guray): bail if not enough data shares to ensure min-k anonymity:
// https://beam.apache.org/releases/javadoc/2.0.0/org/apache/beam/sdk/transforms/Count.html#globally--
// TODO(justinowusu): s/TextIO/AvroIO/
// https://beam.apache.org/releases/javadoc/2.4.0/org/apache/beam/sdk/io/AvroIO.html
.apply("SerializeElements", MapElements.via(new FormatAsTextFn()))
.apply("WriteBatches", TextIO.write().to(options.getOutput()));
try {
pipeline.run().waitUntilFinish();
} catch (Exception e) {
LOG.error("Exception thrown during pipeline run: " + e);
}
}
public static void main(String[] args) {
PipelineOptionsFactory.register(IngestionPipelineOptions.class);
IngestionPipelineOptions options =
PipelineOptionsFactory.fromArgs(args).withValidation().as(IngestionPipelineOptions.class);
try {
runIngestionPipeline(options);
} catch (UnsupportedOperationException ignore) {
// Known issue that this can throw when generating a template:
// https://issues.apache.org/jira/browse/BEAM-9337
} catch (Exception e) {
LOG.error("Exception thrown during pipeline run.", e);
}
}
}
| Remove try block that silences errors thrown during pipeline run.
| src/main/java/com/google/exposurenotification/privateanalytics/ingestion/IngestionPipeline.java | Remove try block that silences errors thrown during pipeline run. | <ide><path>rc/main/java/com/google/exposurenotification/privateanalytics/ingestion/IngestionPipeline.java
<ide> // https://beam.apache.org/releases/javadoc/2.4.0/org/apache/beam/sdk/io/AvroIO.html
<ide> .apply("SerializeElements", MapElements.via(new FormatAsTextFn()))
<ide> .apply("WriteBatches", TextIO.write().to(options.getOutput()));
<del>
<del> try {
<del> pipeline.run().waitUntilFinish();
<del> } catch (Exception e) {
<del> LOG.error("Exception thrown during pipeline run: " + e);
<del> }
<add>
<add> pipeline.run().waitUntilFinish();
<ide> }
<ide>
<ide> public static void main(String[] args) { |
|
Java | apache-2.0 | 186456602586f2852dc4c724bb725c8907b5262b | 0 | metaborg/nabl,metaborg/nabl,metaborg/nabl | package mb.statix.benchmarks.actors;
import java.util.concurrent.TimeUnit;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import mb.statix.concurrent.actors.IActor;
import mb.statix.concurrent.actors.IActorRef;
import mb.statix.concurrent.actors.TypeTag;
import mb.statix.concurrent.actors.futures.CompletableFuture;
import mb.statix.concurrent.actors.futures.ICompletable;
import mb.statix.concurrent.actors.futures.ICompletableFuture;
import mb.statix.concurrent.actors.impl.ActorSystem;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@Fork(1)
@Threads(1)
@State(Scope.Thread)
public class ProducerConsumerBenchmark {
private static final ILogger logger = LoggerUtils.logger(ProducerConsumerBenchmark.class);
@Param({ "1", "2", "4", "8" }) public int parallelism;
@Param({ "0", "8", "32", "128" }) public int producers;
@Param({ "1024", "8192", "65536", "262144" }) public int messages;
@Benchmark public Object run() throws Exception, InterruptedException {
return doRun(producers, messages, parallelism);
}
private static Integer doRun(int producers, int messages, int parallelism) throws Exception, InterruptedException {
final ActorSystem actorSystem = new ActorSystem(parallelism);
final ICompletableFuture<Integer> result = new CompletableFuture<>();
final IActor<IConsumer> consumer = actorSystem.add("consumer", TypeTag.of(IConsumer.class),
self -> new Consumer(self, producers * messages, result));
for(int i = 0; i < producers; i++) {
final IActor<IProducer> producer = actorSystem.add("producer-" + i, TypeTag.of(IProducer.class),
self -> new Producer(self, consumer, messages));
actorSystem.async(producer).sentAll();
}
actorSystem.start();
Integer received = result.get();
actorSystem.stop();
return received;
}
private interface IProducer {
void sentAll();
}
private interface IConsumer {
void receive();
}
private static class Producer implements IProducer {
private final IActor<IProducer> self;
private final IActorRef<IConsumer> consumer;
private final int messages;
public Producer(IActor<IProducer> self, IActorRef<IConsumer> consumer, int messages) {
this.self = self;
this.consumer = consumer;
this.messages = messages;
}
@Override public void sentAll() {
final IConsumer consumer = self.async(this.consumer);
for(int i = 0; i < messages; i++) {
consumer.receive();
}
}
}
private static class Consumer implements IConsumer {
private final int expected;
private final ICompletable<Integer> result;
private int received = 0;
public Consumer(IActor<IConsumer> self, int expected, ICompletable<Integer> result) {
this.expected = expected;
this.result = result;
tryFinish();
}
@Override public void receive() {
received++;
tryFinish();
}
private void tryFinish() {
if(received >= expected) {
result.complete(received);
}
}
}
public static void main(String[] args) {
try {
while(true) {
doRun(0, 1024, 1);
}
} catch(Exception ex) {
logger.error("Failed.", ex);
}
}
} | statix.benchmarks/src/main/java/mb/statix/benchmarks/actors/ProducerConsumerBenchmark.java | package mb.statix.benchmarks.actors;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import mb.statix.concurrent.actors.IActor;
import mb.statix.concurrent.actors.IActorRef;
import mb.statix.concurrent.actors.TypeTag;
import mb.statix.concurrent.actors.futures.CompletableFuture;
import mb.statix.concurrent.actors.futures.ICompletable;
import mb.statix.concurrent.actors.futures.ICompletableFuture;
import mb.statix.concurrent.actors.impl.ActorSystem;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@Fork(1)
@Threads(1)
@State(Scope.Thread)
public class ProducerConsumerBenchmark {
@Param({ "1", "2", "4", "8" }) public int parallelism;
@Param({ "0", "8", "32", "128" }) public int producers;
@Param({ "1024", "8192", "65536", "262144" }) public int messages;
@Benchmark public Object run() throws Exception, InterruptedException {
final ActorSystem actorSystem = new ActorSystem(parallelism);
final ICompletableFuture<Integer> result = new CompletableFuture<>();
final IActor<IConsumer> consumer =
actorSystem.add("consumer", TypeTag.of(IConsumer.class), self -> new Consumer(self, result));
for(int i = 0; i < producers; i++) {
final IActor<IProducer> producer =
actorSystem.add("producer-" + i, TypeTag.of(IProducer.class), self -> new Producer(self, consumer));
actorSystem.async(producer).sentAll();
}
actorSystem.start();
Integer received = result.get();
actorSystem.stop();
return received;
}
private interface IProducer {
void sentAll();
}
private interface IConsumer {
void receive();
}
private class Producer implements IProducer {
private final IActor<IProducer> self;
private final IActorRef<IConsumer> consumer;
public Producer(IActor<IProducer> self, IActorRef<IConsumer> consumer) {
this.self = self;
this.consumer = consumer;
}
@Override public void sentAll() {
final IConsumer consumer = self.async(this.consumer);
for(int i = 0; i < messages; i++) {
consumer.receive();
}
}
}
private class Consumer implements IConsumer {
private final ICompletable<Integer> result;
private int received = 0;
public Consumer(IActor<IConsumer> self, ICompletable<Integer> result) {
this.result = result;
tryFinish();
}
@Override public void receive() {
received++;
tryFinish();
}
private void tryFinish() {
if(received >= (producers * messages)) {
result.complete(received);
}
}
}
} | Adapt benchmark to allow executing as application.
| statix.benchmarks/src/main/java/mb/statix/benchmarks/actors/ProducerConsumerBenchmark.java | Adapt benchmark to allow executing as application. | <ide><path>tatix.benchmarks/src/main/java/mb/statix/benchmarks/actors/ProducerConsumerBenchmark.java
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide>
<add>import org.metaborg.util.log.ILogger;
<add>import org.metaborg.util.log.LoggerUtils;
<ide> import org.openjdk.jmh.annotations.Benchmark;
<ide> import org.openjdk.jmh.annotations.BenchmarkMode;
<ide> import org.openjdk.jmh.annotations.Fork;
<ide> @State(Scope.Thread)
<ide> public class ProducerConsumerBenchmark {
<ide>
<add> private static final ILogger logger = LoggerUtils.logger(ProducerConsumerBenchmark.class);
<add>
<ide> @Param({ "1", "2", "4", "8" }) public int parallelism;
<ide> @Param({ "0", "8", "32", "128" }) public int producers;
<ide> @Param({ "1024", "8192", "65536", "262144" }) public int messages;
<ide>
<ide> @Benchmark public Object run() throws Exception, InterruptedException {
<add> return doRun(producers, messages, parallelism);
<add> }
<add>
<add> private static Integer doRun(int producers, int messages, int parallelism) throws Exception, InterruptedException {
<ide> final ActorSystem actorSystem = new ActorSystem(parallelism);
<ide> final ICompletableFuture<Integer> result = new CompletableFuture<>();
<del> final IActor<IConsumer> consumer =
<del> actorSystem.add("consumer", TypeTag.of(IConsumer.class), self -> new Consumer(self, result));
<add> final IActor<IConsumer> consumer = actorSystem.add("consumer", TypeTag.of(IConsumer.class),
<add> self -> new Consumer(self, producers * messages, result));
<ide> for(int i = 0; i < producers; i++) {
<del> final IActor<IProducer> producer =
<del> actorSystem.add("producer-" + i, TypeTag.of(IProducer.class), self -> new Producer(self, consumer));
<add> final IActor<IProducer> producer = actorSystem.add("producer-" + i, TypeTag.of(IProducer.class),
<add> self -> new Producer(self, consumer, messages));
<ide> actorSystem.async(producer).sentAll();
<ide> }
<ide> actorSystem.start();
<ide> void receive();
<ide> }
<ide>
<del> private class Producer implements IProducer {
<add> private static class Producer implements IProducer {
<ide>
<ide> private final IActor<IProducer> self;
<ide> private final IActorRef<IConsumer> consumer;
<add> private final int messages;
<ide>
<del> public Producer(IActor<IProducer> self, IActorRef<IConsumer> consumer) {
<add> public Producer(IActor<IProducer> self, IActorRef<IConsumer> consumer, int messages) {
<ide> this.self = self;
<ide> this.consumer = consumer;
<add> this.messages = messages;
<ide> }
<ide>
<ide> @Override public void sentAll() {
<ide>
<ide> }
<ide>
<del> private class Consumer implements IConsumer {
<add> private static class Consumer implements IConsumer {
<ide>
<add> private final int expected;
<ide> private final ICompletable<Integer> result;
<ide> private int received = 0;
<ide>
<del> public Consumer(IActor<IConsumer> self, ICompletable<Integer> result) {
<add> public Consumer(IActor<IConsumer> self, int expected, ICompletable<Integer> result) {
<add> this.expected = expected;
<ide> this.result = result;
<ide> tryFinish();
<ide> }
<ide> }
<ide>
<ide> private void tryFinish() {
<del> if(received >= (producers * messages)) {
<add> if(received >= expected) {
<ide> result.complete(received);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<add> public static void main(String[] args) {
<add> try {
<add> while(true) {
<add> doRun(0, 1024, 1);
<add> }
<add> } catch(Exception ex) {
<add> logger.error("Failed.", ex);
<add> }
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | error: pathspec 'java/leetcode/binary_tree_inorder_traversal/Solution.java' did not match any file(s) known to git
| b5ca95a1bf66353ccdca07082875762483a170d7 | 1 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | package leetcode.binary_tree_inorder_traversal;
import java.util.ArrayList;
import java.util.Stack;
import common.TreeNode;
public class Solution {
public static class MyNode{
TreeNode node;
boolean isVisit;
public MyNode(TreeNode node){
this.node = node;
}
}
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> ans = new ArrayList<Integer>();
if(root == null) return ans;
Stack<MyNode> stack = new Stack<MyNode>();
stack.push(new MyNode(root));
while(!stack.isEmpty()){
MyNode cur = stack.pop();
if(cur.isVisit){
ans.add(cur.node.val);
}else{
cur.isVisit = true;
if(cur.node.right != null){
stack.push(new MyNode(cur.node.right));
}
stack.push(cur);
if(cur.node.left != null){
stack.push(new MyNode(cur.node.left));
}
}
}
return ans;
}
public static void main(String[] args){
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
t1.left = t2;
t2.left = t3;
t2.right = t4;
for(int x : new Solution().inorderTraversal(t1)){
System.err.print(x + "->");
}
System.err.println("");
}
}
| java/leetcode/binary_tree_inorder_traversal/Solution.java | Add java solution for 94. Binary Tree Inorder Traversal
94. Binary Tree Inorder Traversal: https://leetcode.com/problems/binary-tree-inorder-traversal/ | java/leetcode/binary_tree_inorder_traversal/Solution.java | Add java solution for 94. Binary Tree Inorder Traversal | <ide><path>ava/leetcode/binary_tree_inorder_traversal/Solution.java
<add>package leetcode.binary_tree_inorder_traversal;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Stack;
<add>
<add>import common.TreeNode;
<add>
<add>public class Solution {
<add>
<add> public static class MyNode{
<add> TreeNode node;
<add> boolean isVisit;
<add> public MyNode(TreeNode node){
<add> this.node = node;
<add> }
<add> }
<add>
<add> public ArrayList<Integer> inorderTraversal(TreeNode root) {
<add> ArrayList<Integer> ans = new ArrayList<Integer>();
<add> if(root == null) return ans;
<add> Stack<MyNode> stack = new Stack<MyNode>();
<add> stack.push(new MyNode(root));
<add> while(!stack.isEmpty()){
<add> MyNode cur = stack.pop();
<add> if(cur.isVisit){
<add> ans.add(cur.node.val);
<add> }else{
<add> cur.isVisit = true;
<add> if(cur.node.right != null){
<add> stack.push(new MyNode(cur.node.right));
<add> }
<add> stack.push(cur);
<add> if(cur.node.left != null){
<add> stack.push(new MyNode(cur.node.left));
<add> }
<add> }
<add> }
<add> return ans;
<add> }
<add>
<add> public static void main(String[] args){
<add> TreeNode t1 = new TreeNode(1);
<add> TreeNode t2 = new TreeNode(2);
<add> TreeNode t3 = new TreeNode(3);
<add> TreeNode t4 = new TreeNode(4);
<add> t1.left = t2;
<add> t2.left = t3;
<add> t2.right = t4;
<add> for(int x : new Solution().inorderTraversal(t1)){
<add> System.err.print(x + "->");
<add> }
<add> System.err.println("");
<add> }
<add>} |
|
Java | agpl-3.0 | 99b5e1e9d55cea1ab6c88ad52c6e2d687fdedb5d | 0 | PoweRGbg/AndroidAPS,PoweRGbg/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,jotomo/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,MilosKozak/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS | package info.nightscout.androidaps.plugins.aps.loop;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.ToastUtils;
/**
* Created by mike on 05.08.2016.
*/
public class LoopPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(L.APS);
private static final String CHANNEL_ID = "AndroidAPS-Openloop";
private long lastBgTriggeredRun = 0;
private static LoopPlugin loopPlugin;
@NonNull
public static LoopPlugin getPlugin() {
if (loopPlugin == null) {
loopPlugin = new LoopPlugin();
}
return loopPlugin;
}
private long loopSuspendedTill = 0L; // end of manual loop suspend
private boolean isSuperBolus = false;
private boolean isDisconnected = false;
public class LastRun {
public APSResult request = null;
public APSResult constraintsProcessed = null;
public PumpEnactResult tbrSetByPump = null;
public PumpEnactResult smbSetByPump = null;
public String source = null;
public Date lastAPSRun = null;
public Date lastEnact = null;
public Date lastOpenModeAccept;
}
static public LastRun lastRun = null;
public LoopPlugin() {
super(new PluginDescription()
.mainType(PluginType.LOOP)
.fragmentClass(LoopFragment.class.getName())
.pluginName(R.string.loop)
.shortName(R.string.loop_shortname)
.preferencesId(R.xml.pref_loop)
.description(R.string.description_loop)
);
loopSuspendedTill = SP.getLong("loopSuspendedTill", 0L);
isSuperBolus = SP.getBoolean("isSuperBolus", false);
isDisconnected = SP.getBoolean("isDisconnected", false);
}
@Override
protected void onStart() {
MainApp.bus().register(this);
createNotificationChannel();
super.onStart();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager =
(NotificationManager) MainApp.instance().getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
@SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(channel);
}
}
@Override
protected void onStop() {
super.onStop();
MainApp.bus().unregister(this);
}
@Override
public boolean specialEnableCondition() {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
}
/**
* This method is triggered once autosens calculation has completed, so the LoopPlugin
* has current data to work with. However, autosens calculation can be triggered by multiple
* sources and currently only a new BG should trigger a loop run. Hence we return early if
* the event causing the calculation is not EventNewBg.
* <p>
*/
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
if (!(ev.getCause() instanceof EventNewBG)) {
// Autosens calculation not triggered by a new BG
return;
}
BgReading bgReading = DatabaseHelper.actualBg();
if (bgReading == null) {
// BG outdated
return;
}
if (bgReading.date <= lastBgTriggeredRun) {
// already looped with that value
return;
}
lastBgTriggeredRun = bgReading.date;
invoke("AutosenseCalculation for " + bgReading, true);
}
public long suspendedTo() {
return loopSuspendedTill;
}
@Subscribe
public void onStatusEvent(final EventTempTargetChange ev) {
new Thread(() -> invoke("EventTempTargetChange", true)).start();
}
public void suspendTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = false;
isDisconnected = false;
SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
}
public void superBolusTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = true;
isDisconnected = false;
SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
}
public void disconnectTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = false;
isDisconnected = true;
SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
}
public int minutesToEndOfSuspend() {
if (loopSuspendedTill == 0)
return 0;
long now = System.currentTimeMillis();
long msecDiff = loopSuspendedTill - now;
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return 0;
}
return (int) (msecDiff / 60d / 1000d);
}
public boolean isSuspended() {
if (loopSuspendedTill == 0)
return false;
long now = System.currentTimeMillis();
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return false;
}
return true;
}
public boolean isSuperBolus() {
if (loopSuspendedTill == 0)
return false;
long now = System.currentTimeMillis();
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return false;
}
return isSuperBolus;
}
public boolean isDisconnected() {
if (loopSuspendedTill == 0)
return false;
long now = System.currentTimeMillis();
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return false;
}
return isDisconnected;
}
public synchronized void invoke(String initiator, boolean allowNotification) {
invoke(initiator, allowNotification, false);
}
public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) {
try {
if (L.isEnabled(L.APS))
log.debug("invoke from " + initiator);
Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed();
if (!loopEnabled.value()) {
String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
if (L.isEnabled(L.APS))
log.debug(message);
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(message));
return;
}
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
APSResult result = null;
if (!isEnabled(PluginType.LOOP))
return;
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null || !ProfileFunctions.getInstance().isProfileValid("Loop")) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return;
}
// Check if pump info is loaded
if (pump.getBaseBasalRate() < 0.01d) return;
APSInterface usedAPS = ConfigBuilderPlugin.getPlugin().getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
usedAPS.invoke(initiator, tempBasalFallback);
result = usedAPS.getLastAPSResult();
}
// Check if we have any result
if (result == null) {
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
return;
}
// Prepare for pumps using % basals
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
result.usePercent = true;
}
result.percent = (int) (result.rate / profile.getBasal() * 100);
// check rate for constrais
final APSResult resultAfterConstraints = result.clone();
resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate);
resultAfterConstraints.rate = MainApp.getConstraintChecker().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value();
resultAfterConstraints.percentConstraint = new Constraint<>(resultAfterConstraints.percent);
resultAfterConstraints.percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value();
resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb);
resultAfterConstraints.smb = MainApp.getConstraintChecker().applyBolusConstraints(resultAfterConstraints.smbConstraint).value();
// safety check for multiple SMBs
long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > System.currentTimeMillis()) {
if (L.isEnabled(L.APS))
log.debug("SMB requsted but still in 3 min interval");
resultAfterConstraints.smb = 0;
}
if (lastRun == null) lastRun = new LastRun();
lastRun.request = result;
lastRun.constraintsProcessed = resultAfterConstraints;
lastRun.lastAPSRun = new Date();
lastRun.source = ((PluginBase) usedAPS).getName();
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
NSUpload.uploadDeviceStatus();
if (isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.loopsuspended));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.pumpsuspended));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return;
}
Constraint<Boolean> closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed();
if (closedLoopEnabled.value()) {
if (resultAfterConstraints.isChangeRequested()
&& !ConfigBuilderPlugin.getPlugin().getCommandQueue().bolusInQueue()
&& !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BOLUS)) {
final PumpEnactResult waiting = new PumpEnactResult();
waiting.queued = true;
if (resultAfterConstraints.tempBasalRequested)
lastRun.tbrSetByPump = waiting;
if (resultAfterConstraints.bolusRequested)
lastRun.smbSetByPump = waiting;
RxBus.INSTANCE.send(new EventLoopUpdateGui());
FabricPrivacy.getInstance().logCustom("APSRequest");
applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override
public void run() {
if (result.enacted || result.success) {
lastRun.tbrSetByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun;
applySMBRequest(resultAfterConstraints, new Callback() {
@Override
public void run() {
//Callback is only called if a bolus was acutally requested
if (result.enacted || result.success) {
lastRun.smbSetByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun;
} else {
new Thread(() -> {
SystemClock.sleep(1000);
LoopPlugin.getPlugin().invoke("tempBasalFallback", allowNotification, true);
}).start();
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
}
});
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
}
});
} else {
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
}
} else {
if (resultAfterConstraints.isChangeRequested() && allowNotification) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainApp.instance().getApplicationContext(), CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(MainApp.gs(R.string.openloop_newsuggestion))
.setContentText(resultAfterConstraints.toString())
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_ALARM)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
if (SP.getBoolean("wearcontrol", false)) {
builder.setLocalOnly(true);
}
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(MainApp.instance().getApplicationContext(), MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainApp.instance().getApplicationContext());
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
MainApp.bus().post(new EventNewOpenLoopNotification());
// Send to Wear
ActionStringHandler.handleInitiate("changeRequest");
} else if (allowNotification) {
// dismiss notifications
NotificationManager notificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
ActionStringHandler.handleInitiate("cancelChangeRequest");
}
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
} finally {
if (L.isEnabled(L.APS))
log.debug("invoke end");
}
}
public void acceptChangeRequest() {
Profile profile = ProfileFunctions.getInstance().getProfile();
applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() {
@Override
public void run() {
if (result.enacted) {
lastRun.tbrSetByPump = result;
lastRun.lastEnact = new Date();
lastRun.lastOpenModeAccept = new Date();
NSUpload.uploadDeviceStatus();
ObjectivesPlugin objectivesPlugin = MainApp.getSpecificPlugin(ObjectivesPlugin.class);
if (objectivesPlugin != null) {
ObjectivesPlugin.getPlugin().manualEnacts++;
ObjectivesPlugin.getPlugin().saveProgress();
}
}
MainApp.bus().post(new EventAcceptOpenLoopChange());
}
});
FabricPrivacy.getInstance().logCustom("AcceptTemp");
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
* TODO: update pump drivers to support APS request in %
*/
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
boolean allowPercentage = VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP);
if (!request.tempBasalRequested) {
if (callback != null) {
callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
}
return;
}
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + request.toString());
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
if (request.usePercent && allowPercentage) {
if (request.percent == 100 && request.duration == 0) {
if (activeTemp != null) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: cancelTempBasal()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(false, callback);
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().percent(request.percent).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& request.percent == activeTemp.percentRate) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().percent(request.percent)
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: tempBasalPercent()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(request.percent, request.duration, false, profile, callback);
}
} else {
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: cancelTempBasal()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(false, callback);
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: setTempBasalAbsolute()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
}
public void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
return;
}
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
long lastBolusTime = activeTreatments.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
if (L.isEnabled(L.APS))
log.debug("SMB requested but still in 3 min interval");
if (callback != null) {
callback.result(new PumpEnactResult()
.comment(MainApp.gs(R.string.smb_frequency_exceeded))
.enacted(false).success(false)).run();
}
return;
}
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + request.toString());
// deliver SMB
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: bolus()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, callback);
}
public void disconnectPump(int durationInMinutes, Profile profile) {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
} else {
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
}
if (pump.getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror));
}
}
});
}
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
public void suspendLoop(int durationInMinutes) {
LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
}
| app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java | package info.nightscout.androidaps.plugins.aps.loop;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.ToastUtils;
/**
* Created by mike on 05.08.2016.
*/
public class LoopPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(L.APS);
private static final String CHANNEL_ID = "AndroidAPS-Openloop";
private long lastBgTriggeredRun = 0;
private static LoopPlugin loopPlugin;
@NonNull
public static LoopPlugin getPlugin() {
if (loopPlugin == null) {
loopPlugin = new LoopPlugin();
}
return loopPlugin;
}
private long loopSuspendedTill = 0L; // end of manual loop suspend
private boolean isSuperBolus = false;
private boolean isDisconnected = false;
public class LastRun {
public APSResult request = null;
public APSResult constraintsProcessed = null;
public PumpEnactResult tbrSetByPump = null;
public PumpEnactResult smbSetByPump = null;
public String source = null;
public Date lastAPSRun = null;
public Date lastEnact = null;
public Date lastOpenModeAccept;
}
static public LastRun lastRun = null;
public LoopPlugin() {
super(new PluginDescription()
.mainType(PluginType.LOOP)
.fragmentClass(LoopFragment.class.getName())
.pluginName(R.string.loop)
.shortName(R.string.loop_shortname)
.preferencesId(R.xml.pref_loop)
.description(R.string.description_loop)
);
loopSuspendedTill = SP.getLong("loopSuspendedTill", 0L);
isSuperBolus = SP.getBoolean("isSuperBolus", false);
isDisconnected = SP.getBoolean("isDisconnected", false);
}
@Override
protected void onStart() {
MainApp.bus().register(this);
createNotificationChannel();
super.onStart();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager =
(NotificationManager) MainApp.instance().getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
@SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(channel);
}
}
@Override
protected void onStop() {
super.onStop();
MainApp.bus().unregister(this);
}
@Override
public boolean specialEnableCondition() {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
}
/**
* This method is triggered once autosens calculation has completed, so the LoopPlugin
* has current data to work with. However, autosens calculation can be triggered by multiple
* sources and currently only a new BG should trigger a loop run. Hence we return early if
* the event causing the calculation is not EventNewBg.
* <p>
*/
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
if (!(ev.getCause() instanceof EventNewBG)) {
// Autosens calculation not triggered by a new BG
return;
}
BgReading bgReading = DatabaseHelper.actualBg();
if (bgReading == null) {
// BG outdated
return;
}
if (bgReading.date <= lastBgTriggeredRun) {
// already looped with that value
return;
}
lastBgTriggeredRun = bgReading.date;
invoke("AutosenseCalculation for " + bgReading, true);
}
public long suspendedTo() {
return loopSuspendedTill;
}
@Subscribe
public void onStatusEvent(final EventTempTargetChange ev) {
new Thread(() -> invoke("EventTempTargetChange", true)).start();
}
public void suspendTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = false;
isDisconnected = false;
SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
}
public void superBolusTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = true;
isDisconnected = false;
SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
}
public void disconnectTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = false;
isDisconnected = true;
SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
}
public int minutesToEndOfSuspend() {
if (loopSuspendedTill == 0)
return 0;
long now = System.currentTimeMillis();
long msecDiff = loopSuspendedTill - now;
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return 0;
}
return (int) (msecDiff / 60d / 1000d);
}
public boolean isSuspended() {
if (loopSuspendedTill == 0)
return false;
long now = System.currentTimeMillis();
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return false;
}
return true;
}
public boolean isSuperBolus() {
if (loopSuspendedTill == 0)
return false;
long now = System.currentTimeMillis();
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return false;
}
return isSuperBolus;
}
public boolean isDisconnected() {
if (loopSuspendedTill == 0)
return false;
long now = System.currentTimeMillis();
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return false;
}
return isDisconnected;
}
public synchronized void invoke(String initiator, boolean allowNotification) {
invoke(initiator, allowNotification, false);
}
public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) {
try {
if (L.isEnabled(L.APS))
log.debug("invoke from " + initiator);
Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed();
if (!loopEnabled.value()) {
String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
if (L.isEnabled(L.APS))
log.debug(message);
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(message));
return;
}
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
APSResult result = null;
if (!isEnabled(PluginType.LOOP))
return;
Profile profile = ProfileFunctions.getInstance().getProfile();
if (!ProfileFunctions.getInstance().isProfileValid("Loop")) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return;
}
// Check if pump info is loaded
if (pump.getBaseBasalRate() < 0.01d) return;
APSInterface usedAPS = ConfigBuilderPlugin.getPlugin().getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
usedAPS.invoke(initiator, tempBasalFallback);
result = usedAPS.getLastAPSResult();
}
// Check if we have any result
if (result == null) {
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
return;
}
// Prepare for pumps using % basals
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
result.usePercent = true;
}
result.percent = (int) (result.rate / profile.getBasal() * 100);
// check rate for constrais
final APSResult resultAfterConstraints = result.clone();
resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate);
resultAfterConstraints.rate = MainApp.getConstraintChecker().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value();
resultAfterConstraints.percentConstraint = new Constraint<>(resultAfterConstraints.percent);
resultAfterConstraints.percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value();
resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb);
resultAfterConstraints.smb = MainApp.getConstraintChecker().applyBolusConstraints(resultAfterConstraints.smbConstraint).value();
// safety check for multiple SMBs
long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > System.currentTimeMillis()) {
if (L.isEnabled(L.APS))
log.debug("SMB requsted but still in 3 min interval");
resultAfterConstraints.smb = 0;
}
if (lastRun == null) lastRun = new LastRun();
lastRun.request = result;
lastRun.constraintsProcessed = resultAfterConstraints;
lastRun.lastAPSRun = new Date();
lastRun.source = ((PluginBase) usedAPS).getName();
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
NSUpload.uploadDeviceStatus();
if (isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.loopsuspended));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.pumpsuspended));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return;
}
Constraint<Boolean> closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed();
if (closedLoopEnabled.value()) {
if (resultAfterConstraints.isChangeRequested()
&& !ConfigBuilderPlugin.getPlugin().getCommandQueue().bolusInQueue()
&& !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BOLUS)) {
final PumpEnactResult waiting = new PumpEnactResult();
waiting.queued = true;
if (resultAfterConstraints.tempBasalRequested)
lastRun.tbrSetByPump = waiting;
if (resultAfterConstraints.bolusRequested)
lastRun.smbSetByPump = waiting;
RxBus.INSTANCE.send(new EventLoopUpdateGui());
FabricPrivacy.getInstance().logCustom("APSRequest");
applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override
public void run() {
if (result.enacted || result.success) {
lastRun.tbrSetByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun;
applySMBRequest(resultAfterConstraints, new Callback() {
@Override
public void run() {
//Callback is only called if a bolus was acutally requested
if (result.enacted || result.success) {
lastRun.smbSetByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun;
} else {
new Thread(() -> {
SystemClock.sleep(1000);
LoopPlugin.getPlugin().invoke("tempBasalFallback", allowNotification, true);
}).start();
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
}
});
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
}
});
} else {
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
}
} else {
if (resultAfterConstraints.isChangeRequested() && allowNotification) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainApp.instance().getApplicationContext(), CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(MainApp.gs(R.string.openloop_newsuggestion))
.setContentText(resultAfterConstraints.toString())
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_ALARM)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
if (SP.getBoolean("wearcontrol", false)) {
builder.setLocalOnly(true);
}
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(MainApp.instance().getApplicationContext(), MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainApp.instance().getApplicationContext());
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
MainApp.bus().post(new EventNewOpenLoopNotification());
// Send to Wear
ActionStringHandler.handleInitiate("changeRequest");
} else if (allowNotification) {
// dismiss notifications
NotificationManager notificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
ActionStringHandler.handleInitiate("cancelChangeRequest");
}
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
} finally {
if (L.isEnabled(L.APS))
log.debug("invoke end");
}
}
public void acceptChangeRequest() {
Profile profile = ProfileFunctions.getInstance().getProfile();
applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() {
@Override
public void run() {
if (result.enacted) {
lastRun.tbrSetByPump = result;
lastRun.lastEnact = new Date();
lastRun.lastOpenModeAccept = new Date();
NSUpload.uploadDeviceStatus();
ObjectivesPlugin objectivesPlugin = MainApp.getSpecificPlugin(ObjectivesPlugin.class);
if (objectivesPlugin != null) {
ObjectivesPlugin.getPlugin().manualEnacts++;
ObjectivesPlugin.getPlugin().saveProgress();
}
}
MainApp.bus().post(new EventAcceptOpenLoopChange());
}
});
FabricPrivacy.getInstance().logCustom("AcceptTemp");
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
* TODO: update pump drivers to support APS request in %
*/
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
boolean allowPercentage = VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP);
if (!request.tempBasalRequested) {
if (callback != null) {
callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
}
return;
}
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + request.toString());
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
if (request.usePercent && allowPercentage) {
if (request.percent == 100 && request.duration == 0) {
if (activeTemp != null) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: cancelTempBasal()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(false, callback);
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().percent(request.percent).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& request.percent == activeTemp.percentRate) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().percent(request.percent)
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: tempBasalPercent()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(request.percent, request.duration, false, profile, callback);
}
} else {
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: cancelTempBasal()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(false, callback);
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: setTempBasalAbsolute()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
}
public void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
return;
}
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
long lastBolusTime = activeTreatments.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
if (L.isEnabled(L.APS))
log.debug("SMB requested but still in 3 min interval");
if (callback != null) {
callback.result(new PumpEnactResult()
.comment(MainApp.gs(R.string.smb_frequency_exceeded))
.enacted(false).success(false)).run();
}
return;
}
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + request.toString());
// deliver SMB
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: bolus()");
ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, callback);
}
public void disconnectPump(int durationInMinutes, Profile profile) {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
} else {
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
}
if (pump.getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror));
}
}
});
}
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
public void suspendLoop(int durationInMinutes) {
LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
}
| fix NPE
| app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java | fix NPE | <ide><path>pp/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java
<ide>
<ide> Profile profile = ProfileFunctions.getInstance().getProfile();
<ide>
<del> if (!ProfileFunctions.getInstance().isProfileValid("Loop")) {
<add> if (profile == null || !ProfileFunctions.getInstance().isProfileValid("Loop")) {
<ide> if (L.isEnabled(L.APS))
<ide> log.debug(MainApp.gs(R.string.noprofileselected));
<ide> RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected))); |
|
Java | bsd-3-clause | 0eb2c145e9357583f749977895fa057c372b773d | 0 | krzyk/rultor,dalifreire/rultor,pecko/rultor,joansmith/rultor,pecko/rultor,maurezen/rultor,linlihai/rultor,maurezen/rultor,joansmith/rultor,krzyk/rultor,krzyk/rultor,pecko/rultor,pecko/rultor,joansmith/rultor,linlihai/rultor,dalifreire/rultor,linlihai/rultor,joansmith/rultor,maurezen/rultor,krzyk/rultor,joansmith/rultor,dalifreire/rultor,maurezen/rultor,krzyk/rultor,pecko/rultor,dalifreire/rultor,linlihai/rultor,dalifreire/rultor,linlihai/rultor,maurezen/rultor | /**
* Copyright (c) 2009-2014, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.agents;
import co.stateful.Sttc;
import com.jcabi.aspects.Immutable;
import com.jcabi.github.Github;
import com.jcabi.manifests.Manifests;
import com.jcabi.s3.Region;
import com.jcabi.s3.retry.ReRegion;
import com.rultor.agents.daemons.ArchivesDaemon;
import com.rultor.agents.daemons.EndsDaemon;
import com.rultor.agents.daemons.KillsDaemon;
import com.rultor.agents.daemons.StartsDaemon;
import com.rultor.agents.github.Question;
import com.rultor.agents.github.Reports;
import com.rultor.agents.github.StartsTalks;
import com.rultor.agents.github.Understands;
import com.rultor.agents.github.qtn.QnAlone;
import com.rultor.agents.github.qtn.QnAskedBy;
import com.rultor.agents.github.qtn.QnDeploy;
import com.rultor.agents.github.qtn.QnHello;
import com.rultor.agents.github.qtn.QnIfContains;
import com.rultor.agents.github.qtn.QnMerge;
import com.rultor.agents.github.qtn.QnParametrized;
import com.rultor.agents.github.qtn.QnReferredTo;
import com.rultor.agents.github.qtn.QnRelease;
import com.rultor.agents.github.qtn.QnStatus;
import com.rultor.agents.github.qtn.QnVersion;
import com.rultor.agents.req.EndsRequest;
import com.rultor.agents.req.StartsRequest;
import com.rultor.agents.shells.RegistersShell;
import com.rultor.agents.shells.RemovesShell;
import com.rultor.spi.Agent;
import com.rultor.spi.Profile;
import com.rultor.spi.SuperAgent;
import com.rultor.spi.Talk;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
/**
* Agents.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 1.0
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle ClassFanOutComplexityCheck (500 lines)
*/
@Immutable
@ToString
@EqualsAndHashCode(of = { "github", "sttc" })
@SuppressWarnings("PMD.ExcessiveImports")
public final class Agents {
/**
* Github client.
*/
private final transient Github github;
/**
* Sttc client.
*/
private final transient Sttc sttc;
/**
* Ctor.
* @param ghub Github client
* @param stc Sttc client
*/
public Agents(final Github ghub, final Sttc stc) {
this.github = ghub;
this.sttc = stc;
}
/**
* Create super agents, starters.
* @return List of them
* @throws IOException If fails
*/
public Collection<SuperAgent> starters() throws IOException {
return Arrays.<SuperAgent>asList(
new StartsTalks(this.github, this.sttc.counters())
);
}
/**
* Create super agents, closers.
* @return List of them
*/
public Collection<SuperAgent> closers() {
return Arrays.<SuperAgent>asList(
new DeactivatesTalks()
);
}
/**
* Create them for a talk.
* @param talk Talk itself
* @param profile Profile
* @return List of them
* @throws IOException If fails
*/
public Collection<Agent> agents(final Talk talk, final Profile profile)
throws IOException {
final Collection<Agent> agents = new LinkedList<Agent>();
final Question list = new Question.FirstOf(
Arrays.<Question>asList(
new QnIfContains(
"merge",
new QnAskedBy(
profile,
"/p/merge/commanders/item/text()",
new QnAlone(talk, this.sttc.locks(), new QnMerge())
)
),
new QnIfContains(
"deploy",
new QnAskedBy(
profile,
"/p/deploy/commanders/item/text()",
new QnAlone(talk, this.sttc.locks(), new QnDeploy())
)
),
new QnIfContains(
"release",
new QnAskedBy(
profile,
"/p/release/commanders/item/text()",
new QnAlone(talk, this.sttc.locks(), new QnRelease())
)
),
new QnIfContains("status", new QnStatus(talk)),
new QnIfContains("version", new QnVersion()),
new QnIfContains("hello", new QnHello())
)
);
agents.addAll(
Arrays.asList(
new Understands(
this.github,
new QnReferredTo(
this.github.users().self().login(),
new QnParametrized(list)
)
),
new StartsRequest(profile),
new RegistersShell(
// @checkstyle MagicNumber (1 line)
"b1.rultor.com", 22,
"rultor",
IOUtils.toString(
this.getClass().getResourceAsStream("rultor.key"),
CharEncoding.UTF_8
)
),
new StartsDaemon(profile),
new KillsDaemon(),
new EndsDaemon(),
new EndsRequest(),
new Reports(this.github),
new RemovesShell(),
new ArchivesDaemon(
new ReRegion(
new Region.Simple(
Manifests.read("Rultor-S3Key"),
Manifests.read("Rultor-S3Secret")
)
).bucket(Manifests.read("Rultor-S3Bucket"))
)
)
);
return agents;
}
}
| src/main/java/com/rultor/agents/Agents.java | /**
* Copyright (c) 2009-2014, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.agents;
import co.stateful.Sttc;
import com.jcabi.aspects.Immutable;
import com.jcabi.github.Github;
import com.jcabi.manifests.Manifests;
import com.jcabi.s3.Region;
import com.jcabi.s3.retry.ReRegion;
import com.rultor.agents.daemons.ArchivesDaemon;
import com.rultor.agents.daemons.EndsDaemon;
import com.rultor.agents.daemons.KillsDaemon;
import com.rultor.agents.daemons.StartsDaemon;
import com.rultor.agents.github.Question;
import com.rultor.agents.github.Reports;
import com.rultor.agents.github.StartsTalks;
import com.rultor.agents.github.Understands;
import com.rultor.agents.github.qtn.QnAlone;
import com.rultor.agents.github.qtn.QnAskedBy;
import com.rultor.agents.github.qtn.QnDeploy;
import com.rultor.agents.github.qtn.QnHello;
import com.rultor.agents.github.qtn.QnIfContains;
import com.rultor.agents.github.qtn.QnMerge;
import com.rultor.agents.github.qtn.QnParametrized;
import com.rultor.agents.github.qtn.QnReferredTo;
import com.rultor.agents.github.qtn.QnRelease;
import com.rultor.agents.github.qtn.QnStatus;
import com.rultor.agents.github.qtn.QnVersion;
import com.rultor.agents.req.EndsRequest;
import com.rultor.agents.req.StartsRequest;
import com.rultor.agents.shells.RegistersShell;
import com.rultor.agents.shells.RemovesShell;
import com.rultor.spi.Agent;
import com.rultor.spi.Profile;
import com.rultor.spi.SuperAgent;
import com.rultor.spi.Talk;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
/**
* Agents.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 1.0
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle ClassFanOutComplexityCheck (500 lines)
*/
@Immutable
@ToString
@EqualsAndHashCode(of = { "github", "sttc" })
@SuppressWarnings("PMD.ExcessiveImports")
public final class Agents {
/**
* Github client.
*/
private final transient Github github;
/**
* Sttc client.
*/
private final transient Sttc sttc;
/**
* Ctor.
* @param ghub Github client
* @param stc Sttc client
*/
public Agents(final Github ghub, final Sttc stc) {
this.github = ghub;
this.sttc = stc;
}
/**
* Create super agents, starters.
* @return List of them
* @throws IOException If fails
*/
public Collection<SuperAgent> starters() throws IOException {
return Arrays.<SuperAgent>asList(
new StartsTalks(this.github, this.sttc.counters())
);
}
/**
* Create super agents, closers.
* @return List of them
*/
public Collection<SuperAgent> closers() {
return Arrays.<SuperAgent>asList(
new DeactivatesTalks()
);
}
/**
* Create them for a talk.
* @param talk Talk itself
* @param profile Profile
* @return List of them
* @throws IOException If fails
*/
public Collection<Agent> agents(final Talk talk, final Profile profile)
throws IOException {
final Collection<Agent> agents = new LinkedList<Agent>();
agents.addAll(
Arrays.asList(
new Understands(
this.github,
new QnReferredTo(
this.github.users().self().login(),
new QnParametrized(
new Question.FirstOf(
Arrays.<Question>asList(
new QnIfContains(
"merge",
new QnAskedBy(
profile,
"/p/merge/commanders/item/text()",
new QnAlone(
talk,
this.sttc.locks(),
new QnMerge()
)
)
),
new QnIfContains(
"deploy",
new QnAskedBy(
profile,
"/p/deploy/commanders/item/text()",
new QnAlone(
talk,
this.sttc.locks(),
new QnDeploy()
)
)
),
new QnIfContains(
"release",
new QnAskedBy(
profile,
"/p/release/commanders/item/text()",
new QnAlone(
talk,
this.sttc.locks(),
new QnRelease()
)
)
),
new QnIfContains(
"status", new QnStatus(talk)
),
new QnIfContains(
"version", new QnVersion()
),
new QnIfContains("hello", new QnHello())
)
)
)
)
),
new StartsRequest(profile),
new RegistersShell(
// @checkstyle MagicNumber (1 line)
"b1.rultor.com", 22,
"rultor",
IOUtils.toString(
this.getClass().getResourceAsStream("rultor.key"),
CharEncoding.UTF_8
)
),
new StartsDaemon(profile),
new KillsDaemon(),
new EndsDaemon(),
new EndsRequest(),
new Reports(this.github),
new RemovesShell(),
new ArchivesDaemon(
new ReRegion(
new Region.Simple(
Manifests.read("Rultor-S3Key"),
Manifests.read("Rultor-S3Secret")
)
).bucket(Manifests.read("Rultor-S3Bucket"))
)
)
);
return agents;
}
}
| #509 optimized
| src/main/java/com/rultor/agents/Agents.java | #509 optimized | <ide><path>rc/main/java/com/rultor/agents/Agents.java
<ide> public Collection<Agent> agents(final Talk talk, final Profile profile)
<ide> throws IOException {
<ide> final Collection<Agent> agents = new LinkedList<Agent>();
<add> final Question list = new Question.FirstOf(
<add> Arrays.<Question>asList(
<add> new QnIfContains(
<add> "merge",
<add> new QnAskedBy(
<add> profile,
<add> "/p/merge/commanders/item/text()",
<add> new QnAlone(talk, this.sttc.locks(), new QnMerge())
<add> )
<add> ),
<add> new QnIfContains(
<add> "deploy",
<add> new QnAskedBy(
<add> profile,
<add> "/p/deploy/commanders/item/text()",
<add> new QnAlone(talk, this.sttc.locks(), new QnDeploy())
<add> )
<add> ),
<add> new QnIfContains(
<add> "release",
<add> new QnAskedBy(
<add> profile,
<add> "/p/release/commanders/item/text()",
<add> new QnAlone(talk, this.sttc.locks(), new QnRelease())
<add> )
<add> ),
<add> new QnIfContains("status", new QnStatus(talk)),
<add> new QnIfContains("version", new QnVersion()),
<add> new QnIfContains("hello", new QnHello())
<add> )
<add> );
<ide> agents.addAll(
<ide> Arrays.asList(
<ide> new Understands(
<ide> this.github,
<ide> new QnReferredTo(
<ide> this.github.users().self().login(),
<del> new QnParametrized(
<del> new Question.FirstOf(
<del> Arrays.<Question>asList(
<del> new QnIfContains(
<del> "merge",
<del> new QnAskedBy(
<del> profile,
<del> "/p/merge/commanders/item/text()",
<del> new QnAlone(
<del> talk,
<del> this.sttc.locks(),
<del> new QnMerge()
<del> )
<del> )
<del> ),
<del> new QnIfContains(
<del> "deploy",
<del> new QnAskedBy(
<del> profile,
<del> "/p/deploy/commanders/item/text()",
<del> new QnAlone(
<del> talk,
<del> this.sttc.locks(),
<del> new QnDeploy()
<del> )
<del> )
<del> ),
<del> new QnIfContains(
<del> "release",
<del> new QnAskedBy(
<del> profile,
<del> "/p/release/commanders/item/text()",
<del> new QnAlone(
<del> talk,
<del> this.sttc.locks(),
<del> new QnRelease()
<del> )
<del> )
<del> ),
<del> new QnIfContains(
<del> "status", new QnStatus(talk)
<del> ),
<del> new QnIfContains(
<del> "version", new QnVersion()
<del> ),
<del> new QnIfContains("hello", new QnHello())
<del> )
<del> )
<del> )
<add> new QnParametrized(list)
<ide> )
<ide> ),
<ide> new StartsRequest(profile), |
|
Java | mit | error: pathspec 'src/test/java/br/com/pjbank/sdk/api/PJBankConfigTest.java' did not match any file(s) known to git
| 2ae79a687550646a57f4cc75bb7f4dd4d9937993 | 1 | pjbank/pjbank-java-sdk,viniciusls/pjbank-java-sdk | package br.com.pjbank.sdk.api;
/**
* @author Vinícius Silva <[email protected]>
* @version 1.0
* @since 1.0
*/
public class PJBankConfigTest {
/**
* Credencial para boletos (Conta de Recebimento)
*/
public final static String credencialBoletosContaRecebimento = "d3418668b85cea70aa28965eafaf927cd34d004c";
/**
* Chave para boletos (Conta de Recebimento)
*/
public final static String chaveBoletosContaRecebimento = "46e79d6d5161336afa7b98f01236efacf5d0f24b";
/**
* Credencial para cartão de crédito (Conta de Recebimento)
*/
public final static String credencialCartaoCreditoContaRecebimento = "1264e7bea04bb1c24b07ace759f64a1bd65c8560";
/**
* Chave para cartão de crédito (Conta de Recebimento)
*/
public final static String chaveCartaoCreditoContaRecebimento = "ef947cf5867488f744b82744dd3a8fc4852e529f";
/**
* Credencial para conta digital
*/
public final static String credencialContaDigital = "eb2af021c5e2448c343965a7a80d7d090eb64164";
/**
* Chave para conta digital
*/
public final static String chaveContaDigital = "a834d47e283dd12f50a1b3a771603ae9dfd5a32c";
}
| src/test/java/br/com/pjbank/sdk/api/PJBankConfigTest.java | Adição de arquivo para manter as configurações de testes, como credenciamento e outras
| src/test/java/br/com/pjbank/sdk/api/PJBankConfigTest.java | Adição de arquivo para manter as configurações de testes, como credenciamento e outras | <ide><path>rc/test/java/br/com/pjbank/sdk/api/PJBankConfigTest.java
<add>package br.com.pjbank.sdk.api;
<add>
<add>/**
<add> * @author Vinícius Silva <[email protected]>
<add> * @version 1.0
<add> * @since 1.0
<add> */
<add>public class PJBankConfigTest {
<add> /**
<add> * Credencial para boletos (Conta de Recebimento)
<add> */
<add> public final static String credencialBoletosContaRecebimento = "d3418668b85cea70aa28965eafaf927cd34d004c";
<add>
<add> /**
<add> * Chave para boletos (Conta de Recebimento)
<add> */
<add> public final static String chaveBoletosContaRecebimento = "46e79d6d5161336afa7b98f01236efacf5d0f24b";
<add>
<add> /**
<add> * Credencial para cartão de crédito (Conta de Recebimento)
<add> */
<add> public final static String credencialCartaoCreditoContaRecebimento = "1264e7bea04bb1c24b07ace759f64a1bd65c8560";
<add>
<add> /**
<add> * Chave para cartão de crédito (Conta de Recebimento)
<add> */
<add> public final static String chaveCartaoCreditoContaRecebimento = "ef947cf5867488f744b82744dd3a8fc4852e529f";
<add>
<add> /**
<add> * Credencial para conta digital
<add> */
<add> public final static String credencialContaDigital = "eb2af021c5e2448c343965a7a80d7d090eb64164";
<add>
<add> /**
<add> * Chave para conta digital
<add> */
<add> public final static String chaveContaDigital = "a834d47e283dd12f50a1b3a771603ae9dfd5a32c";
<add>} |
|
JavaScript | mit | e407a228ba28eb44824b1e641bec5bc8e53911c7 | 0 | ericvaladas/formwood | import React from 'react';
import MinLengthValidator from '../forms/validators/min-length';
import EmailValidator from '../forms/validators/email';
import RequiredValidator from '../forms/validators/required';
import ExactValidator from '../forms/validators/exact';
import Field from '../forms/components/field';
import Form from '../forms/components/form'
import TermsConditions from './fields/terms-conditions';
import ReactDom from 'react-dom';
const TextField = Field(React.createClass({
handleChange(e) {
this.props.handleChange(e)
.then(this.props.validate);
},
render() {
let classNames = "form-row";
if (!this.props.valid) {
classNames += " invalid";
}
return (
<div className={classNames}>
<label>Name</label>
<input type="text" name={this.props.name} id={this.props.id} onChange={this.handleChange} />
<span className="message">{this.props.message}</span>
</div>
);
}
}));
const EmailField = Field(React.createClass({
render() {
return (
<div>
<label>Email</label>
<input type="text" name={this.props.name} id={this.props.id} onChange={this.props.handleChange} />
<span className="message">{this.props.message}</span>
</div>
);
}
}));
const PasswordField = Field(React.createClass({
render() {
return (
<div>
<label>Password</label>
<input type="text" name={this.props.name} id={this.props.id} onChange={this.props.handleChange} />
<span className="message">{this.props.message}</span>
</div>
);
}
}));
const Checkbox = Field(React.createClass({
render() {
return (
<div className="checkbox">
<input type="checkbox" id="legal--i-agree" name="legal" value="i-agree" required="" data-audit-required="true" data-audit-error-message="Agree or Not" data-audit-multiple="legal" onChange={this.props.handleChange}/>
<label className="label" htmlFor="legal--i-agree">I agree</label>
</div>
);
}
}));
export default React.createClass({
getInitialState() {
return {
invalidFieldCount: 0
};
},
handleSubmit(e, values) {
if (this.form.state.valid) {
console.log(values);
}
else {
console.log('form is invalid');
}
this.setState({invalidFieldCount: Object.keys(this.form.invalidFields).length});
},
render() {
return (
<Form onSubmit={this.handleSubmit} ref={(form) => { this.form = form; }}>
{this.state.invalidFieldCount} invalid fields
<TextField name="something" id="something" validators={[MinLengthValidator(3)]}/>
<PasswordField name="password" id="password" validators={[RequiredValidator()]}/>
<PasswordField name="password2" id="password2" validators={[RequiredValidator(), ExactValidator(() => { return this.form.fields.password.state.value })]} />
<EmailField name="email" id="email" validators={[EmailValidator()]}/>
<TermsConditions name="terms" id="terms" validators={[RequiredValidator()]}/>
<button type="submit">submit</button>
</Form>
);
}
});
| src/js/components/test-form.js | import React from 'react';
import MinLengthValidator from '../forms/validators/min-length';
import EmailValidator from '../forms/validators/email';
import {Field, ErrorMessage} from '../forms/components/field';
import Form from '../forms/components/form'
export default React.createClass({
render() {
return (
<Form action="/" method="get">
<Field validators={[MinLengthValidator(3)]}>
<label>Name</label>
<input type="text" name="name" id="name"/>
<ErrorMessage/>
</Field>
<Field validators={[EmailValidator()]}>
<label>Email</label>
<input type="text" name="email" id="email"/>
<ErrorMessage/>
</Field>
<button type="submit">Submit</button>
</Form>
);
}
});
| Update example form | src/js/components/test-form.js | Update example form | <ide><path>rc/js/components/test-form.js
<ide> import React from 'react';
<ide> import MinLengthValidator from '../forms/validators/min-length';
<ide> import EmailValidator from '../forms/validators/email';
<del>import {Field, ErrorMessage} from '../forms/components/field';
<add>import RequiredValidator from '../forms/validators/required';
<add>import ExactValidator from '../forms/validators/exact';
<add>import Field from '../forms/components/field';
<ide> import Form from '../forms/components/form'
<add>import TermsConditions from './fields/terms-conditions';
<add>import ReactDom from 'react-dom';
<add>
<add>
<add>const TextField = Field(React.createClass({
<add> handleChange(e) {
<add> this.props.handleChange(e)
<add> .then(this.props.validate);
<add> },
<add>
<add> render() {
<add> let classNames = "form-row";
<add> if (!this.props.valid) {
<add> classNames += " invalid";
<add> }
<add> return (
<add> <div className={classNames}>
<add> <label>Name</label>
<add> <input type="text" name={this.props.name} id={this.props.id} onChange={this.handleChange} />
<add> <span className="message">{this.props.message}</span>
<add> </div>
<add> );
<add> }
<add>
<add>}));
<add>
<add>const EmailField = Field(React.createClass({
<add> render() {
<add> return (
<add> <div>
<add> <label>Email</label>
<add> <input type="text" name={this.props.name} id={this.props.id} onChange={this.props.handleChange} />
<add> <span className="message">{this.props.message}</span>
<add> </div>
<add> );
<add> }
<add>}));
<add>
<add>const PasswordField = Field(React.createClass({
<add> render() {
<add> return (
<add> <div>
<add> <label>Password</label>
<add> <input type="text" name={this.props.name} id={this.props.id} onChange={this.props.handleChange} />
<add> <span className="message">{this.props.message}</span>
<add> </div>
<add> );
<add> }
<add>}));
<add>
<add>
<add>const Checkbox = Field(React.createClass({
<add> render() {
<add> return (
<add> <div className="checkbox">
<add> <input type="checkbox" id="legal--i-agree" name="legal" value="i-agree" required="" data-audit-required="true" data-audit-error-message="Agree or Not" data-audit-multiple="legal" onChange={this.props.handleChange}/>
<add> <label className="label" htmlFor="legal--i-agree">I agree</label>
<add> </div>
<add> );
<add> }
<add>}));
<ide>
<ide>
<ide> export default React.createClass({
<ide>
<add> getInitialState() {
<add> return {
<add> invalidFieldCount: 0
<add> };
<add> },
<add>
<add> handleSubmit(e, values) {
<add> if (this.form.state.valid) {
<add> console.log(values);
<add> }
<add> else {
<add> console.log('form is invalid');
<add> }
<add>
<add> this.setState({invalidFieldCount: Object.keys(this.form.invalidFields).length});
<add> },
<add>
<ide> render() {
<ide> return (
<del> <Form action="/" method="get">
<del> <Field validators={[MinLengthValidator(3)]}>
<del> <label>Name</label>
<del> <input type="text" name="name" id="name"/>
<del> <ErrorMessage/>
<del> </Field>
<add> <Form onSubmit={this.handleSubmit} ref={(form) => { this.form = form; }}>
<ide>
<del> <Field validators={[EmailValidator()]}>
<del> <label>Email</label>
<del> <input type="text" name="email" id="email"/>
<del> <ErrorMessage/>
<del> </Field>
<add> {this.state.invalidFieldCount} invalid fields
<ide>
<del> <button type="submit">Submit</button>
<add> <TextField name="something" id="something" validators={[MinLengthValidator(3)]}/>
<add>
<add> <PasswordField name="password" id="password" validators={[RequiredValidator()]}/>
<add> <PasswordField name="password2" id="password2" validators={[RequiredValidator(), ExactValidator(() => { return this.form.fields.password.state.value })]} />
<add>
<add> <EmailField name="email" id="email" validators={[EmailValidator()]}/>
<add> <TermsConditions name="terms" id="terms" validators={[RequiredValidator()]}/>
<add>
<add> <button type="submit">submit</button>
<add>
<ide> </Form>
<add>
<ide> );
<ide> }
<ide> }); |
|
Java | bsd-3-clause | f1dbec4c3724c768a83920b57c9c937fdfb2d40b | 0 | NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk | package test.xml.data;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.DiscusFish;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.FishTank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.FreshwaterFishTank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.SaltwaterFishTank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Substrate;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Tank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.TankAccessory;
import gov.nih.nci.iso21090.Ii;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import java.util.Collection;
import java.util.Iterator;
import test.xml.mapping.SDKXMLDataTestBase;
public class ImplicitParentWithAssociationXMLDataTest extends SDKXMLDataTestBase
{
public static String getTestCaseName()
{
return "Implicit Parent With Association XML Data Test Case";
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch1() throws Exception
{
Tank searchObject = new Tank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Tank",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Tank result = (Tank)i.next();
toXML(result);
validateClassElements(result);
assertTrue(validateXMLData(result, searchObject.getClass()));
Tank result2 = (Tank)fromXML(result);
assertNotNull(result2);
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch2() throws Exception
{
FishTank searchObject = new FishTank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.FishTank",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
FishTank result = (FishTank)i.next();
toXML(result);
validateClassElements(result);
validateAttribute(result,"id",result.getId());
validateAttribute(result,"numGallons",result.getNumGallons());
validateAttribute(result,"shape",result.getShape());
assertTrue(validateXMLData(result, searchObject.getClass()));
FishTank result2 = (FishTank)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getNumGallons());
assertNotNull(result2.getShape());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch3() throws Exception
{
FreshwaterFishTank searchObject = new FreshwaterFishTank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.FreshwaterFishTank",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
FreshwaterFishTank result = (FreshwaterFishTank)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "filterModel", "value", result.getFilterModel().getValue());
validateIso90210Element(result, "numGallons", "value", result.getNumGallons().getValue());
validateIso90210Element(result, "shape", "value", result.getShape().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
FreshwaterFishTank result2 = (FreshwaterFishTank)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getFilterModel());
assertNotNull(result2.getNumGallons());
assertNotNull(result2.getShape());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch4() throws Exception
{
SaltwaterFishTank searchObject = new SaltwaterFishTank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.SaltwaterFishTank",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
SaltwaterFishTank result = (SaltwaterFishTank)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "proteinSkimmerModel", "value", result.getProteinSkimmerModel().getValue());
validateIso90210Element(result, "numGallons", "value", result.getNumGallons().getValue());
validateIso90210Element(result, "shape", "value", result.getShape().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
SaltwaterFishTank result2 = (SaltwaterFishTank)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getProteinSkimmerModel());
assertNotNull(result2.getNumGallons());
assertNotNull(result2.getShape());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch5() throws Exception
{
Fish searchObject = new Fish();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Fish result = (Fish)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "genera", "value", result.getGenera().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
Fish result2 = (Fish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch6() throws Exception
{
AngelFish searchObject = new AngelFish();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
AngelFish result = (AngelFish)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "genera", "value", result.getGenera().getValue());
validateIso90210Element(result, "finSize", "value", result.getFinSize().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
AngelFish result2 = (AngelFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch7() throws Exception
{
DiscusFish searchObject = new DiscusFish();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.DiscusFish",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
DiscusFish result = (DiscusFish)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "genera", "value", result.getGenera().getValue());
validateIso90210Element(result, "primaryColor", "value", result.getPrimaryColor().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
DiscusFish result2 = (DiscusFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
assertNotNull(result2.getPrimaryColor());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch8() throws Exception
{
TankAccessory searchObject = new TankAccessory();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.TankAccessory",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
TankAccessory result = (TankAccessory)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "name", "value", result.getName().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
TankAccessory result2 = (TankAccessory)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch9() throws Exception
{
Substrate searchObject = new Substrate();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Substrate",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Substrate result = (Substrate)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "name", "value", result.getName().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
Substrate result2 = (Substrate)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
}
}
/**
* Uses Nested Search Criteria for inheritance as association in search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestAssociationNestedSearch1() throws Exception
{
AngelFish searchObject = new AngelFish();
Ii ii = new Ii();
ii.setExtension("3");
searchObject.setId(ii);
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish",searchObject );
assertNotNull(results);
assertEquals(1,results.size());
Fish result = (Fish)results.iterator().next();
toXML(result);
Fish result2 = (Fish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
assertEquals("3", result2.getId().getExtension());
}
public void xtestAssociationNestedSearchHQL1() throws Exception {
HQLCriteria hqlCriteria = new HQLCriteria(
"from gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish where id='3'");
Collection results = search(hqlCriteria,
"gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish");
assertNotNull(results);
assertEquals(1,results.size());
Fish result = (Fish)results.iterator().next();
toXML(result);
Fish result2 = (Fish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
assertEquals("3", result2.getId().getExtension());
}
/**
* Uses Nested Search Criteria for inheritance as association in search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestAssociationNestedSearch2() throws Exception
{
Fish searchObject = new Fish();
Ii ii = new Ii();
ii.setExtension("3");
searchObject.setId(ii);
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish",searchObject );
assertNotNull(results);
assertEquals(1,results.size());
AngelFish result = (AngelFish)results.iterator().next();
toXML(result);
AngelFish result2 = (AngelFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertEquals("3", result2.getId().getExtension());
}
public void xtestAssociationNestedSearchHQL2() throws Exception {
HQLCriteria hqlCriteria = new HQLCriteria(
"from gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish where id='3'");
Collection results = search(hqlCriteria,
"gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish");
assertNotNull(results);
assertEquals(1,results.size());
AngelFish result = (AngelFish)results.iterator().next();
toXML(result);
AngelFish result2 = (AngelFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertEquals("3", result2.getId().getExtension());
}
/**
* Uses Nested Search Criteria for inheritance as association in search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestAssociationNestedSearch10() throws Exception
{
SaltwaterFishTank searchObject = new SaltwaterFishTank();
Ii ii = new Ii();
ii.setExtension("3");
searchObject.setId(ii);
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Substrate",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
Substrate result = (Substrate)results.iterator().next();
toXML(result);
Substrate result2 = (Substrate)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
assertEquals("1", result2.getId().getExtension());
}
}
| sdk-toolkit/iso-example-project/junit/src/test/xml/data/ImplicitParentWithAssociationXMLDataTest.java | package test.xml.data;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.DiscusFish;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.FishTank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.FreshwaterFishTank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.SaltwaterFishTank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Substrate;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Tank;
import gov.nih.nci.cacoresdk.domain.inheritance.implicit.TankAccessory;
import gov.nih.nci.iso21090.Ii;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import java.util.Collection;
import java.util.Iterator;
import test.xml.mapping.SDKXMLDataTestBase;
public class ImplicitParentWithAssociationXMLDataTest extends SDKXMLDataTestBase
{
public static String getTestCaseName()
{
return "Implicit Parent With Association XML Data Test Case";
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void testEntireObjectNestedSearch1() throws Exception
{
Tank searchObject = new Tank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Tank",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Tank result = (Tank)i.next();
toXML(result);
validateClassElements(result);
assertTrue(validateXMLData(result, searchObject.getClass()));
Tank result2 = (Tank)fromXML(result);
assertNotNull(result2);
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void testEntireObjectNestedSearch2() throws Exception
{
FishTank searchObject = new FishTank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.FishTank",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
FishTank result = (FishTank)i.next();
toXML(result);
validateClassElements(result);
validateAttribute(result,"id",result.getId());
validateAttribute(result,"numGallons",result.getNumGallons());
validateAttribute(result,"shape",result.getShape());
assertTrue(validateXMLData(result, searchObject.getClass()));
FishTank result2 = (FishTank)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getNumGallons());
assertNotNull(result2.getShape());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch3() throws Exception
{
FreshwaterFishTank searchObject = new FreshwaterFishTank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.FreshwaterFishTank",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
FreshwaterFishTank result = (FreshwaterFishTank)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "filterModel", "value", result.getFilterModel().getValue());
validateIso90210Element(result, "numGallons", "value", result.getNumGallons().getValue());
validateIso90210Element(result, "shape", "value", result.getShape().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
FreshwaterFishTank result2 = (FreshwaterFishTank)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getFilterModel());
assertNotNull(result2.getNumGallons());
assertNotNull(result2.getShape());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch4() throws Exception
{
SaltwaterFishTank searchObject = new SaltwaterFishTank();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.SaltwaterFishTank",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
SaltwaterFishTank result = (SaltwaterFishTank)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "proteinSkimmerModel", "value", result.getProteinSkimmerModel().getValue());
validateIso90210Element(result, "numGallons", "value", result.getNumGallons().getValue());
validateIso90210Element(result, "shape", "value", result.getShape().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
SaltwaterFishTank result2 = (SaltwaterFishTank)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getProteinSkimmerModel());
assertNotNull(result2.getNumGallons());
assertNotNull(result2.getShape());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch5() throws Exception
{
Fish searchObject = new Fish();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Fish result = (Fish)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "genera", "value", result.getGenera().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
Fish result2 = (Fish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch6() throws Exception
{
AngelFish searchObject = new AngelFish();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
AngelFish result = (AngelFish)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "genera", "value", result.getGenera().getValue());
validateIso90210Element(result, "finSize", "value", result.getFinSize().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
AngelFish result2 = (AngelFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch7() throws Exception
{
DiscusFish searchObject = new DiscusFish();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.DiscusFish",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
DiscusFish result = (DiscusFish)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "genera", "value", result.getGenera().getValue());
validateIso90210Element(result, "primaryColor", "value", result.getPrimaryColor().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
DiscusFish result2 = (DiscusFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
assertNotNull(result2.getPrimaryColor());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch8() throws Exception
{
TankAccessory searchObject = new TankAccessory();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.TankAccessory",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
TankAccessory result = (TankAccessory)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "name", "value", result.getName().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
TankAccessory result2 = (TankAccessory)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestEntireObjectNestedSearch9() throws Exception
{
Substrate searchObject = new Substrate();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Substrate",searchObject );
assertNotNull(results);
assertEquals(4,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Substrate result = (Substrate)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "name", "value", result.getName().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
Substrate result2 = (Substrate)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
}
}
/**
* Uses Nested Search Criteria for inheritance as association in search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestAssociationNestedSearch1() throws Exception
{
AngelFish searchObject = new AngelFish();
Ii ii = new Ii();
ii.setExtension("3");
searchObject.setId(ii);
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish",searchObject );
assertNotNull(results);
assertEquals(1,results.size());
Fish result = (Fish)results.iterator().next();
toXML(result);
Fish result2 = (Fish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
assertEquals("3", result2.getId().getExtension());
}
public void xtestAssociationNestedSearchHQL1() throws Exception {
HQLCriteria hqlCriteria = new HQLCriteria(
"from gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish where id='3'");
Collection results = search(hqlCriteria,
"gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish");
assertNotNull(results);
assertEquals(1,results.size());
Fish result = (Fish)results.iterator().next();
toXML(result);
Fish result2 = (Fish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getGenera());
assertEquals("3", result2.getId().getExtension());
}
/**
* Uses Nested Search Criteria for inheritance as association in search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestAssociationNestedSearch2() throws Exception
{
Fish searchObject = new Fish();
Ii ii = new Ii();
ii.setExtension("3");
searchObject.setId(ii);
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish",searchObject );
assertNotNull(results);
assertEquals(1,results.size());
AngelFish result = (AngelFish)results.iterator().next();
toXML(result);
AngelFish result2 = (AngelFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertEquals("3", result2.getId().getExtension());
}
public void xtestAssociationNestedSearchHQL2() throws Exception {
HQLCriteria hqlCriteria = new HQLCriteria(
"from gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish where id='3'");
Collection results = search(hqlCriteria,
"gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish");
assertNotNull(results);
assertEquals(1,results.size());
AngelFish result = (AngelFish)results.iterator().next();
toXML(result);
AngelFish result2 = (AngelFish)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertEquals("3", result2.getId().getExtension());
}
/**
* Uses Nested Search Criteria for inheritance as association in search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void xtestAssociationNestedSearch10() throws Exception
{
SaltwaterFishTank searchObject = new SaltwaterFishTank();
Ii ii = new Ii();
ii.setExtension("3");
searchObject.setId(ii);
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Substrate",searchObject );
assertNotNull(results);
assertEquals(2,results.size());
Substrate result = (Substrate)results.iterator().next();
toXML(result);
Substrate result2 = (Substrate)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
assertEquals("1", result2.getId().getExtension());
}
}
| updated Assertions
SVN-Revision: 894
| sdk-toolkit/iso-example-project/junit/src/test/xml/data/ImplicitParentWithAssociationXMLDataTest.java | updated Assertions | <ide><path>dk-toolkit/iso-example-project/junit/src/test/xml/data/ImplicitParentWithAssociationXMLDataTest.java
<ide> *
<ide> * @throws Exception
<ide> */
<del> public void testEntireObjectNestedSearch1() throws Exception
<add> public void xtestEntireObjectNestedSearch1() throws Exception
<ide> {
<ide> Tank searchObject = new Tank();
<ide> Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Tank",searchObject );
<ide> *
<ide> * @throws Exception
<ide> */
<del> public void testEntireObjectNestedSearch2() throws Exception
<add> public void xtestEntireObjectNestedSearch2() throws Exception
<ide> {
<ide> FishTank searchObject = new FishTank();
<ide> Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.FishTank",searchObject ); |
|
Java | apache-2.0 | 22c39d75976df53561733c5cf306a9c622fdacbe | 0 | caot/intellij-community,slisson/intellij-community,kdwink/intellij-community,asedunov/intellij-community,samthor/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,consulo/consulo,apixandru/intellij-community,ernestp/consulo,youdonghai/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,robovm/robovm-studio,signed/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,kool79/intellij-community,dslomov/intellij-community,da1z/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,semonte/intellij-community,kdwink/intellij-community,amith01994/intellij-community,retomerz/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,clumsy/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,allotria/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,allotria/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,signed/intellij-community,blademainer/intellij-community,ryano144/intellij-community,diorcety/intellij-community,xfournet/intellij-community,kool79/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ryano144/intellij-community,vladmm/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,petteyg/intellij-community,izonder/intellij-community,da1z/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,hurricup/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,fnouama/intellij-community,fitermay/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,supersven/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,signed/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,fitermay/intellij-community,asedunov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,orekyuu/intellij-community,semonte/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,kool79/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,fitermay/intellij-community,diorcety/intellij-community,diorcety/intellij-community,blademainer/intellij-community,apixandru/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,jagguli/intellij-community,kdwink/intellij-community,caot/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,petteyg/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,petteyg/intellij-community,jagguli/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,izonder/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,ernestp/consulo,clumsy/intellij-community,allotria/intellij-community,asedunov/intellij-community,supersven/intellij-community,xfournet/intellij-community,blademainer/intellij-community,samthor/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,da1z/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,ernestp/consulo,holmes/intellij-community,tmpgit/intellij-community,slisson/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,slisson/intellij-community,holmes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,retomerz/intellij-community,ernestp/consulo,fnouama/intellij-community,allotria/intellij-community,blademainer/intellij-community,allotria/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,holmes/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,consulo/consulo,petteyg/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,caot/intellij-community,semonte/intellij-community,caot/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,consulo/consulo,mglukhikh/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,amith01994/intellij-community,ryano144/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,adedayo/intellij-community,clumsy/intellij-community,fnouama/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,holmes/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,holmes/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,supersven/intellij-community,petteyg/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,caot/intellij-community,supersven/intellij-community,consulo/consulo,salguarnieri/intellij-community,clumsy/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,holmes/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,ernestp/consulo,pwoodworth/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,izonder/intellij-community,apixandru/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,samthor/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,retomerz/intellij-community,holmes/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,supersven/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,dslomov/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,slisson/intellij-community,akosyakov/intellij-community,caot/intellij-community,caot/intellij-community,amith01994/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,amith01994/intellij-community,slisson/intellij-community,jagguli/intellij-community,kool79/intellij-community,dslomov/intellij-community,allotria/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,clumsy/intellij-community,da1z/intellij-community,holmes/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,signed/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,amith01994/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,allotria/intellij-community,apixandru/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,blademainer/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,da1z/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,samthor/intellij-community,consulo/consulo,akosyakov/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,signed/intellij-community,dslomov/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,diorcety/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,asedunov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,FHannes/intellij-community,caot/intellij-community,dslomov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,signed/intellij-community,jagguli/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,izonder/intellij-community,ibinti/intellij-community,xfournet/intellij-community,blademainer/intellij-community,kdwink/intellij-community,retomerz/intellij-community,slisson/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,semonte/intellij-community,blademainer/intellij-community,supersven/intellij-community,signed/intellij-community,izonder/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,caot/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,semonte/intellij-community,semonte/intellij-community,dslomov/intellij-community,ryano144/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,izonder/intellij-community,petteyg/intellij-community,holmes/intellij-community,diorcety/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,izonder/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,orekyuu/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.integrate;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsKey;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.update.UpdatedFilesReverseSide;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnVcs;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.wc.SVNPropertyData;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class GatheringChangelistBuilder implements ChangelistBuilder {
private final Set<VirtualFile> myCheckSet;
private final List<Change> myChanges;
private final UpdatedFilesReverseSide myFiles;
private final VirtualFile myMergeRoot;
private final SvnVcs myVcs;
public GatheringChangelistBuilder(final Project project, final UpdatedFilesReverseSide files, final VirtualFile mergeRoot) {
myVcs = SvnVcs.getInstance(project);
myFiles = files;
myMergeRoot = mergeRoot;
myChanges = new ArrayList<Change>();
myCheckSet = new HashSet<VirtualFile>();
}
public void processChange(final Change change, VcsKey vcsKey) {
addChange(change);
}
public void processChangeInList(final Change change, @Nullable final ChangeList changeList, VcsKey vcsKey) {
addChange(change);
}
public void processChangeInList(final Change change, final String changeListName, VcsKey vcsKey) {
addChange(change);
}
private void addChange(final Change change) {
final FilePath path = ChangesUtil.getFilePath(change);
final VirtualFile vf = path.getVirtualFile();
if ((mergeinfoChanged(path.getIOFile()) || ((vf != null) && myFiles.containsFile(vf))) && (! myCheckSet.contains(vf))) {
myCheckSet.add(vf);
myChanges.add(change);
}
}
private boolean mergeinfoChanged(final File file) {
final SVNWCClient client = myVcs.createWCClient();
try {
final SVNPropertyData current = client.doGetProperty(file, "svn:mergeinfo", SVNRevision.UNDEFINED, SVNRevision.WORKING);
final SVNPropertyData base = client.doGetProperty(file, "svn:mergeinfo", SVNRevision.UNDEFINED, SVNRevision.BASE);
if (current != null) {
if (base == null) {
return true;
} else {
final SVNPropertyValue currentValue = current.getValue();
final SVNPropertyValue baseValue = base.getValue();
return ! Comparing.equal(currentValue, baseValue);
}
}
}
catch (SVNException e) {
//
}
return false;
}
public void processUnversionedFile(final VirtualFile file) {
}
public void processLocallyDeletedFile(final FilePath file) {
}
public void processLocallyDeletedFile(LocallyDeletedChange locallyDeletedChange) {
}
public void processModifiedWithoutCheckout(final VirtualFile file) {
}
public void processIgnoredFile(final VirtualFile file) {
}
public void processLockedFolder(final VirtualFile file) {
}
public void processLogicallyLockedFolder(VirtualFile file, LogicalLock logicalLock) {
}
public void processSwitchedFile(final VirtualFile file, final String branch, final boolean recursive) {
}
public void processRootSwitch(VirtualFile file, String branch) {
}
public boolean reportChangesOutsideProject() {
return true;
}
@Override
public void reportAdditionalInfo(final String text) {
}
@Override
public void reportAdditionalInfo(Factory<JComponent> infoComponent) {
}
public void reportWarningMessage(final String message) {
// todo maybe, use further
}
public List<Change> getChanges() {
return myChanges;
}
}
| plugins/svn4ideaOld/src/org/jetbrains/idea/svn/integrate/GatheringChangelistBuilder.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.integrate;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsKey;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.update.UpdatedFilesReverseSide;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnVcs;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.wc.SVNPropertyData;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class GatheringChangelistBuilder implements ChangelistBuilder {
private final Set<VirtualFile> myCheckSet;
private final List<Change> myChanges;
private final UpdatedFilesReverseSide myFiles;
private final VirtualFile myMergeRoot;
private final SvnVcs myVcs;
public GatheringChangelistBuilder(final Project project, final UpdatedFilesReverseSide files, final VirtualFile mergeRoot) {
myVcs = SvnVcs.getInstance(project);
myFiles = files;
myMergeRoot = mergeRoot;
myChanges = new ArrayList<Change>();
myCheckSet = new HashSet<VirtualFile>();
}
public void processChange(final Change change, VcsKey vcsKey) {
addChange(change);
}
public void processChangeInList(final Change change, @Nullable final ChangeList changeList, VcsKey vcsKey) {
addChange(change);
}
public void processChangeInList(final Change change, final String changeListName, VcsKey vcsKey) {
addChange(change);
}
private void addChange(final Change change) {
final FilePath path = ChangesUtil.getFilePath(change);
final VirtualFile vf = path.getVirtualFile();
if ((mergeinfoChanged(path.getIOFile()) || ((vf != null) && myFiles.containsFile(vf))) && (! myCheckSet.contains(vf))) {
myCheckSet.add(vf);
myChanges.add(change);
}
}
private boolean mergeinfoChanged(final File file) {
final SVNWCClient client = myVcs.createWCClient();
try {
final SVNPropertyData current = client.doGetProperty(file, "svn:mergeinfo", SVNRevision.UNDEFINED, SVNRevision.WORKING);
final SVNPropertyData base = client.doGetProperty(file, "svn:mergeinfo", SVNRevision.UNDEFINED, SVNRevision.BASE);
if (current != null) {
if (base == null) {
return true;
} else {
final SVNPropertyValue currentValue = current.getValue();
final SVNPropertyValue baseValue = base.getValue();
return ! Comparing.equal(currentValue, baseValue);
}
}
}
catch (SVNException e) {
//
}
return false;
}
public void processUnversionedFile(final VirtualFile file) {
}
public void processLocallyDeletedFile(final FilePath file) {
}
public void processLocallyDeletedFile(LocallyDeletedChange locallyDeletedChange) {
}
public void processModifiedWithoutCheckout(final VirtualFile file) {
}
public void processIgnoredFile(final VirtualFile file) {
}
public void processLockedFolder(final VirtualFile file) {
}
public void processLogicallyLockedFolder(VirtualFile file, LogicalLock logicalLock) {
}
public void processSwitchedFile(final VirtualFile file, final String branch, final boolean recursive) {
}
public void processRootSwitch(VirtualFile file, String branch) {
}
public boolean reportChangesOutsideProject() {
return true;
}
@Override
public void reportAdditionalInfo(final String text) {
}
@Override
public void reportAdditionalInfo(Factory<JComponent> infoComponent) {
}
public void reportWarningMessage(final String message) {
// todo maybe, use further
}
public List<Change> getChanges() {
return myChanges;
}
}
| fix imports
| plugins/svn4ideaOld/src/org/jetbrains/idea/svn/integrate/GatheringChangelistBuilder.java | fix imports | <ide><path>lugins/svn4ideaOld/src/org/jetbrains/idea/svn/integrate/GatheringChangelistBuilder.java
<ide>
<ide> import com.intellij.openapi.project.Project;
<ide> import com.intellij.openapi.util.Comparing;
<add>import com.intellij.openapi.util.Factory;
<ide> import com.intellij.openapi.vcs.FilePath;
<ide> import com.intellij.openapi.vcs.VcsKey;
<ide> import com.intellij.openapi.vcs.changes.*;
<ide> import org.tmatesoft.svn.core.wc.SVNRevision;
<ide> import org.tmatesoft.svn.core.wc.SVNWCClient;
<ide>
<add>import javax.swing.*;
<ide> import java.io.File;
<ide> import java.util.ArrayList;
<ide> import java.util.HashSet;
<ide> }
<ide>
<ide> public void processLocallyDeletedFile(LocallyDeletedChange locallyDeletedChange) {
<del>
<add>
<ide> }
<ide>
<ide> public void processModifiedWithoutCheckout(final VirtualFile file) { |
|
Java | agpl-3.0 | e0a858d8ce30c04975cc1ee6d58e7caf0559e6fc | 0 | dgray16/libreplan,poum/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,skylow95/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,Marine-22/libre,Marine-22/libre,dgray16/libreplan,dgray16/libreplan,dgray16/libreplan,Marine-22/libre,LibrePlan/libreplan,LibrePlan/libreplan,skylow95/libreplan,poum/libreplan,PaulLuchyn/libreplan,poum/libreplan,skylow95/libreplan,poum/libreplan,Marine-22/libre,Marine-22/libre,dgray16/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,skylow95/libreplan,poum/libreplan,Marine-22/libre,skylow95/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,poum/libreplan | /*
* This file is part of NavalPlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2011 Igalia, S.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.web.orders;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.navalplanner.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE;
import static org.navalplanner.web.WebappGlobalNames.WEBAPP_SPRING_CONFIG_FILE;
import static org.navalplanner.web.WebappGlobalNames.WEBAPP_SPRING_SECURITY_CONFIG_FILE;
import static org.navalplanner.web.test.WebappGlobalNames.WEBAPP_SPRING_CONFIG_TEST_FILE;
import static org.navalplanner.web.test.WebappGlobalNames.WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE;
import java.math.BigDecimal;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.navalplanner.business.IDataBootstrap;
import org.navalplanner.business.advance.bootstrap.PredefinedAdvancedTypes;
import org.navalplanner.business.advance.entities.AdvanceType;
import org.navalplanner.business.advance.entities.DirectAdvanceAssignment;
import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException;
import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException;
import org.navalplanner.business.labels.entities.Label;
import org.navalplanner.business.labels.entities.LabelType;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.orders.entities.OrderLine;
import org.navalplanner.business.orders.entities.OrderLineGroup;
import org.navalplanner.business.qualityforms.entities.QualityForm;
import org.navalplanner.business.requirements.entities.CriterionRequirement;
import org.navalplanner.business.requirements.entities.DirectCriterionRequirement;
import org.navalplanner.business.requirements.entities.IndirectCriterionRequirement;
import org.navalplanner.business.resources.daos.ICriterionDAO;
import org.navalplanner.business.resources.entities.Criterion;
import org.navalplanner.business.scenarios.bootstrap.PredefinedScenarios;
import org.navalplanner.business.scenarios.entities.OrderVersion;
import org.navalplanner.business.scenarios.entities.Scenario;
import org.navalplanner.business.templates.entities.OrderElementTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* Tests for {@link OrderElementTreeModel}
*
* @author Manuel Rego Casasnovas <[email protected]>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
WEBAPP_SPRING_CONFIG_FILE, WEBAPP_SPRING_CONFIG_TEST_FILE,
WEBAPP_SPRING_SECURITY_CONFIG_FILE,
WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE })
@Transactional
public class OrderElementTreeModelTest {
private static final BigDecimal HUNDRED = new BigDecimal(100);
@Resource
private IDataBootstrap defaultAdvanceTypesBootstrapListener;
@Resource
private IDataBootstrap scenariosBootstrap;
@Resource
private IDataBootstrap criterionsBootstrap;
@Resource
private IDataBootstrap configurationBootstrap;
@Autowired
private ICriterionDAO criterionDAO;
private Order order;
private OrderElementTreeModel model;
private Criterion criterion, criterion2, criterion3;
private AdvanceType advanceType, advanceType2, advanceType3;
private MaterialAssignment materialAssignment;
private Label label;
private QualityForm qualityForm;
private OrderElementTemplate template;
@Before
public void loadRequiredaData() {
// Load data
configurationBootstrap.loadRequiredData();
defaultAdvanceTypesBootstrapListener.loadRequiredData();
scenariosBootstrap.loadRequiredData();
criterionsBootstrap.loadRequiredData();
givenOrder();
givenModel();
}
private void givenOrder() {
order = Order.create();
order.setName("order");
Scenario scenario = PredefinedScenarios.MASTER.getScenario();
OrderVersion result = OrderVersion.createInitialVersion(scenario);
order.setVersionForScenario(scenario, result);
order.useSchedulingDataFor(scenario);
}
private void givenModel() {
model = new OrderElementTreeModel(order);
}
private void addCriterionRequirement(OrderElement orderElement) {
criterion = criterionDAO.findByNameAndType("medicalLeave", "LEAVE")
.get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addAnotherCriterionRequirement(OrderElement orderElement) {
criterion2 = criterionDAO.findByNameAndType(
"hiredResourceWorkingRelationship", "WORK_RELATIONSHIP").get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion2);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addAnotherDifferentCriterionRequirement(
OrderElement orderElement) {
criterion3 = criterionDAO.findByNameAndType("paternityLeave", "LEAVE")
.get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion3);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addDirectAdvanceAssignment(OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create(true, HUNDRED);
advanceType = PredefinedAdvancedTypes.PERCENTAGE.getType();
directAdvanceAssignment.setAdvanceType(advanceType);
orderElement.addAdvanceAssignment(directAdvanceAssignment);
}
private void addAnotherDirectAdvanceAssignment(OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create(false, HUNDRED);
advanceType2 = PredefinedAdvancedTypes.UNITS.getType();
directAdvanceAssignment.setAdvanceType(advanceType2);
orderElement.addAdvanceAssignment(directAdvanceAssignment);
}
private void addAnotherDifferentDirectAdvanceAssignment(
OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create(false, HUNDRED);
advanceType3 = PredefinedAdvancedTypes.SUBCONTRACTOR.getType();
directAdvanceAssignment.setAdvanceType(advanceType3);
orderElement.addAdvanceAssignment(directAdvanceAssignment);
}
private void addLabel(OrderElement orderElement) {
label = Label.create("label");
LabelType.create("label-type").addLabel(label);
orderElement.addLabel(label);
}
private void addMaterialAssignment(OrderElement orderElement) {
materialAssignment = MaterialAssignment.create(Material
.createUnvalidated("material-code", "material-description",
HUNDRED, false));
orderElement.addMaterialAssignment(materialAssignment);
}
private void addQualityForm(OrderElement element) {
qualityForm = QualityForm.create("quality-form-name",
"quality-form-description");
element.addTaskQualityForm(qualityForm);
}
private void addTemplate(OrderElement element) {
template = createNiceMock(OrderElementTemplate.class);
expect(template.getName()).andReturn("order-element-template-name")
.anyTimes();
replay(template);
element.initializeTemplate(template);
}
@Test
public void checkAddElementWithCriteriaAndAdvancesOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
addDirectAdvanceAssignment(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
private static void assertDirectCriterion(
CriterionRequirement criterionRequirement, Criterion criterion) {
assertCriterion(criterionRequirement, criterion, true);
}
private static void assertIndirectCriterion(
CriterionRequirement criterionRequirement, Criterion criterion) {
assertCriterion(criterionRequirement, criterion, false);
}
private static void assertCriterion(
CriterionRequirement criterionRequirement, Criterion criterion,
boolean direct) {
if (direct) {
assertTrue(criterionRequirement instanceof DirectCriterionRequirement);
} else {
assertTrue(criterionRequirement instanceof IndirectCriterionRequirement);
}
assertTrue(criterionRequirement.getCriterion().isEquivalent(criterion));
}
@Test
public void checkRemoveElementWithCriteriaAndAdvancesOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
addCriterionRequirement(order);
addDirectAdvanceAssignment(order);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.removeNode(element);
assertTrue(order.getChildren().isEmpty());
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertFalse(order.getCriterionRequirements().isEmpty());
}
@Test
public void checkRemoveElementWithCriteriaAndAdvancesOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
model.removeNode(element);
assertTrue(order.getChildren().isEmpty());
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNull(order.getIndirectAdvanceAssignment(advanceType));
assertTrue(order.getCriterionRequirements().isEmpty());
}
@Test
public void checkAddCriterionOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addCriterionRequirement(element);
assertTrue(order.getCriterionRequirements().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkAddCriterionOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addCriterionRequirement(order);
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkAddAssignmentOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addDirectAdvanceAssignment(element);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertFalse(order.getIndirectAdvanceAssignments().isEmpty());
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
}
@Test
public void checkAddAdvanceOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addDirectAdvanceAssignment(order);
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(order.getDirectAdvanceAssignmentByType(advanceType));
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
}
@Test
public void checkAddElementOnOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addAnotherCriterionRequirement(element);
addDirectAdvanceAssignment(element);
model.addElementAt(element, "element2", 50);
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(order.getWorkHours(), equalTo(150));
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
assertThat(container.getWorkHours(), equalTo(150));
assertThat(container.getChildren().size(), equalTo(2));
for (OrderElement each : container.getChildren()) {
if (each.getName().equals("element")) {
assertThat(each.getCriterionRequirements().size(), equalTo(2));
assertThat(each.getDirectAdvanceAssignments().size(),
equalTo(1));
assertNotNull(each
.getDirectAdvanceAssignmentByType(advanceType));
assertThat(each.getWorkHours(), equalTo(100));
assertThat(element.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(2));
} else if (each.getName().equals("element2")) {
assertThat(each.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(each.getCriterionRequirements()
.iterator().next(), criterion);
assertTrue(each.getDirectAdvanceAssignments().isEmpty());
assertThat(each.getWorkHours(), equalTo(50));
assertThat(each.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(each.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(),
criterion);
} else {
fail("Unexpected OrderElment name: " + each.getName());
}
}
}
@Test
public void checkAddElementOnOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.addElementAt(element, "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
container.setName("container");
addAnotherCriterionRequirement(container);
addDirectAdvanceAssignment(container);
model.addElementAt(container, "element3", 150);
assertThat(order.getWorkHours(), equalTo(300));
assertThat(container.getChildren().size(), equalTo(3));
for (OrderElement each : container.getChildren()) {
if (each.getName().equals("element3")) {
assertThat(each.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement criterionRequirement : each
.getCriterionRequirements()) {
assertTrue(criterionRequirement instanceof IndirectCriterionRequirement);
}
assertTrue(each.getDirectAdvanceAssignments().isEmpty());
assertThat(each.getWorkHours(), equalTo(150));
assertThat(element.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(2));
}
}
}
@Test
public void checkRemoveElementOnOnlyOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.addElementAt(element, "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
model.removeNode(container.getChildren().iterator().next());
element = (OrderLine) container.getChildren().get(0);
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
// * infoComponent (code, name, description)
String name = "container";
container.setName(name);
String code = "code";
container.setCode(code);
String description = "description";
container.setDescription(description);
// * initDate
Date date = new Date();
container.setInitDate(date);
// * deadline
container.setDeadline(date);
// * directAdvanceAssignments
addAnotherDirectAdvanceAssignment(container);
// * materialAssignments
addMaterialAssignment(container);
// * labels
addLabel(container);
// * taskQualityForms
addQualityForm(container);
// * criterionRequirements
addAnotherCriterionRequirement(container);
// * template
addTemplate(container);
// * externalCode
String externalCode = "external-code";
container.setExternalCode(externalCode);
model.removeNode(element);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNull(order.getIndirectAdvanceAssignment(advanceType));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
assertTrue(order.getCriterionRequirements().isEmpty());
assertThat(order.getWorkHours(), equalTo(0));
element = (OrderLine) order.getChildren().get(0);
assertThat(element.getWorkHours(), equalTo(0));
// * infoComponent (code, name, description)
assertThat(element.getName(), equalTo(name));
assertNull(element.getCode());
assertThat(element.getDescription(), equalTo(description));
// * initDate
assertThat(element.getInitDate(), equalTo(date));
// * deadline
assertThat(element.getDeadline(), equalTo(date));
// * directAdvanceAssignments
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(element.getDirectAdvanceAssignmentByType(advanceType2));
assertThat(element.getDirectAdvanceAssignmentByType(advanceType2)
.getOrderElement(), equalTo((OrderElement) element));
// * materialAssignments
assertThat(element.getMaterialAssignments().size(), equalTo(1));
assertThat(element.getMaterialAssignments().iterator().next()
.getMaterial(), equalTo(materialAssignment.getMaterial()));
assertThat(element.getMaterialAssignments().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
// * labels
assertThat(element.getLabels().size(), equalTo(1));
assertThat(element.getLabels().iterator().next(), equalTo(label));
assertThat(element.getLabels().iterator().next().getType(),
equalTo(label.getType()));
// * taskQualityForms
assertThat(element.getQualityForms().size(), equalTo(1));
assertThat(element.getQualityForms().iterator().next(),
equalTo(qualityForm));
assertThat(element.getTaskQualityForms().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
// * criterionRequirements
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion2);
assertThat(element.getCriterionRequirements().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion2);
// * template
assertNotNull(element.getTemplate());
assertThat(element.getTemplate().getName(), equalTo(template.getName()));
// * externalCode
assertThat(element.getExternalCode(), equalTo(externalCode));
}
@Test
public void checkPreservationOfInvalidatedIndirectCriterionRequirementInToLeaf()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.addElementAt(element, "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
model.removeNode(container.getChildren().iterator().next());
IndirectCriterionRequirement indirectCriterionRequirement = (IndirectCriterionRequirement) container
.getCriterionRequirements().iterator().next();
assertTrue(indirectCriterionRequirement.getCriterion().isEquivalent(
criterion));
indirectCriterionRequirement.setValid(false);
addAnotherCriterionRequirement(container);
// This calls toLeaf in the container
model.removeNode(container.getChildren().get(0));
element = (OrderLine) order.getChildren().get(0);
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof IndirectCriterionRequirement);
assertFalse(each.isValid());
} else if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof IndirectCriterionRequirement);
assertFalse(each.isValid());
} else if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof IndirectCriterionRequirement);
assertTrue(each.isValid());
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
@Test
public void checkIndentOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
addCriterionRequirement(element2);
addDirectAdvanceAssignment(element2);
model.indent(element2);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertTrue(order.getCriterionRequirements().isEmpty());
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
assertTrue(container.getCriterionRequirements().isEmpty());
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertTrue(element.getCriterionRequirements().isEmpty());
assertTrue(element.getHoursGroups().get(0).getCriterionRequirements()
.isEmpty());
assertNotNull(element2.getAdvanceAssignmentByType(advanceType));
assertThat(element2.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element2.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element2.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkIndentOnOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
model.indent(element2);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertTrue(order.getCriterionRequirements().isEmpty());
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
assertTrue(container.getCriterionRequirements().isEmpty());
assertNotNull(element.getAdvanceAssignmentByType(advanceType));
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertTrue(element2.getDirectAdvanceAssignments().isEmpty());
assertTrue(element2.getCriterionRequirements().isEmpty());
assertTrue(element2.getHoursGroups().get(0).getCriterionRequirements()
.isEmpty());
}
@Test
public void checkIndentOnOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElementAt(order.getChildren().get(0), "element2", 50);
model.addElement("element3", 30);
OrderLineGroup container = null;
OrderLine element3 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("new container")) {
container = (OrderLineGroup) each;
} else if (each.getName().equals("element3")) {
element3 = (OrderLine) each;
}
}
addCriterionRequirement(container);
addDirectAdvanceAssignment(container);
model.indent(element3);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertTrue(order.getCriterionRequirements().isEmpty());
assertNotNull(container.getAdvanceAssignmentByType(advanceType));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertTrue(element3.getDirectAdvanceAssignments().isEmpty());
assertThat(element3.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element3.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(container.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkUnindentOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
model.indent(element2);
addCriterionRequirement(element2);
addDirectAdvanceAssignment(element2);
addAnotherDirectAdvanceAssignment(element2);
addAnotherDirectAdvanceAssignment(element);
addAnotherCriterionRequirement(order);
model.unindent(element2);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNull(container.getIndirectAdvanceAssignment(advanceType));
assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(element.getAdvanceAssignmentByType(advanceType2));
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertNotNull(element2.getAdvanceAssignmentByType(advanceType));
assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if ((each.getCriterion().isEquivalent(criterion) || each
.getCriterion().isEquivalent(criterion2))) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
@Test
public void checkMoveOrderLineWithCriteriaAndAdvancesToOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
addAnotherCriterionRequirement(element2);
addAnotherDirectAdvanceAssignment(element2);
addAnotherDifferentCriterionRequirement(order);
addAnotherDifferentDirectAdvanceAssignment(order);
model.move(element2, element);
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(order.getDirectAdvanceAssignmentByType(advanceType3));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion3);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
assertNull(container.getIndirectAdvanceAssignment(advanceType3));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion3);
assertNotNull(element.getAdvanceAssignmentByType(advanceType));
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion2)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
@Test
public void checkMoveOrderLineWithCriteriaAndAdvancesToOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElementAt(order.getChildren().get(0), "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : container.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
model.unindent(element2);
addCriterionRequirement(container);
addDirectAdvanceAssignment(container);
addAnotherCriterionRequirement(element2);
addAnotherDirectAdvanceAssignment(element2);
addAnotherDifferentCriterionRequirement(order);
addAnotherDifferentDirectAdvanceAssignment(order);
model.move(element2, container);
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(order.getDirectAdvanceAssignmentByType(advanceType3));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion3);
assertThat(container.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(container.getDirectAdvanceAssignmentByType(advanceType));
assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
assertNull(container.getIndirectAdvanceAssignment(advanceType3));
assertThat(container.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : container.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
assertThat(element2.getCriterionRequirements().size(), equalTo(3));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(3));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion2)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
}
| navalplanner-webapp/src/test/java/org/navalplanner/web/orders/OrderElementTreeModelTest.java | /*
* This file is part of NavalPlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2011 Igalia, S.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.web.orders;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.navalplanner.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE;
import static org.navalplanner.web.WebappGlobalNames.WEBAPP_SPRING_CONFIG_FILE;
import static org.navalplanner.web.WebappGlobalNames.WEBAPP_SPRING_SECURITY_CONFIG_FILE;
import static org.navalplanner.web.test.WebappGlobalNames.WEBAPP_SPRING_CONFIG_TEST_FILE;
import static org.navalplanner.web.test.WebappGlobalNames.WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE;
import java.math.BigDecimal;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.navalplanner.business.IDataBootstrap;
import org.navalplanner.business.advance.bootstrap.PredefinedAdvancedTypes;
import org.navalplanner.business.advance.entities.DirectAdvanceAssignment;
import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException;
import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException;
import org.navalplanner.business.labels.entities.Label;
import org.navalplanner.business.labels.entities.LabelType;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.orders.entities.OrderLine;
import org.navalplanner.business.orders.entities.OrderLineGroup;
import org.navalplanner.business.qualityforms.entities.QualityForm;
import org.navalplanner.business.requirements.entities.CriterionRequirement;
import org.navalplanner.business.requirements.entities.DirectCriterionRequirement;
import org.navalplanner.business.requirements.entities.IndirectCriterionRequirement;
import org.navalplanner.business.resources.daos.ICriterionDAO;
import org.navalplanner.business.resources.entities.Criterion;
import org.navalplanner.business.scenarios.bootstrap.PredefinedScenarios;
import org.navalplanner.business.scenarios.entities.OrderVersion;
import org.navalplanner.business.scenarios.entities.Scenario;
import org.navalplanner.business.templates.entities.OrderElementTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* Tests for {@link OrderElementTreeModel}
*
* @author Manuel Rego Casasnovas <[email protected]>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
WEBAPP_SPRING_CONFIG_FILE, WEBAPP_SPRING_CONFIG_TEST_FILE,
WEBAPP_SPRING_SECURITY_CONFIG_FILE,
WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE })
@Transactional
public class OrderElementTreeModelTest {
private static final BigDecimal HUNDRED = new BigDecimal(100);
@Resource
private IDataBootstrap defaultAdvanceTypesBootstrapListener;
@Resource
private IDataBootstrap scenariosBootstrap;
@Resource
private IDataBootstrap criterionsBootstrap;
@Resource
private IDataBootstrap configurationBootstrap;
@Autowired
private ICriterionDAO criterionDAO;
private Order order;
private OrderElementTreeModel model;
private Criterion criterion, criterion2, criterion3;
private DirectAdvanceAssignment directAdvanceAssignment,
directAdvanceAssignment2, directAdvanceAssignment3;
private MaterialAssignment materialAssignment;
private Label label;
private QualityForm qualityForm;
private OrderElementTemplate template;
@Before
public void loadRequiredaData() {
// Load data
configurationBootstrap.loadRequiredData();
defaultAdvanceTypesBootstrapListener.loadRequiredData();
scenariosBootstrap.loadRequiredData();
criterionsBootstrap.loadRequiredData();
givenOrder();
givenModel();
}
private void givenOrder() {
order = Order.create();
order.setName("order");
Scenario scenario = PredefinedScenarios.MASTER.getScenario();
OrderVersion result = OrderVersion.createInitialVersion(scenario);
order.setVersionForScenario(scenario, result);
order.useSchedulingDataFor(scenario);
}
private void givenModel() {
model = new OrderElementTreeModel(order);
}
private void addCriterionRequirement(OrderElement orderElement) {
criterion = criterionDAO.findByNameAndType("medicalLeave", "LEAVE")
.get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addAnotherCriterionRequirement(OrderElement orderElement) {
criterion2 = criterionDAO.findByNameAndType(
"hiredResourceWorkingRelationship", "WORK_RELATIONSHIP").get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion2);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addAnotherDifferentCriterionRequirement(
OrderElement orderElement) {
criterion3 = criterionDAO.findByNameAndType("paternityLeave", "LEAVE")
.get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion3);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addDirectAdvanceAssignment(OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
directAdvanceAssignment = DirectAdvanceAssignment.create(true, HUNDRED);
directAdvanceAssignment
.setAdvanceType(PredefinedAdvancedTypes.PERCENTAGE.getType());
orderElement.addAdvanceAssignment(directAdvanceAssignment);
}
private void addAnotherDirectAdvanceAssignment(OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
directAdvanceAssignment2 = DirectAdvanceAssignment.create(false,
HUNDRED);
directAdvanceAssignment2.setAdvanceType(PredefinedAdvancedTypes.UNITS
.getType());
orderElement.addAdvanceAssignment(directAdvanceAssignment2);
}
private void addAnotherDifferentDirectAdvanceAssignment(
OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
directAdvanceAssignment3 = DirectAdvanceAssignment.create(false,
HUNDRED);
directAdvanceAssignment3
.setAdvanceType(PredefinedAdvancedTypes.SUBCONTRACTOR.getType());
orderElement.addAdvanceAssignment(directAdvanceAssignment3);
}
private void addLabel(OrderElement orderElement) {
label = Label.create("label");
LabelType.create("label-type").addLabel(label);
orderElement.addLabel(label);
}
private void addMaterialAssignment(OrderElement orderElement) {
materialAssignment = MaterialAssignment.create(Material
.createUnvalidated("material-code", "material-description",
HUNDRED, false));
orderElement.addMaterialAssignment(materialAssignment);
}
private void addQualityForm(OrderElement element) {
qualityForm = QualityForm.create("quality-form-name",
"quality-form-description");
element.addTaskQualityForm(qualityForm);
}
private void addTemplate(OrderElement element) {
template = createNiceMock(OrderElementTemplate.class);
expect(template.getName()).andReturn("order-element-template-name")
.anyTimes();
replay(template);
element.initializeTemplate(template);
}
@Test
public void checkAddElementWithCriteriaAndAdvancesOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
addDirectAdvanceAssignment(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
private static void assertDirectCriterion(
CriterionRequirement criterionRequirement, Criterion criterion) {
assertCriterion(criterionRequirement, criterion, true);
}
private static void assertIndirectCriterion(
CriterionRequirement criterionRequirement, Criterion criterion) {
assertCriterion(criterionRequirement, criterion, false);
}
private static void assertCriterion(
CriterionRequirement criterionRequirement,
Criterion criterion,
boolean direct) {
if (direct) {
assertTrue(criterionRequirement instanceof DirectCriterionRequirement);
} else {
assertTrue(criterionRequirement instanceof IndirectCriterionRequirement);
}
assertTrue(criterionRequirement.getCriterion().isEquivalent(criterion));
}
@Test
public void checkRemoveElementWithCriteriaAndAdvancesOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
addCriterionRequirement(order);
addDirectAdvanceAssignment(order);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.removeNode(element);
assertTrue(order.getChildren().isEmpty());
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertFalse(order.getCriterionRequirements().isEmpty());
}
@Test
public void checkRemoveElementWithCriteriaAndAdvancesOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
model.removeNode(element);
assertTrue(order.getChildren().isEmpty());
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNull(order.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertTrue(order.getCriterionRequirements().isEmpty());
}
@Test
public void checkAddCriterionOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addCriterionRequirement(element);
assertTrue(order.getCriterionRequirements().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkAddCriterionOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addCriterionRequirement(order);
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkAddAssignmentOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addDirectAdvanceAssignment(element);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertFalse(order.getIndirectAdvanceAssignments().isEmpty());
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
}
@Test
public void checkAddAdvanceOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addDirectAdvanceAssignment(order);
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(order
.getDirectAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
}
@Test
public void checkAddElementOnOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addAnotherCriterionRequirement(element);
addDirectAdvanceAssignment(element);
model.addElementAt(element, "element2", 50);
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(order.getWorkHours(), equalTo(150));
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertNotNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertThat(container.getWorkHours(), equalTo(150));
assertThat(container.getChildren().size(), equalTo(2));
for (OrderElement each : container.getChildren()) {
if (each.getName().equals("element")) {
assertThat(each.getCriterionRequirements().size(), equalTo(2));
assertThat(each.getDirectAdvanceAssignments().size(),
equalTo(1));
assertNotNull(each
.getDirectAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertThat(each.getWorkHours(), equalTo(100));
assertThat(element.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(2));
} else if (each.getName().equals("element2")) {
assertThat(each.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(each.getCriterionRequirements()
.iterator().next(), criterion);
assertTrue(each.getDirectAdvanceAssignments().isEmpty());
assertThat(each.getWorkHours(), equalTo(50));
assertThat(each.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(each.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(),
criterion);
} else {
fail("Unexpected OrderElment name: " + each.getName());
}
}
}
@Test
public void checkAddElementOnOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.addElementAt(element, "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
container.setName("container");
addAnotherCriterionRequirement(container);
addDirectAdvanceAssignment(container);
model.addElementAt(container, "element3", 150);
assertThat(order.getWorkHours(), equalTo(300));
assertThat(container.getChildren().size(), equalTo(3));
for (OrderElement each : container.getChildren()) {
if (each.getName().equals("element3")) {
assertThat(each.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement criterionRequirement : each
.getCriterionRequirements()) {
assertTrue(criterionRequirement instanceof IndirectCriterionRequirement);
}
assertTrue(each.getDirectAdvanceAssignments().isEmpty());
assertThat(each.getWorkHours(), equalTo(150));
assertThat(element.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(2));
}
}
}
@Test
public void checkRemoveElementOnOnlyOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.addElementAt(element, "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
model.removeNode(container.getChildren().iterator().next());
element = (OrderLine) container.getChildren().get(0);
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
// * infoComponent (code, name, description)
String name = "container";
container.setName(name);
String code = "code";
container.setCode(code);
String description = "description";
container.setDescription(description);
// * initDate
Date date = new Date();
container.setInitDate(date);
// * deadline
container.setDeadline(date);
// * directAdvanceAssignments
addAnotherDirectAdvanceAssignment(container);
// * materialAssignments
addMaterialAssignment(container);
// * labels
addLabel(container);
// * taskQualityForms
addQualityForm(container);
// * criterionRequirements
addAnotherCriterionRequirement(container);
// * template
addTemplate(container);
// * externalCode
String externalCode = "external-code";
container.setExternalCode(externalCode);
model.removeNode(element);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNull(order.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment2
.getAdvanceType()));
assertTrue(order.getCriterionRequirements().isEmpty());
assertThat(order.getWorkHours(), equalTo(0));
element = (OrderLine) order.getChildren().get(0);
assertThat(element.getWorkHours(), equalTo(0));
// * infoComponent (code, name, description)
assertThat(element.getName(), equalTo(name));
assertNull(element.getCode());
assertThat(element.getDescription(), equalTo(description));
// * initDate
assertThat(element.getInitDate(), equalTo(date));
// * deadline
assertThat(element.getDeadline(), equalTo(date));
// * directAdvanceAssignments
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(element
.getDirectAdvanceAssignmentByType(directAdvanceAssignment2
.getAdvanceType()));
assertThat(element.getDirectAdvanceAssignmentByType(
directAdvanceAssignment2.getAdvanceType()).getOrderElement(),
equalTo((OrderElement) element));
// * materialAssignments
assertThat(element.getMaterialAssignments().size(), equalTo(1));
assertThat(element.getMaterialAssignments().iterator().next()
.getMaterial(), equalTo(materialAssignment.getMaterial()));
assertThat(element.getMaterialAssignments().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
// * labels
assertThat(element.getLabels().size(), equalTo(1));
assertThat(element.getLabels().iterator().next(), equalTo(label));
assertThat(element.getLabels().iterator().next().getType(),
equalTo(label.getType()));
// * taskQualityForms
assertThat(element.getQualityForms().size(), equalTo(1));
assertThat(element.getQualityForms().iterator().next(),
equalTo(qualityForm));
assertThat(element.getTaskQualityForms().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
// * criterionRequirements
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion2);
assertThat(element.getCriterionRequirements().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion2);
// * template
assertNotNull(element.getTemplate());
assertThat(element.getTemplate().getName(), equalTo(template.getName()));
// * externalCode
assertThat(element.getExternalCode(), equalTo(externalCode));
}
@Test
public void checkPreservationOfInvalidatedIndirectCriterionRequirementInToLeaf()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.addElementAt(element, "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
model.removeNode(container.getChildren().iterator().next());
IndirectCriterionRequirement indirectCriterionRequirement = (IndirectCriterionRequirement) container
.getCriterionRequirements().iterator().next();
assertTrue(indirectCriterionRequirement.getCriterion().isEquivalent(
criterion));
indirectCriterionRequirement.setValid(false);
addAnotherCriterionRequirement(container);
// This calls toLeaf in the container
model.removeNode(container.getChildren().get(0));
element = (OrderLine) order.getChildren().get(0);
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof IndirectCriterionRequirement);
assertFalse(each.isValid());
} else if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof IndirectCriterionRequirement);
assertFalse(each.isValid());
} else if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof IndirectCriterionRequirement);
assertTrue(each.isValid());
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
@Test
public void checkIndentOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
addCriterionRequirement(element2);
addDirectAdvanceAssignment(element2);
model.indent(element2);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertTrue(order.getCriterionRequirements().isEmpty());
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNotNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertTrue(container.getCriterionRequirements().isEmpty());
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertTrue(element.getCriterionRequirements().isEmpty());
assertTrue(element.getHoursGroups().get(0).getCriterionRequirements()
.isEmpty());
assertNotNull(element2
.getAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertThat(element2.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element2.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element2.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkIndentOnOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
model.indent(element2);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertTrue(order.getCriterionRequirements().isEmpty());
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNotNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertTrue(container.getCriterionRequirements().isEmpty());
assertNotNull(element
.getAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertTrue(element2.getDirectAdvanceAssignments().isEmpty());
assertTrue(element2.getCriterionRequirements().isEmpty());
assertTrue(element2.getHoursGroups().get(0).getCriterionRequirements()
.isEmpty());
}
@Test
public void checkIndentOnOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElementAt(order.getChildren().get(0), "element2", 50);
model.addElement("element3", 30);
OrderLineGroup container = null;
OrderLine element3 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("new container")) {
container = (OrderLineGroup) each;
} else if (each.getName().equals("element3")) {
element3 = (OrderLine) each;
}
}
addCriterionRequirement(container);
addDirectAdvanceAssignment(container);
model.indent(element3);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertTrue(order.getCriterionRequirements().isEmpty());
assertNotNull(container
.getAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertTrue(element3.getDirectAdvanceAssignments().isEmpty());
assertThat(element3.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element3.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(container.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
}
@Test
public void checkUnindentOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
model.indent(element2);
addCriterionRequirement(element2);
addDirectAdvanceAssignment(element2);
addAnotherDirectAdvanceAssignment(element2);
addAnotherDirectAdvanceAssignment(element);
addAnotherCriterionRequirement(order);
model.unindent(element2);
assertTrue(order.getDirectAdvanceAssignments().isEmpty());
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment2
.getAdvanceType()));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment2
.getAdvanceType()));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(element
.getAdvanceAssignmentByType(directAdvanceAssignment2
.getAdvanceType()));
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertNotNull(element2
.getAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(element2
.getAdvanceAssignmentByType(directAdvanceAssignment2
.getAdvanceType()));
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if ((each.getCriterion().isEquivalent(criterion) || each
.getCriterion().isEquivalent(criterion2))) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
@Test
public void checkMoveOrderLineWithCriteriaAndAdvancesToOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
addCriterionRequirement(element);
addDirectAdvanceAssignment(element);
addAnotherCriterionRequirement(element2);
addAnotherDirectAdvanceAssignment(element2);
addAnotherDifferentCriterionRequirement(order);
addAnotherDifferentDirectAdvanceAssignment(order);
model.move(element2, element);
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(order
.getDirectAdvanceAssignmentByType(directAdvanceAssignment3
.getAdvanceType()));
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment2
.getAdvanceType()));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion3);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
assertNotNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment2
.getAdvanceType()));
assertNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment3
.getAdvanceType()));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion3);
assertNotNull(element
.getAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0).getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertNotNull(element2
.getAdvanceAssignmentByType(directAdvanceAssignment2
.getAdvanceType()));
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion2)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
@Test
public void checkMoveOrderLineWithCriteriaAndAdvancesToOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElementAt(order.getChildren().get(0), "element2", 50);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : container.getChildren()) {
if (each.getName().equals("element")) {
element = (OrderLine) each;
} else if (each.getName().equals("element2")) {
element2 = (OrderLine) each;
}
}
model.unindent(element2);
addCriterionRequirement(container);
addDirectAdvanceAssignment(container);
addAnotherCriterionRequirement(element2);
addAnotherDirectAdvanceAssignment(element2);
addAnotherDifferentCriterionRequirement(order);
addAnotherDifferentDirectAdvanceAssignment(order);
model.move(element2, container);
assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(order
.getDirectAdvanceAssignmentByType(directAdvanceAssignment3
.getAdvanceType()));
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(order
.getIndirectAdvanceAssignment(directAdvanceAssignment2
.getAdvanceType()));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion3);
assertThat(container.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(container
.getDirectAdvanceAssignmentByType(directAdvanceAssignment
.getAdvanceType()));
assertNotNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment2
.getAdvanceType()));
assertNull(container
.getIndirectAdvanceAssignment(directAdvanceAssignment3
.getAdvanceType()));
assertThat(container.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : container.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertNotNull(element2
.getAdvanceAssignmentByType(directAdvanceAssignment2
.getAdvanceType()));
assertThat(element2.getCriterionRequirements().size(), equalTo(3));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion2)) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(3));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion2)
|| each.getCriterion().isEquivalent(criterion3)) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
}
} | Refactorized test to have AdvanceType as checking variables.
FEA: ItEr74S07WBSTreeRefactoring
| navalplanner-webapp/src/test/java/org/navalplanner/web/orders/OrderElementTreeModelTest.java | Refactorized test to have AdvanceType as checking variables. | <ide><path>avalplanner-webapp/src/test/java/org/navalplanner/web/orders/OrderElementTreeModelTest.java
<ide> import org.junit.runner.RunWith;
<ide> import org.navalplanner.business.IDataBootstrap;
<ide> import org.navalplanner.business.advance.bootstrap.PredefinedAdvancedTypes;
<add>import org.navalplanner.business.advance.entities.AdvanceType;
<ide> import org.navalplanner.business.advance.entities.DirectAdvanceAssignment;
<ide> import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException;
<ide> import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException;
<ide>
<ide> private Criterion criterion, criterion2, criterion3;
<ide>
<del> private DirectAdvanceAssignment directAdvanceAssignment,
<del> directAdvanceAssignment2, directAdvanceAssignment3;
<add> private AdvanceType advanceType, advanceType2, advanceType3;
<ide>
<ide> private MaterialAssignment materialAssignment;
<ide>
<ide> private void addDirectAdvanceAssignment(OrderElement orderElement)
<ide> throws DuplicateValueTrueReportGlobalAdvanceException,
<ide> DuplicateAdvanceAssignmentForOrderElementException {
<del> directAdvanceAssignment = DirectAdvanceAssignment.create(true, HUNDRED);
<del> directAdvanceAssignment
<del> .setAdvanceType(PredefinedAdvancedTypes.PERCENTAGE.getType());
<add> DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
<add> .create(true, HUNDRED);
<add> advanceType = PredefinedAdvancedTypes.PERCENTAGE.getType();
<add> directAdvanceAssignment.setAdvanceType(advanceType);
<ide> orderElement.addAdvanceAssignment(directAdvanceAssignment);
<ide> }
<ide>
<ide> private void addAnotherDirectAdvanceAssignment(OrderElement orderElement)
<ide> throws DuplicateValueTrueReportGlobalAdvanceException,
<ide> DuplicateAdvanceAssignmentForOrderElementException {
<del> directAdvanceAssignment2 = DirectAdvanceAssignment.create(false,
<del> HUNDRED);
<del> directAdvanceAssignment2.setAdvanceType(PredefinedAdvancedTypes.UNITS
<del> .getType());
<del> orderElement.addAdvanceAssignment(directAdvanceAssignment2);
<add> DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
<add> .create(false, HUNDRED);
<add> advanceType2 = PredefinedAdvancedTypes.UNITS.getType();
<add> directAdvanceAssignment.setAdvanceType(advanceType2);
<add> orderElement.addAdvanceAssignment(directAdvanceAssignment);
<ide> }
<ide>
<ide> private void addAnotherDifferentDirectAdvanceAssignment(
<ide> OrderElement orderElement)
<ide> throws DuplicateValueTrueReportGlobalAdvanceException,
<ide> DuplicateAdvanceAssignmentForOrderElementException {
<del> directAdvanceAssignment3 = DirectAdvanceAssignment.create(false,
<del> HUNDRED);
<del> directAdvanceAssignment3
<del> .setAdvanceType(PredefinedAdvancedTypes.SUBCONTRACTOR.getType());
<del> orderElement.addAdvanceAssignment(directAdvanceAssignment3);
<add> DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
<add> .create(false, HUNDRED);
<add> advanceType3 = PredefinedAdvancedTypes.SUBCONTRACTOR.getType();
<add> directAdvanceAssignment.setAdvanceType(advanceType3);
<add> orderElement.addAdvanceAssignment(directAdvanceAssignment);
<ide> }
<ide>
<ide> private void addLabel(OrderElement orderElement) {
<ide> }
<ide>
<ide> private static void assertCriterion(
<del> CriterionRequirement criterionRequirement,
<del> Criterion criterion,
<add> CriterionRequirement criterionRequirement, Criterion criterion,
<ide> boolean direct) {
<ide> if (direct) {
<ide> assertTrue(criterionRequirement instanceof DirectCriterionRequirement);
<ide> addCriterionRequirement(element);
<ide> addDirectAdvanceAssignment(element);
<ide>
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<ide>
<ide> model.removeNode(element);
<ide> assertTrue(order.getChildren().isEmpty());
<ide> assertTrue(order.getDirectAdvanceAssignments().isEmpty());
<del> assertNull(order.getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNull(order.getIndirectAdvanceAssignment(advanceType));
<ide> assertTrue(order.getCriterionRequirements().isEmpty());
<ide> }
<ide>
<ide> addDirectAdvanceAssignment(element);
<ide> assertTrue(order.getDirectAdvanceAssignments().isEmpty());
<ide> assertFalse(order.getIndirectAdvanceAssignments().isEmpty());
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<ide> assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
<ide> }
<ide>
<ide> addDirectAdvanceAssignment(order);
<ide>
<ide> assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
<del> assertNotNull(order
<del> .getDirectAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(order.getDirectAdvanceAssignmentByType(advanceType));
<ide> assertTrue(element.getDirectAdvanceAssignments().isEmpty());
<ide> }
<ide>
<ide>
<ide> model.addElementAt(element, "element2", 50);
<ide>
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<ide> assertThat(order.getCriterionRequirements().size(), equalTo(1));
<ide> assertDirectCriterion(order.getCriterionRequirements().iterator()
<ide> .next(), criterion);
<ide> assertThat(container.getCriterionRequirements().size(), equalTo(1));
<ide> assertIndirectCriterion(container.getCriterionRequirements().iterator()
<ide> .next(), criterion);
<del> assertNotNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
<ide> assertThat(container.getWorkHours(), equalTo(150));
<ide>
<ide> assertThat(container.getChildren().size(), equalTo(2));
<ide> assertThat(each.getDirectAdvanceAssignments().size(),
<ide> equalTo(1));
<ide> assertNotNull(each
<del> .getDirectAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<add> .getDirectAdvanceAssignmentByType(advanceType));
<ide> assertThat(each.getWorkHours(), equalTo(100));
<ide> assertThat(element.getHoursGroups().get(0)
<ide> .getCriterionRequirements().size(), equalTo(2));
<ide> model.removeNode(element);
<ide>
<ide> assertTrue(order.getDirectAdvanceAssignments().isEmpty());
<del> assertNull(order.getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNull(order.getIndirectAdvanceAssignment(advanceType));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
<ide> assertTrue(order.getCriterionRequirements().isEmpty());
<ide> assertThat(order.getWorkHours(), equalTo(0));
<ide>
<ide>
<ide> // * directAdvanceAssignments
<ide> assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
<del> assertNotNull(element
<del> .getDirectAdvanceAssignmentByType(directAdvanceAssignment2
<del> .getAdvanceType()));
<del> assertThat(element.getDirectAdvanceAssignmentByType(
<del> directAdvanceAssignment2.getAdvanceType()).getOrderElement(),
<del> equalTo((OrderElement) element));
<add> assertNotNull(element.getDirectAdvanceAssignmentByType(advanceType2));
<add> assertThat(element.getDirectAdvanceAssignmentByType(advanceType2)
<add> .getOrderElement(), equalTo((OrderElement) element));
<ide>
<ide> // * materialAssignments
<ide> assertThat(element.getMaterialAssignments().size(), equalTo(1));
<ide> model.indent(element2);
<ide>
<ide> assertTrue(order.getDirectAdvanceAssignments().isEmpty());
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<ide> assertTrue(order.getCriterionRequirements().isEmpty());
<ide>
<ide> OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
<ide> assertTrue(container.getDirectAdvanceAssignments().isEmpty());
<del> assertNotNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
<ide> assertTrue(container.getCriterionRequirements().isEmpty());
<ide>
<ide> assertTrue(element.getDirectAdvanceAssignments().isEmpty());
<ide> assertTrue(element.getHoursGroups().get(0).getCriterionRequirements()
<ide> .isEmpty());
<ide>
<del> assertNotNull(element2
<del> .getAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(element2.getAdvanceAssignmentByType(advanceType));
<ide> assertThat(element2.getCriterionRequirements().size(), equalTo(1));
<ide> assertDirectCriterion(element2.getCriterionRequirements().iterator()
<ide> .next(), criterion);
<ide> model.indent(element2);
<ide>
<ide> assertTrue(order.getDirectAdvanceAssignments().isEmpty());
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<ide> assertTrue(order.getCriterionRequirements().isEmpty());
<ide>
<ide> OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
<ide> assertTrue(container.getDirectAdvanceAssignments().isEmpty());
<del> assertNotNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
<ide> assertTrue(container.getCriterionRequirements().isEmpty());
<ide>
<del> assertNotNull(element
<del> .getAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(element.getAdvanceAssignmentByType(advanceType));
<ide> assertThat(element.getCriterionRequirements().size(), equalTo(1));
<ide> assertDirectCriterion(element.getCriterionRequirements().iterator()
<ide> .next(), criterion);
<ide> model.indent(element3);
<ide>
<ide> assertTrue(order.getDirectAdvanceAssignments().isEmpty());
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<ide> assertTrue(order.getCriterionRequirements().isEmpty());
<ide>
<del> assertNotNull(container
<del> .getAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(container.getAdvanceAssignmentByType(advanceType));
<ide> assertThat(container.getCriterionRequirements().size(), equalTo(1));
<ide> assertDirectCriterion(container.getCriterionRequirements().iterator()
<ide> .next(), criterion);
<ide> model.unindent(element2);
<ide>
<ide> assertTrue(order.getDirectAdvanceAssignments().isEmpty());
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
<ide> assertThat(order.getCriterionRequirements().size(), equalTo(1));
<ide>
<ide> OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
<ide> assertTrue(container.getDirectAdvanceAssignments().isEmpty());
<del> assertNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNull(container.getIndirectAdvanceAssignment(advanceType));
<add> assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
<ide> assertThat(container.getCriterionRequirements().size(), equalTo(1));
<ide>
<ide> assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
<del> assertNotNull(element
<del> .getAdvanceAssignmentByType(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNotNull(element.getAdvanceAssignmentByType(advanceType2));
<ide> assertThat(element.getCriterionRequirements().size(), equalTo(1));
<ide> assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
<ide> .size(), equalTo(1));
<ide>
<del> assertNotNull(element2
<del> .getAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(element2
<del> .getAdvanceAssignmentByType(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNotNull(element2.getAdvanceAssignmentByType(advanceType));
<add> assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
<ide> assertThat(element2.getCriterionRequirements().size(), equalTo(2));
<ide> for (CriterionRequirement each : element2.getCriterionRequirements()) {
<ide> if (each.getCriterion().isEquivalent(criterion)) {
<ide> model.move(element2, element);
<ide>
<ide> assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
<del> assertNotNull(order
<del> .getDirectAdvanceAssignmentByType(directAdvanceAssignment3
<del> .getAdvanceType()));
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNotNull(order.getDirectAdvanceAssignmentByType(advanceType3));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
<ide> assertThat(order.getCriterionRequirements().size(), equalTo(1));
<ide> assertDirectCriterion(order.getCriterionRequirements().iterator()
<ide> .next(), criterion3);
<ide>
<ide> OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
<ide> assertTrue(container.getDirectAdvanceAssignments().isEmpty());
<del> assertNotNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment2
<del> .getAdvanceType()));
<del> assertNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment3
<del> .getAdvanceType()));
<add> assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
<add> assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
<add> assertNull(container.getIndirectAdvanceAssignment(advanceType3));
<ide> assertThat(container.getCriterionRequirements().size(), equalTo(1));
<ide> assertIndirectCriterion(container.getCriterionRequirements().iterator()
<ide> .next(), criterion3);
<ide>
<del> assertNotNull(element
<del> .getAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<add> assertNotNull(element.getAdvanceAssignmentByType(advanceType));
<ide> assertThat(element.getCriterionRequirements().size(), equalTo(2));
<ide> for (CriterionRequirement each : element.getCriterionRequirements()) {
<ide> if (each.getCriterion().isEquivalent(criterion)) {
<ide> }
<ide> assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
<ide> .size(), equalTo(2));
<del> for (CriterionRequirement each : element.getHoursGroups().get(0).getCriterionRequirements()) {
<add> for (CriterionRequirement each : element.getHoursGroups().get(0)
<add> .getCriterionRequirements()) {
<ide> if (each.getCriterion().isEquivalent(criterion)
<ide> || each.getCriterion().isEquivalent(criterion3)) {
<ide> assertTrue(each instanceof IndirectCriterionRequirement);
<ide> }
<ide> }
<ide>
<del> assertNotNull(element2
<del> .getAdvanceAssignmentByType(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
<ide> assertThat(element2.getCriterionRequirements().size(), equalTo(2));
<ide> for (CriterionRequirement each : element2.getCriterionRequirements()) {
<ide> if (each.getCriterion().isEquivalent(criterion2)) {
<ide> model.move(element2, container);
<ide>
<ide> assertThat(order.getDirectAdvanceAssignments().size(), equalTo(1));
<del> assertNotNull(order
<del> .getDirectAdvanceAssignmentByType(directAdvanceAssignment3
<del> .getAdvanceType()));
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(order
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNotNull(order.getDirectAdvanceAssignmentByType(advanceType3));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
<add> assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
<ide> assertThat(order.getCriterionRequirements().size(), equalTo(1));
<ide> assertDirectCriterion(order.getCriterionRequirements().iterator()
<ide> .next(), criterion3);
<ide>
<ide> assertThat(container.getDirectAdvanceAssignments().size(), equalTo(1));
<del> assertNotNull(container
<del> .getDirectAdvanceAssignmentByType(directAdvanceAssignment
<del> .getAdvanceType()));
<del> assertNotNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment2
<del> .getAdvanceType()));
<del> assertNull(container
<del> .getIndirectAdvanceAssignment(directAdvanceAssignment3
<del> .getAdvanceType()));
<add> assertNotNull(container.getDirectAdvanceAssignmentByType(advanceType));
<add> assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
<add> assertNull(container.getIndirectAdvanceAssignment(advanceType3));
<ide> assertThat(container.getCriterionRequirements().size(), equalTo(2));
<ide> for (CriterionRequirement each : container.getCriterionRequirements()) {
<ide> if (each.getCriterion().isEquivalent(criterion3)) {
<ide> }
<ide> }
<ide>
<del> assertNotNull(element2
<del> .getAdvanceAssignmentByType(directAdvanceAssignment2
<del> .getAdvanceType()));
<add> assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
<ide> assertThat(element2.getCriterionRequirements().size(), equalTo(3));
<ide> for (CriterionRequirement each : element2.getCriterionRequirements()) {
<ide> if (each.getCriterion().isEquivalent(criterion2)) { |
|
Java | apache-2.0 | 28d0da4be9e4515418ec44c826d2540cdff09a60 | 0 | PathVisio/libGPML,PathVisio/libGPML | /*******************************************************************************
* PathVisio, a tool for data visualization and analysis using biological pathways
* Copyright 2006-2021 BiGCaT Bioinformatics, WikiPathways
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.pathvisio.io;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.io.ByteArrayInputStream;
import org.bridgedb.DataSource;
import org.bridgedb.Xref;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaderJDOMFactory;
import org.jdom2.input.sax.XMLReaderXSDFactory;
import org.pathvisio.debug.Logger;
import org.pathvisio.io.*;
import org.pathvisio.model.*;
import org.pathvisio.model.graphics.*;
import org.pathvisio.model.elements.*;
import org.pathvisio.model.type.*;
public class GPML2021Reader extends GpmlFormatAbstract implements GpmlFormatReader {
public static final GPML2021Reader GPML2021READER = new GPML2021Reader("GPML2021.xsd",
Namespace.getNamespace("http://pathvisio.org/GPML/2021"));
protected GPML2021Reader(String xsdFile, Namespace nsGPML) {
super(xsdFile, nsGPML);
}
/*------------------------------------MY METHODS --------------------------------------*/
//
// public PathwayModel readFromXml(InputStream is) throws ConverterException {
// PathwayModel pathwayModel = null;
// try {
// XMLReaderJDOMFactory schemafactory = new XMLReaderXSDFactory(xsdFile); // schema
// SAXBuilder builder = new SAXBuilder(schemafactory);
// Document doc = builder.build(is);
// Element root = doc.getRootElement();
// System.out.println("Root: " + doc.getRootElement());
// pathwayModel = readFromRoot(pathwayModel, root);
// } catch (JDOMException e) {
// throw new ConverterException(e);
// } catch (IOException e) {
// throw new ConverterException(e);
// } catch (Exception e) {
// throw new ConverterException(e); // TODO e.printStackTrace()?
// }
// return pathwayModel;// TODO do we want to return pathway or not?
// }
//
// /**
// * Read the JDOM document from the file specified
// *
// * @param file the file from which the JDOM document should be read.
// * @throws ConverterException
// */
// public PathwayModel readFromXml(File file) throws ConverterException {
// InputStream is;
// try {
// is = new FileInputStream(file);
// } catch (FileNotFoundException e) {
// throw new ConverterException(e);
// }
// return readFromXml(is);
// }
//
// /**
// * Read the JDOM document from the file specified
// *
// * @param s the string input.
// * @param string the file from which the JDOM document should be read.
// * @throws ConverterException
// */
// public PathwayModel readFromXml(String str) throws ConverterException {
// if (str == null)
// return null;
// InputStream is;
// try {
// is = stringToInputStream(str);// TODO does this work?
// } catch (Exception e) {
// throw new ConverterException(e);
// }
// return readFromXml(is);
// }
//
// // METHOD FROM UTILS
// public static InputStream stringToInputStream(String str) {
// if (str == null)
// return null;
// InputStream is = null;
// try {
// is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
// } catch (Exception ex) {
// }
// return is;
// }
public PathwayModel readFromRoot(PathwayModel pathwayModel, Element root) throws ConverterException {
Pathway pathway = readPathway(root);
System.out.println("read pathway");
pathwayModel.setPathway(pathway); // = new PathwayModel(pathway); // TODO think about order
System.out.println("set pathway");
readAuthors(pathwayModel, root);
System.out.println("read authors");
readAnnotations(pathwayModel, root);
System.out.println("read success");
readCitations(pathwayModel, root);
System.out.println("read success");
readEvidences(pathwayModel, root);
System.out.println(pathwayModel.getElementIds());
readPathwayInfo(pathwayModel, root); // comment group and evidenceRefs
readGroups(pathwayModel, root); // TODO read group first
readLabels(pathwayModel, root);
readShapes(pathwayModel, root);
readDataNodes(pathwayModel, root); // TODO will elementRef (refers to only Group?)
readInteractions(pathwayModel, root);
readGraphicalLines(pathwayModel, root);
// Read ElementRefs last
readDataNodeElementRef(pathwayModel, root); // TODO reads points last due to possible reference to anchor
readPointElementRef(pathwayModel, root); // TODO reads points last due to possible reference to anchor
Logger.log.trace("End reading gpml");
return pathwayModel;
// TODO check groups have at least one pathwayElement inside?
// TODO check at least 2 points per line element?
// TODO handle relative and absolute coordinates
// return pathwayModel;
}
/*------------------------------------MY METHODS --------------------------------------*/
// public void readFromRoot(Element root, PathwayModel pathwayModel) throws ConverterException {
// // TODO Auto-generated method stub
//
// }
protected Pathway readPathway(Element root) throws ConverterException {
String title = root.getAttributeValue("title");
Element gfx = root.getChild("Graphics", root.getNamespace());
double boardWidth = Double.parseDouble(gfx.getAttributeValue("boardWidth"));
double boardHeight = Double.parseDouble(gfx.getAttributeValue("boardHeight"));
Color backgroundColor = ColorUtils.stringToColor(gfx.getAttributeValue("backgroundColor")); // TODO optional?
Coordinate infoBox = readInfoBox(root);
Pathway pathway = new Pathway.PathwayBuilder(title, boardWidth, boardHeight, backgroundColor, infoBox).build();
/* optional properties */
Xref xref = readXref(root);
String organism = root.getAttributeValue("organism");
String source = root.getAttributeValue("source");
String version = root.getAttributeValue("version");
String license = root.getAttributeValue("license");
if (xref != null)
pathway.setXref(xref);
if (organism != null)
pathway.setOrganism(organism);
if (source != null)
pathway.setSource(source);
if (version != null)
pathway.setVersion(version);
if (license != null)
pathway.setLicense(license);
return pathway;
}
protected Xref readXref(Element e) throws ConverterException {
Element xref = e.getChild("Xref", e.getNamespace());
if (xref != null) {
String identifier = xref.getAttributeValue("identifier");
String dataSource = xref.getAttributeValue("dataSource");
if (DataSource.fullNameExists(dataSource)) {
return new Xref(identifier, DataSource.getExistingByFullName(dataSource));
} else if (DataSource.systemCodeExists(dataSource)) {
return new Xref(identifier, DataSource.getByAlias(dataSource));
} else {
System.out.println("Invalid xref dataSource: " + dataSource);
return null; // TODO how to handle better
// throw new IllegalArgumentException("Invalid xref dataSource: " + dataSource);
}
}
return null;
}
protected Coordinate readInfoBox(Element root) {
Element ifbx = root.getChild("InfoBox", root.getNamespace());
double centerX = Double.parseDouble(ifbx.getAttributeValue("centerX"));
double centerY = Double.parseDouble(ifbx.getAttributeValue("centerY"));
return new Coordinate(centerX, centerY);
}
protected void readAuthors(PathwayModel pathwayModel, Element root) throws ConverterException {
Element aus = root.getChild("Authors", root.getNamespace());
if (aus != null) {
for (Element au : aus.getChildren("Author", aus.getNamespace())) {
String name = au.getAttributeValue("name");
String fullName = au.getAttributeValue("fullName");
String email = au.getAttributeValue("email");
Author author = new Author.AuthorBuilder(name).build();
if (fullName != null)
author.setFullName(fullName);
if (email != null)
author.setEmail(email);
if (author != null)
pathwayModel.addAuthor(author);
}
}
}
protected void readAnnotations(PathwayModel pathwayModel, Element root) throws ConverterException {
Element annts = root.getChild("Annotations", root.getNamespace());
if (annts != null) {
for (Element annt : annts.getChildren("Annotation", annts.getNamespace())) {
String elementId = annt.getAttributeValue("elementId");
String value = annt.getAttributeValue("value");
AnnotationType type = AnnotationType.register(annt.getAttributeValue("type"));
Annotation annotation = new Annotation(elementId, pathwayModel, value, type);
/* optional properties */
Xref xref = readXref(annt);
String url = annt.getAttributeValue("url");
if (xref != null)
annotation.setXref(xref);
if (url != null)
annotation.setUrl(url);
if (annotation != null)
pathwayModel.addAnnotation(annotation);
}
}
}
protected void readCitations(PathwayModel pathwayModel, Element root) throws ConverterException {
Element cits = root.getChild("Citations", root.getNamespace());
if (cits != null) {
for (Element cit : cits.getChildren("Citation", cits.getNamespace())) {
String elementId = cit.getAttributeValue("elementId");
Xref xref = readXref(cit);
Citation citation = new Citation(elementId, pathwayModel, xref);
/* optional properties */
String url = cit.getAttributeValue("url");
if (url != null)
citation.setUrl(url);
if (citation != null)
pathwayModel.addCitation(citation);
}
}
}
protected void readEvidences(PathwayModel pathwayModel, Element root) throws ConverterException {
Element evids = root.getChild("Evidences", root.getNamespace());
if (evids != null) {
for (Element evid : evids.getChildren("Evidence", evids.getNamespace())) {
String elementId = evid.getAttributeValue("elementId");
Xref xref = readXref(evid);
Evidence evidence = new Evidence(elementId, pathwayModel, xref);
/* optional properties */
String value = evid.getAttributeValue("value");
String url = evid.getAttributeValue("url");
if (value != null)
evidence.setValue(value);
if (url != null)
evidence.setUrl(url);
if (evidence != null)
pathwayModel.addEvidence(evidence);
}
}
}
protected void readPathwayInfo(PathwayModel pathwayModel, Element root) throws ConverterException {
readPathwayComments(pathwayModel, root);
readPathwayDynamicProperties(pathwayModel, root);
readPathwayAnnotationRefs(pathwayModel, root);
readPathwayCitationRefs(pathwayModel, root);
readPathwayEvidenceRefs(pathwayModel, root);
}
protected void readPathwayComments(PathwayModel pathwayModel, Element root) throws ConverterException {
for (Element cmt : root.getChildren("Comment", root.getNamespace())) {
String source = cmt.getAttributeValue("Source");
String content = cmt.getText();
if (content != null && !content.equals("")) {
Comment comment = new Comment(content); // TODO needs parent pathwayModel?
if (source != null && !source.equals(""))
comment.setSource(source);
pathwayModel.getPathway().addComment(new Comment(source, content));
}
}
}
protected void readPathwayDynamicProperties(PathwayModel pathwayModel, Element root) throws ConverterException {
for (Element dp : root.getChildren("Property", root.getNamespace())) {
String key = dp.getAttributeValue("key");
String value = dp.getAttributeValue("value");
pathwayModel.getPathway().setDynamicProperty(key, value);
}
}
protected void readPathwayAnnotationRefs(PathwayModel pathwayModel, Element root) throws ConverterException {
for (Element anntRef : root.getChildren("AnnotationRef", root.getNamespace())) {
Annotation annotation = (Annotation) pathwayModel
.getPathwayElement(anntRef.getAttributeValue("elementRef"));
AnnotationRef annotationRef = new AnnotationRef(annotation);
for (Element citRef : anntRef.getChildren("CitationRef", anntRef.getNamespace())) {
Citation citationRef = (Citation) pathwayModel
.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null)
annotationRef.addCitationRef(citationRef);
}
for (Element evidRef : anntRef.getChildren("EvidenceRef", anntRef.getNamespace())) {
Evidence evidenceRef = (Evidence) pathwayModel
.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
annotationRef.addEvidenceRef(evidenceRef);
}
pathwayModel.getPathway().addAnnotationRef(annotationRef);
}
}
protected void readPathwayCitationRefs(PathwayModel pathwayModel, Element e) throws ConverterException {
for (Element citRef : e.getChildren("CitationRef", e.getNamespace())) {
Citation citationRef = (Citation) pathwayModel.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null)
pathwayModel.getPathway().addCitationRef(citationRef);
}
}
protected void readPathwayEvidenceRefs(PathwayModel pathwayModel, Element e) throws ConverterException {
for (Element evidRef : e.getChildren("EvidenceRef", e.getNamespace())) {
Evidence evidenceRef = (Evidence) pathwayModel.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
pathwayModel.getPathway().addEvidenceRef(evidenceRef);
}
}
protected void readGroups(PathwayModel pathwayModel, Element root) throws ConverterException {
Element grps = root.getChild("Groups", root.getNamespace());
if (grps != null) {
for (Element grp : grps.getChildren("Group", grps.getNamespace())) {
String elementId = grp.getAttributeValue("elementId");
GroupType type = GroupType.register(grp.getAttributeValue("type"));
Element gfx = grp.getChild("Graphics", grp.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
Group group = new Group(elementId, pathwayModel, rectProperty, fontProperty, shapeStyleProperty, type);
/* read comment group, evidenceRefs */
readElementInfo(group, grp);
/* set optional properties */
String textLabel = grp.getAttributeValue("textLabel");
Xref xref = readXref(grp);
if (xref != null)
group.setXref(xref);
if (textLabel != null)
group.setTextLabel(textLabel);
if (group != null)
pathwayModel.addGroup(group);
}
/**
* Because a group may refer to another group not yet initialized. We read all
* group elements before setting groupRef.
*/
for (Element grp : grps.getChildren("Group", grps.getNamespace())) {
String groupRef = grp.getAttributeValue("groupRef");
if (groupRef != null && !groupRef.equals("")) {
String elementId = grp.getAttributeValue("elementId");
Group group = (Group) pathwayModel.getPathwayElement(elementId);
group.setGroupRef((Group) group.getPathwayModel().getPathwayElement(groupRef));
}
}
}
}
protected void readLabels(PathwayModel pathwayModel, Element root) throws ConverterException {
Element lbs = root.getChild("Labels", root.getNamespace());
if (lbs != null) {
for (Element lb : lbs.getChildren("Label", lbs.getNamespace())) {
String elementId = lb.getAttributeValue("elementId");
String textLabel = lb.getAttributeValue("textLabel");
Element gfx = lb.getChild("Graphics", lb.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
Label label = new Label(elementId, pathwayModel, rectProperty, fontProperty, shapeStyleProperty,
textLabel);
/* read comment group, evidenceRefs */
readElementInfo(label, lb);
/* set optional properties */
String href = lb.getAttributeValue("href");
String groupRef = lb.getAttributeValue("groupRef");
if (href != null)
label.setHref(href);
if (groupRef != null && !groupRef.equals(""))
label.setGroupRef((Group) label.getPathwayModel().getPathwayElement(groupRef));
if (label != null)
pathwayModel.addLabel(label);
}
}
}
protected void readShapes(PathwayModel pathwayModel, Element root) throws ConverterException {
Element shps = root.getChild("Shapes", root.getNamespace());
if (shps != null) {
for (Element shp : shps.getChildren("Shape", shps.getNamespace())) {
String elementId = shp.getAttributeValue("elementId");
Element gfx = shp.getChild("Graphics", shp.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
double rotation = Double.parseDouble(gfx.getAttributeValue("rotation"));
Shape shape = new Shape(elementId, pathwayModel, rectProperty, fontProperty, shapeStyleProperty,
rotation);
/* read comment group, evidenceRefs */
readElementInfo(shape, shp);
/* set optional properties */
String textLabel = shp.getAttributeValue("textLabel");
String groupRef = shp.getAttributeValue("groupRef");
if (textLabel != null)
shape.setTextLabel(textLabel);
if (groupRef != null && !groupRef.equals(""))
shape.setGroupRef((Group) shape.getPathwayModel().getPathwayElement(groupRef));
if (shape != null)
pathwayModel.addShape(shape);
}
}
}
protected void readDataNodes(PathwayModel pathwayModel, Element root) throws ConverterException {
Element dns = root.getChild("DataNodes", root.getNamespace());
if (dns != null) {
for (Element dn : dns.getChildren("DataNode", dns.getNamespace())) {
String elementId = dn.getAttributeValue("elementId");
Element gfx = dn.getChild("Graphics", dn.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
String textLabel = dn.getAttributeValue("textLabel");
DataNodeType type = DataNodeType.register(dn.getAttributeValue("type"));
Xref xref = readXref(dn);
DataNode dataNode = new DataNode(elementId, pathwayModel, rectProperty, fontProperty,
shapeStyleProperty, textLabel, type, xref);
/* read comment group, evidenceRefs */
readElementInfo(dataNode, dn);
/* read states */
readStates(dataNode, dn);
/* set optional properties */
String groupRef = dn.getAttributeValue("groupRef");
String elementRef = dn.getAttributeValue("elementRef");
if (groupRef != null && !groupRef.equals(""))
dataNode.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
if (elementRef != null && !elementRef.equals(""))
dataNode.setElementRef(pathwayModel.getPathwayElement(elementRef));
if (dataNode != null)
pathwayModel.addDataNode(dataNode);
}
}
}
/**
* TODO should absolute x and y be optional?
*/
protected void readStates(DataNode dataNode, Element dn) throws ConverterException {
Element sts = dn.getChild("States", dn.getNamespace());
if (sts != null) {
for (Element st : sts.getChildren("State", sts.getNamespace())) {
String elementId = st.getAttributeValue("elementId");
String textLabel = st.getAttributeValue("textLabel");
StateType type = StateType.register(st.getAttributeValue("type"));
Element gfx = st.getChild("Graphics", st.getNamespace());
double relX = Double.parseDouble(gfx.getAttributeValue("relX"));
double relY = Double.parseDouble(gfx.getAttributeValue("relY"));
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
State state = new State(elementId, dataNode.getPathwayModel(), dataNode, textLabel, type, relX, relY,
rectProperty, fontProperty, shapeStyleProperty);
/* read comment group, evidenceRefs */
readElementInfo(dataNode, st);
/* set optional properties */
Xref xref = readXref(st);
if (xref != null)
state.setXref(xref);
if (state != null)
dataNode.addState(state);
}
}
}
protected void readGraphicalLines(PathwayModel pathwayModel, Element root) throws ConverterException {
Element glns = root.getChild("GraphicaLines", root.getNamespace());
if (glns != null) {
for (Element gln : glns.getChildren("GraphicaLine", glns.getNamespace())) {
String elementId = gln.getAttributeValue("elementId");
Element gfx = gln.getChild("Graphics", gln.getNamespace());
LineStyleProperty lineStyleProperty = readLineStyleProperty(gfx);
GraphicalLine graphicalLine = new GraphicalLine(elementId, pathwayModel, lineStyleProperty);
readLineElement(graphicalLine, gln);
if (graphicalLine != null)
if (graphicalLine.getPoints().size() < 2) {
System.out.println("GraphicalLine elementId:" + elementId + "has"
+ graphicalLine.getPoints().size() + " points, must have at least 2 points");// TODO //
// error!
}
pathwayModel.addGraphicalLine(graphicalLine);
}
}
}
protected void readLineElement(LineElement lineElement, Element ln) throws ConverterException {
readElementInfo(lineElement, ln); // comment group and evidence Ref
Element wyps = ln.getChild("Waypoints", ln.getNamespace());
readPoints(lineElement, wyps);
readAnchors(lineElement, wyps);
/* set optional properties */
String groupRef = ln.getAttributeValue("groupRef");
if (groupRef != null && !groupRef.equals(""))
lineElement.setGroupRef((Group) lineElement.getPathwayModel().getPathwayElement(groupRef));
}
protected void readInteractions(PathwayModel pathwayModel, Element root) throws ConverterException {
Element ias = root.getChild("Interactions", root.getNamespace());
if (ias != null) {
for (Element ia : ias.getChildren("Interaction", ias.getNamespace())) {
String elementId = ia.getAttributeValue("elementId");
Element gfx = ia.getChild("Graphics", ia.getNamespace());
LineStyleProperty lineStyleProperty = readLineStyleProperty(gfx);
Xref xref = readXref(ia);
Interaction interaction = new Interaction(elementId, pathwayModel, lineStyleProperty, xref);
/* read comment group, evidenceRefs */
readLineElement(interaction, ia);
if (interaction != null) {
if (interaction.getPoints().size() < 2) {
System.out.println("Interaction elementId:" + elementId + "has" + interaction.getPoints().size()
+ " points, must have at least 2 points");// TODO error!
}
pathwayModel.addInteraction(interaction);
}
}
}
}
protected void readAnchors(LineElement lineElement, Element wyps) throws ConverterException {
for (Element an : wyps.getChildren("Anchor", wyps.getNamespace())) {
String elementId = an.getAttributeValue("elementId");
double position = Double.parseDouble(an.getAttributeValue("position"));
Coordinate xy = new Coordinate(Double.parseDouble(an.getAttributeValue("x")),
Double.parseDouble(an.getAttributeValue("y")));
AnchorType shapeType = AnchorType.register(an.getAttributeValue("shapeType"));
Anchor anchor = new Anchor(elementId, lineElement.getPathwayModel(), position, xy, shapeType);
if (anchor != null)
lineElement.addAnchor(anchor);
}
}
protected void readPoints(LineElement lineElement, Element wyps) throws ConverterException {
for (Element pt : wyps.getChildren("Point", wyps.getNamespace())) {
String elementId = pt.getAttributeValue("elementId");
ArrowHeadType arrowHead = ArrowHeadType.register(pt.getAttributeValue("elementId"));
Coordinate xy = new Coordinate(Double.parseDouble(pt.getAttributeValue("x")),
Double.parseDouble(pt.getAttributeValue("y")));
Point point = new Point(elementId, lineElement.getPathwayModel(), arrowHead, xy);
if (point != null) // set elementRef and optional properties later
lineElement.addPoint(point);
}
}
private void readElementInfo(ElementInfo elementInfo, Element e) throws ConverterException {
readComments(elementInfo, e);
readDynamicProperties(elementInfo, e);
readAnnotationRefs(elementInfo, e);
readCitationRefs(elementInfo, e);
readEvidenceRefs(elementInfo, e);
}
protected void readComments(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element cmt : e.getChildren("Comment", e.getNamespace())) {
String source = cmt.getAttributeValue("Source");
String content = cmt.getText();
if (content != null && !content.equals("")) {
Comment comment = new Comment(content); // TODO needs parent pathwayModel?
if (source != null && !source.equals(""))
comment.setSource(source);
elementInfo.addComment(new Comment(source, content));
}
}
}
protected void readDynamicProperties(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element dp : e.getChildren("Property", e.getNamespace())) {
String key = dp.getAttributeValue("key");
String value = dp.getAttributeValue("value");
elementInfo.setDynamicProperty(key, value);
}
}
protected void readAnnotationRefs(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element anntRef : e.getChildren("AnnotationRef", e.getNamespace())) {
Annotation annotation = (Annotation) elementInfo.getPathwayModel()
.getPathwayElement(anntRef.getAttributeValue("elementRef"));
AnnotationRef annotationRef = new AnnotationRef(annotation);
for (Element citRef : anntRef.getChildren("CitationRef", anntRef.getNamespace())) {
Citation citationRef = (Citation) elementInfo.getPathwayModel()
.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null)
annotationRef.addCitationRef(citationRef);
}
for (Element evidRef : anntRef.getChildren("EvidenceRef", anntRef.getNamespace())) {
Evidence evidenceRef = (Evidence) elementInfo.getPathwayModel()
.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
annotationRef.addEvidenceRef(evidenceRef);
}
elementInfo.addAnnotationRef(annotationRef);
}
}
protected void readCitationRefs(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element citRef : e.getChildren("CitationRef", e.getNamespace())) {
Citation citationRef = (Citation) elementInfo.getPathwayModel()
.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null) {
elementInfo.addCitationRef(citationRef);
}
}
}
protected void readEvidenceRefs(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element evidRef : e.getChildren("EvidenceRef", e.getNamespace())) {
Evidence evidenceRef = (Evidence) elementInfo.getPathwayModel()
.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
elementInfo.addEvidenceRef(evidenceRef);
}
}
/**
* Reads gpml RectAttributes from Graphics element and returns RectProperty.
* Default schema values are automatically handled by jdom
*/
protected RectProperty readRectProperty(Element gfx) throws ConverterException {
double centerX = Double.parseDouble(gfx.getAttributeValue("centerX"));
double centerY = Double.parseDouble(gfx.getAttributeValue("centerY"));
double width = Double.parseDouble(gfx.getAttributeValue("width"));
double height = Double.parseDouble(gfx.getAttributeValue("height"));
return new RectProperty(new Coordinate(centerX, centerY), width, height);
}
/**
* Reads gpml FontAttributes from Graphics element and returns FontProperty.
* Default schema values are automatically handled by jdom
*/
protected FontProperty readFontProperty(Element gfx) throws ConverterException {
Color textColor = ColorUtils.stringToColor(gfx.getAttributeValue("textColor"));
String fontName = gfx.getAttributeValue("fontName");
boolean fontWeight = gfx.getAttributeValue("fontWeight").equals("Bold");
boolean fontStyle = gfx.getAttributeValue("fontStyle").equals("Italic");
boolean fontDecoration = gfx.getAttributeValue("fontDecoration").equals("Underline");
boolean fontStrikethru = gfx.getAttributeValue("fontStrikethru").equals("Strikethru");
int fontSize = Integer.parseInt(gfx.getAttributeValue("fontSize"));
HAlignType hAlignType = HAlignType.fromName(gfx.getAttributeValue("hAlign"));
VAlignType vAlignType = VAlignType.fromName(gfx.getAttributeValue("vAlign"));
return new FontProperty(textColor, fontName, fontWeight, fontStyle, fontDecoration, fontStrikethru, fontSize,
hAlignType, vAlignType);
}
/**
* Reads gpml ShapeStyleAttributes from Graphics element and returns
* ShapeStyleProperty. Default schema values are automatically handled by jdom
*/
protected ShapeStyleProperty readShapeStyleProperty(Element gfx) throws ConverterException {
Color borderColor = ColorUtils.stringToColor(gfx.getAttributeValue("borderColor"));
LineStyleType borderStyle = LineStyleType.register(gfx.getAttributeValue("borderStyle"));
double borderWidth = Double.parseDouble(gfx.getAttributeValue("borderWidth"));
Color fillColor = ColorUtils.stringToColor(gfx.getAttributeValue("fillColor"));
ShapeType shapeType = ShapeType.register(gfx.getAttributeValue("shapeType"));
String zOrder = gfx.getAttributeValue("zOrder");
ShapeStyleProperty shapeStyleProperty = new ShapeStyleProperty(borderColor, borderStyle, borderWidth, fillColor,
shapeType);
if (zOrder != null) {
shapeStyleProperty.setZOrder(Integer.parseInt(zOrder));
}
return shapeStyleProperty;
}
/**
* Reads gpml LineStyleAttributes from Graphics element and returns
* LineStyleProperty. Default schema values are automatically handled by jdom
*/
protected LineStyleProperty readLineStyleProperty(Element gfx) throws ConverterException {
Color lineColor = ColorUtils.stringToColor(gfx.getAttributeValue("lineColor"));
LineStyleType lineStyle = LineStyleType.register(gfx.getAttributeValue("lineStyle"));
double lineWidth = Double.parseDouble(gfx.getAttributeValue("lineWidth"));
ConnectorType connectorType = ConnectorType.register(gfx.getAttributeValue("connectorType"));
String zOrder = gfx.getAttributeValue("zOrder");
LineStyleProperty lineStyleProperty = new LineStyleProperty(lineColor, lineStyle, lineWidth, connectorType);
if (zOrder != null) {
lineStyleProperty.setZOrder(Integer.parseInt(zOrder));
}
return lineStyleProperty;
}
/*---------------------------------------------------------------------------*/
protected void readPointElementRef(PathwayModel pathwayModel, Element root) throws ConverterException {
List<String> lnElementNames = Collections.unmodifiableList(Arrays.asList("Interactions", "GraphicalLines"));
List<String> lnElementName = Collections.unmodifiableList(Arrays.asList("Interaction", "GraphicalLine"));
for (int i = 0; i < lnElementNames.size(); i++) {
Element ias = root.getChild(lnElementNames.get(i), root.getNamespace());
if (ias != null) {
for (Element ia : ias.getChildren(lnElementName.get(i), ias.getNamespace())) {
Element wyps = ia.getChild("Waypoints", ia.getNamespace());
for (Element pt : wyps.getChildren("Point", wyps.getNamespace())) {
String elementRef = pt.getAttributeValue("elementRef");
if (elementRef != null && !elementRef.equals("")) {
PathwayElement elemRf = pathwayModel.getPathwayElement(elementRef);
if (elemRf != null) {
String elementId = pt.getAttributeValue("elementId");
Point point = (Point) pathwayModel.getPathwayElement(elementId);
point.setElementRef(elemRf);
point.setRelX(Double.parseDouble(pt.getAttributeValue("relX")));
point.setRelY(Double.parseDouble(pt.getAttributeValue("relY")));
}
}
}
}
}
}
}
protected void readDataNodeElementRef(PathwayModel pathwayModel, Element root) throws ConverterException {
Element dns = root.getChild("DataNodes", root.getNamespace());
for (Element dn : dns.getChildren("DataNode", dns.getNamespace())) {
String elementRef = dn.getAttributeValue("elementRef");
if (elementRef != null && !elementRef.equals("")) {
PathwayElement elemRf = pathwayModel.getPathwayElement(elementRef);
if (elemRf != null) {
String elementId = dn.getAttributeValue("elementId");
DataNode dataNode = (DataNode) pathwayModel.getPathwayElement(elementId);
dataNode.setElementRef(elemRf);
}
}
}
}
// TODO PROBLEM CASTING?
// protected void readGroupRefs(PathwayModel pathwayModel, Element root) {
// List<String> shpElements = Collections
// .unmodifiableList(Arrays.asList("DataNodes", "Labels", "Shapes", "Groups"));
// List<String> shpElement = Collections.unmodifiableList(Arrays.asList("DataNode", "Label", "Shape", "Group"));
// for (int i = 0; i < shpElements.size(); i++) {
// Element grps = root.getChild(shpElements.get(i), root.getNamespace());
// for (Element grp : grps.getChildren(shpElement.get(i), grps.getNamespace())) {
// String groupRef = grp.getAttributeValue("groupRef");
// if (groupRef != null && !groupRef.equals("")) {
// String elementId = grp.getAttributeValue("elementId");
// ShapedElement shapedElement = (ShapedElement) pathwayModel.getPathwayElement(elementId);
// shapedElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
// }
// }
// }
// List<String> lnElements = Collections.unmodifiableList(Arrays.asList("Interactions", "GraphicalLines"));
// List<String> lnElement = Collections.unmodifiableList(Arrays.asList("Interaction", "GraphicalLine"));
// for (int i = 0; i < shpElements.size(); i++) {
// Element grps = root.getChild(lnElements.get(i), root.getNamespace());
// for (Element grp : grps.getChildren(lnElement.get(i), grps.getNamespace())) {
// String groupRef = grp.getAttributeValue("groupRef");
// if (groupRef != null && !groupRef.equals("")) {
// String elementId = grp.getAttributeValue("elementId");
// LineElement lineElement = (LineElement) pathwayModel.getPathwayElement(elementId);
// lineElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
// }
// }
// }
// }
}
| org.pathvisio.lib/src/main/java/org/pathvisio/io/GPML2021Reader.java | /*******************************************************************************
* PathVisio, a tool for data visualization and analysis using biological pathways
* Copyright 2006-2021 BiGCaT Bioinformatics, WikiPathways
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.pathvisio.io;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.io.ByteArrayInputStream;
import org.bridgedb.DataSource;
import org.bridgedb.Xref;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaderJDOMFactory;
import org.jdom2.input.sax.XMLReaderXSDFactory;
import org.pathvisio.debug.Logger;
import org.pathvisio.io.*;
import org.pathvisio.model.*;
import org.pathvisio.model.graphics.*;
import org.pathvisio.model.elements.*;
import org.pathvisio.model.type.*;
public class GPML2021Reader extends GpmlFormatAbstract implements GpmlFormatReader {
public static final GPML2021Reader GPML2021READER = new GPML2021Reader("GPML2021.xsd",
Namespace.getNamespace("http://pathvisio.org/GPML/2021"));
protected GPML2021Reader(String xsdFile, Namespace nsGPML) {
super(xsdFile, nsGPML);
}
/*------------------------------------MY METHODS --------------------------------------*/
//
// public PathwayModel readFromXml(InputStream is) throws ConverterException {
// PathwayModel pathwayModel = null;
// try {
// XMLReaderJDOMFactory schemafactory = new XMLReaderXSDFactory(xsdFile); // schema
// SAXBuilder builder = new SAXBuilder(schemafactory);
// Document doc = builder.build(is);
// Element root = doc.getRootElement();
// System.out.println("Root: " + doc.getRootElement());
// pathwayModel = readFromRoot(pathwayModel, root);
// } catch (JDOMException e) {
// throw new ConverterException(e);
// } catch (IOException e) {
// throw new ConverterException(e);
// } catch (Exception e) {
// throw new ConverterException(e); // TODO e.printStackTrace()?
// }
// return pathwayModel;// TODO do we want to return pathway or not?
// }
//
// /**
// * Read the JDOM document from the file specified
// *
// * @param file the file from which the JDOM document should be read.
// * @throws ConverterException
// */
// public PathwayModel readFromXml(File file) throws ConverterException {
// InputStream is;
// try {
// is = new FileInputStream(file);
// } catch (FileNotFoundException e) {
// throw new ConverterException(e);
// }
// return readFromXml(is);
// }
//
// /**
// * Read the JDOM document from the file specified
// *
// * @param s the string input.
// * @param string the file from which the JDOM document should be read.
// * @throws ConverterException
// */
// public PathwayModel readFromXml(String str) throws ConverterException {
// if (str == null)
// return null;
// InputStream is;
// try {
// is = stringToInputStream(str);// TODO does this work?
// } catch (Exception e) {
// throw new ConverterException(e);
// }
// return readFromXml(is);
// }
//
// // METHOD FROM UTILS
// public static InputStream stringToInputStream(String str) {
// if (str == null)
// return null;
// InputStream is = null;
// try {
// is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
// } catch (Exception ex) {
// }
// return is;
// }
public PathwayModel readFromRoot(PathwayModel pathwayModel, Element root) throws ConverterException {
Pathway pathway = readPathway(root);
System.out.println("read pathway");
pathwayModel.setPathway(pathway); // = new PathwayModel(pathway); // TODO think about order
System.out.println("set pathway");
readAuthors(pathwayModel, root);
System.out.println("read authors");
readAnnotations(pathwayModel, root);
System.out.println("read success");
readCitations(pathwayModel, root);
System.out.println("read success");
readEvidences(pathwayModel, root);
System.out.println(pathwayModel.getElementIds());
readPathwayInfo(pathwayModel, root); // comment group and evidenceRefs
readGroups(pathwayModel, root); // TODO read group first
readLabels(pathwayModel, root);
readShapes(pathwayModel, root);
readDataNodes(pathwayModel, root); // TODO will elementRef (refers to only Group?)
readInteractions(pathwayModel, root);
readGraphicalLines(pathwayModel, root);
readLinePoints(pathwayModel, root); // TODO reads points last due to possible reference to anchor
Logger.log.trace("End reading gpml");
return pathwayModel;
// TODO check groups have at least one pathwayElement inside?
// TODO check at least 2 points per line element?
// TODO handle relative and absolute coordinates
// return pathwayModel;
}
/*------------------------------------MY METHODS --------------------------------------*/
// public void readFromRoot(Element root, PathwayModel pathwayModel) throws ConverterException {
// // TODO Auto-generated method stub
//
// }
protected Pathway readPathway(Element root) throws ConverterException {
String title = root.getAttributeValue("title");
Element gfx = root.getChild("Graphics", root.getNamespace());
double boardWidth = Double.parseDouble(gfx.getAttributeValue("boardWidth"));
double boardHeight = Double.parseDouble(gfx.getAttributeValue("boardHeight"));
Color backgroundColor = ColorUtils.stringToColor(gfx.getAttributeValue("backgroundColor")); // TODO optional?
Coordinate infoBox = readInfoBox(root);
Pathway pathway = new Pathway.PathwayBuilder(title, boardWidth, boardHeight, backgroundColor, infoBox).build();
/* optional properties */
Xref xref = readXref(root);
String organism = root.getAttributeValue("organism");
String source = root.getAttributeValue("source");
String version = root.getAttributeValue("version");
String license = root.getAttributeValue("license");
if (xref != null)
pathway.setXref(xref);
if (organism != null)
pathway.setOrganism(organism);
if (source != null)
pathway.setSource(source);
if (version != null)
pathway.setVersion(version);
if (license != null)
pathway.setLicense(license);
return pathway;
}
protected Xref readXref(Element e) throws ConverterException {
Element xref = e.getChild("Xref", e.getNamespace());
if (xref != null) {
String identifier = xref.getAttributeValue("identifier");
String dataSource = xref.getAttributeValue("dataSource");
if (DataSource.fullNameExists(dataSource)) {
return new Xref(identifier, DataSource.getExistingByFullName(dataSource));
} else if (DataSource.systemCodeExists(dataSource)) {
return new Xref(identifier, DataSource.getByAlias(dataSource));
} else {
System.out.println("Invalid xref dataSource: " + dataSource);
return null; // TODO how to handle better
// throw new IllegalArgumentException("Invalid xref dataSource: " + dataSource);
}
}
return null;
}
protected Coordinate readInfoBox(Element root) {
Element ifbx = root.getChild("InfoBox", root.getNamespace());
double centerX = Double.parseDouble(ifbx.getAttributeValue("centerX"));
double centerY = Double.parseDouble(ifbx.getAttributeValue("centerY"));
return new Coordinate(centerX, centerY);
}
protected void readAuthors(PathwayModel pathwayModel, Element root) throws ConverterException {
Element aus = root.getChild("Authors", root.getNamespace());
if (aus != null) {
for (Element au : aus.getChildren("Author", aus.getNamespace())) {
String name = au.getAttributeValue("name");
String fullName = au.getAttributeValue("fullName");
String email = au.getAttributeValue("email");
Author author = new Author.AuthorBuilder(name).build();
if (fullName != null)
author.setFullName(fullName);
if (email != null)
author.setEmail(email);
if (author != null)
pathwayModel.addAuthor(author);
}
}
}
protected void readAnnotations(PathwayModel pathwayModel, Element root) throws ConverterException {
Element annts = root.getChild("Annotations", root.getNamespace());
if (annts != null) {
for (Element annt : annts.getChildren("Annotation", annts.getNamespace())) {
String elementId = annt.getAttributeValue("elementId");
String value = annt.getAttributeValue("value");
AnnotationType type = AnnotationType.register(annt.getAttributeValue("type"));
Annotation annotation = new Annotation(elementId, pathwayModel, value, type);
/* optional properties */
Xref xref = readXref(annt);
String url = annt.getAttributeValue("url");
if (xref != null)
annotation.setXref(xref);
if (url != null)
annotation.setUrl(url);
if (annotation != null)
pathwayModel.addAnnotation(annotation);
}
}
}
protected void readCitations(PathwayModel pathwayModel, Element root) throws ConverterException {
Element cits = root.getChild("Citations", root.getNamespace());
if (cits != null) {
for (Element cit : cits.getChildren("Citation", cits.getNamespace())) {
String elementId = cit.getAttributeValue("elementId");
Xref xref = readXref(cit);
Citation citation = new Citation(elementId, pathwayModel, xref);
/* optional properties */
String url = cit.getAttributeValue("url");
if (url != null)
citation.setUrl(url);
if (citation != null)
pathwayModel.addCitation(citation);
}
}
}
protected void readEvidences(PathwayModel pathwayModel, Element root) throws ConverterException {
Element evids = root.getChild("Evidences", root.getNamespace());
if (evids != null) {
for (Element evid : evids.getChildren("Evidence", evids.getNamespace())) {
String elementId = evid.getAttributeValue("elementId");
Xref xref = readXref(evid);
Evidence evidence = new Evidence(elementId, pathwayModel, xref);
/* optional properties */
String value = evid.getAttributeValue("value");
String url = evid.getAttributeValue("url");
if (value != null)
evidence.setValue(value);
if (url != null)
evidence.setUrl(url);
if (evidence != null)
pathwayModel.addEvidence(evidence);
}
}
}
protected void readPathwayInfo(PathwayModel pathwayModel, Element root) throws ConverterException {
readPathwayComments(pathwayModel, root);
readPathwayDynamicProperties(pathwayModel, root);
readPathwayAnnotationRefs(pathwayModel, root);
readPathwayCitationRefs(pathwayModel, root);
readPathwayEvidenceRefs(pathwayModel, root);
}
protected void readPathwayComments(PathwayModel pathwayModel, Element root) throws ConverterException {
for (Element cmt : root.getChildren("Comment", root.getNamespace())) {
String source = cmt.getAttributeValue("Source");
String content = cmt.getText();
if (content != null && !content.equals("")) {
Comment comment = new Comment(content); // TODO needs parent pathwayModel?
if (source != null && !source.equals(""))
comment.setSource(source);
pathwayModel.getPathway().addComment(new Comment(source, content));
}
}
}
protected void readPathwayDynamicProperties(PathwayModel pathwayModel, Element root) throws ConverterException {
for (Element dp : root.getChildren("Property", root.getNamespace())) {
String key = dp.getAttributeValue("key");
String value = dp.getAttributeValue("value");
pathwayModel.getPathway().setDynamicProperty(key, value);
}
}
protected void readPathwayAnnotationRefs(PathwayModel pathwayModel, Element root) throws ConverterException {
for (Element anntRef : root.getChildren("AnnotationRef", root.getNamespace())) {
Annotation annotation = (Annotation) pathwayModel
.getPathwayElement(anntRef.getAttributeValue("elementRef"));
AnnotationRef annotationRef = new AnnotationRef(annotation);
for (Element citRef : anntRef.getChildren("CitationRef", anntRef.getNamespace())) {
Citation citationRef = (Citation) pathwayModel
.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null)
annotationRef.addCitationRef(citationRef);
}
for (Element evidRef : anntRef.getChildren("EvidenceRef", anntRef.getNamespace())) {
Evidence evidenceRef = (Evidence) pathwayModel
.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
annotationRef.addEvidenceRef(evidenceRef);
}
pathwayModel.getPathway().addAnnotationRef(annotationRef);
}
}
protected void readPathwayCitationRefs(PathwayModel pathwayModel, Element e) throws ConverterException {
for (Element citRef : e.getChildren("CitationRef", e.getNamespace())) {
Citation citationRef = (Citation) pathwayModel.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null)
pathwayModel.getPathway().addCitationRef(citationRef);
}
}
protected void readPathwayEvidenceRefs(PathwayModel pathwayModel, Element e) throws ConverterException {
for (Element evidRef : e.getChildren("EvidenceRef", e.getNamespace())) {
Evidence evidenceRef = (Evidence) pathwayModel.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
pathwayModel.getPathway().addEvidenceRef(evidenceRef);
}
}
protected void readGroups(PathwayModel pathwayModel, Element root) throws ConverterException {
Element grps = root.getChild("Groups", root.getNamespace());
if (grps != null) {
for (Element grp : grps.getChildren("Group", grps.getNamespace())) {
String elementId = grp.getAttributeValue("elementId");
GroupType type = GroupType.register(grp.getAttributeValue("type"));
Element gfx = grp.getChild("Graphics", grp.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
Group group = new Group(elementId, pathwayModel, rectProperty, fontProperty, shapeStyleProperty, type);
/* read comment group, evidenceRefs */
readElementInfo(group, grp);
/* set optional properties */
String textLabel = grp.getAttributeValue("textLabel");
Xref xref = readXref(grp);
if (xref != null)
group.setXref(xref);
if (textLabel != null)
group.setTextLabel(textLabel);
if (group != null)
pathwayModel.addGroup(group);
}
/**
* Because a group may refer to another group not yet initialized. We read all
* group elements before setting groupRef.
*/
for (Element grp : grps.getChildren("Group", grps.getNamespace())) {
String groupRef = grp.getAttributeValue("groupRef");
if (groupRef != null && !groupRef.equals("")) {
String elementId = grp.getAttributeValue("elementId");
Group group = (Group) pathwayModel.getPathwayElement(elementId);
group.setGroupRef((Group) group.getPathwayModel().getPathwayElement(groupRef));
}
}
}
}
protected void readLabels(PathwayModel pathwayModel, Element root) throws ConverterException {
Element lbs = root.getChild("Labels", root.getNamespace());
if (lbs != null) {
for (Element lb : lbs.getChildren("Label", lbs.getNamespace())) {
String elementId = lb.getAttributeValue("elementId");
String textLabel = lb.getAttributeValue("textLabel");
Element gfx = lb.getChild("Graphics", lb.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
Label label = new Label(elementId, pathwayModel, rectProperty, fontProperty, shapeStyleProperty,
textLabel);
/* read comment group, evidenceRefs */
readElementInfo(label, lb);
/* set optional properties */
String href = lb.getAttributeValue("href");
String groupRef = lb.getAttributeValue("grouRef");
if (href != null)
label.setHref(href);
if (groupRef != null && !groupRef.equals(""))
label.setGroupRef((Group) label.getPathwayModel().getPathwayElement(groupRef));
if (label != null)
pathwayModel.addLabel(label);
}
}
}
protected void readShapes(PathwayModel pathwayModel, Element root) throws ConverterException {
Element shps = root.getChild("Shapes", root.getNamespace());
if (shps != null) {
for (Element shp : shps.getChildren("Shape", shps.getNamespace())) {
String elementId = shp.getAttributeValue("elementId");
Element gfx = shp.getChild("Graphics", shp.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
double rotation = Double.parseDouble(gfx.getAttributeValue("rotation"));
Shape shape = new Shape(elementId, pathwayModel, rectProperty, fontProperty, shapeStyleProperty,
rotation);
/* read comment group, evidenceRefs */
readElementInfo(shape, shp);
/* set optional properties */
String textLabel = shp.getAttributeValue("textLabel");
String groupRef = shp.getAttributeValue("grouRef");
if (textLabel != null)
shape.setTextLabel(textLabel);
if (groupRef != null && !groupRef.equals(""))
shape.setGroupRef((Group) shape.getPathwayModel().getPathwayElement(groupRef));
if (shape != null)
pathwayModel.addShape(shape);
}
}
}
protected void readDataNodes(PathwayModel pathwayModel, Element root) throws ConverterException {
Element dns = root.getChild("DataNodes", root.getNamespace());
if (dns != null) {
for (Element dn : dns.getChildren("DataNode", dns.getNamespace())) {
String elementId = dn.getAttributeValue("elementId");
Element gfx = dn.getChild("Graphics", dn.getNamespace());
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
String textLabel = dn.getAttributeValue("textLabel");
DataNodeType type = DataNodeType.register(dn.getAttributeValue("type"));
Xref xref = readXref(dn);
DataNode dataNode = new DataNode(elementId, pathwayModel, rectProperty, fontProperty,
shapeStyleProperty, textLabel, type, xref);
/* read comment group, evidenceRefs */
readElementInfo(dataNode, dn);
/* read states */
readStates(dataNode, dn);
/* set optional properties */
String groupRef = dn.getAttributeValue("groupRef");
String elementRef = dn.getAttributeValue("elementRef");
if (groupRef != null && !groupRef.equals(""))
dataNode.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
if (elementRef != null && !elementRef.equals(""))
dataNode.setElementRef(pathwayModel.getPathwayElement(elementRef));
if (dataNode != null)
pathwayModel.addDataNode(dataNode);
}
}
}
/**
* TODO should absolute x and y be optional?
*/
protected void readStates(DataNode dataNode, Element dn) throws ConverterException {
Element sts = dn.getChild("States", dn.getNamespace());
if (sts != null) {
for (Element st : sts.getChildren("State", sts.getNamespace())) {
String elementId = st.getAttributeValue("elementId");
String textLabel = st.getAttributeValue("textLabel");
StateType type = StateType.register(st.getAttributeValue("type"));
Element gfx = st.getChild("Graphics", st.getNamespace());
double relX = Double.parseDouble(gfx.getAttributeValue("relX"));
double relY = Double.parseDouble(gfx.getAttributeValue("relY"));
RectProperty rectProperty = readRectProperty(gfx);
FontProperty fontProperty = readFontProperty(gfx);
ShapeStyleProperty shapeStyleProperty = readShapeStyleProperty(gfx);
State state = new State(elementId, dataNode.getPathwayModel(), dataNode, textLabel, type, relX, relY,
rectProperty, fontProperty, shapeStyleProperty);
/* read comment group, evidenceRefs */
readElementInfo(dataNode, st);
/* set optional properties */
Xref xref = readXref(st);
if (xref != null)
state.setXref(xref);
if (state != null)
dataNode.addState(state);
}
}
}
protected void readGraphicalLines(PathwayModel pathwayModel, Element root) throws ConverterException {
Element glns = root.getChild("GraphicaLines", root.getNamespace());
if (glns != null) {
for (Element gln : glns.getChildren("GraphicaLine", glns.getNamespace())) {
String elementId = gln.getAttributeValue("elementId");
Element gfx = gln.getChild("Graphics", gln.getNamespace());
LineStyleProperty lineStyleProperty = readLineStyleProperty(gfx);
GraphicalLine graphicalLine = new GraphicalLine(elementId, pathwayModel, lineStyleProperty);
/* read comment group, evidenceRefs */
readElementInfo(graphicalLine, gln);
/* read anchors (NB: points are read later) */
readAnchors(graphicalLine, gln);
/* set optional properties */
String groupRef = gln.getAttributeValue("groupRef");
if (groupRef != null && !groupRef.equals(""))
graphicalLine.setGroupRef((Group) graphicalLine.getPathwayModel().getPathwayElement(groupRef));
if (graphicalLine != null)
pathwayModel.addGraphicalLine(graphicalLine);
}
}
}
protected void readInteractions(PathwayModel pathwayModel, Element root) throws ConverterException {
Element ias = root.getChild("Interactions", root.getNamespace());
if (ias != null) {
for (Element ia : ias.getChildren("Interaction", ias.getNamespace())) {
String elementId = ia.getAttributeValue("elementId");
Element gfx = ia.getChild("Graphics", ia.getNamespace());
LineStyleProperty lineStyleProperty = readLineStyleProperty(gfx);
Xref xref = readXref(ia);
Interaction interaction = new Interaction(elementId, pathwayModel, lineStyleProperty, xref);
/* read comment group, evidenceRefs */
readElementInfo(interaction, ia);
/* read anchors (NB: points are read later) */
readAnchors(interaction, ia);
/* set optional properties */
String groupRef = ia.getAttributeValue("groupRef");
if (groupRef != null && !groupRef.equals(""))
interaction.setGroupRef((Group) interaction.getPathwayModel().getPathwayElement(groupRef));
if (interaction != null)
pathwayModel.addInteraction(interaction);
}
}
}
protected void readAnchors(LineElement lineElement, Element ln) throws ConverterException {
Element wyps = ln.getChild("Waypoints", ln.getNamespace());
if (wyps != null) {
for (Element an : wyps.getChildren("Anchor", wyps.getNamespace())) {
String elementId = an.getAttributeValue("elementId");
double position = Double.parseDouble(an.getAttributeValue("position"));
Coordinate xy = new Coordinate(Double.parseDouble(an.getAttributeValue("x")),
Double.parseDouble(an.getAttributeValue("y")));
AnchorType shapeType = AnchorType.register(an.getAttributeValue("shapeType"));
Anchor anchor = new Anchor(elementId, lineElement.getPathwayModel(), position, xy, shapeType);
if (anchor != null)
lineElement.addAnchor(anchor);
}
}
}
// TODO can cast to LinedElement? to reduce duplicate code
protected void readLinePoints(PathwayModel pathwayModel, Element root) throws ConverterException {
Element ias = root.getChild("Interactions", root.getNamespace());
if (ias != null) {
for (Element ia : ias.getChildren("Interaction", ias.getNamespace())) {
String elementId = ia.getAttributeValue("elementId");
System.out.println(elementId);
Interaction interaction = (Interaction) pathwayModel.getPathwayElement(elementId);
System.out.println(interaction);
readPoints(interaction, ia);
// TODO check here
if (interaction.getPoints().size() <= 2) {
System.out.println("Interaction has" + interaction.getPoints().size()
+ " points, must have at least 2 points");// TODO error!
}
}
}
Element glns = root.getChild("GraphicaLines", root.getNamespace());
if (glns != null) {
for (Element gln : glns.getChildren("GraphicaLine", glns.getNamespace())) {
String elementId = gln.getAttributeValue("elementId");
GraphicalLine graphicalLine = (GraphicalLine) pathwayModel.getPathwayElement(elementId);
readPoints(graphicalLine, gln);
// TODO check here
if (graphicalLine.getPoints().size() <= 2) {
System.out.println("Graphical line" + graphicalLine.getPoints().size()
+ " points, must have at least 2 points");// TODO error!
}
}
}
}
protected void readPoints(LineElement lineElement, Element ln) throws ConverterException {
Element wyps = ln.getChild("Waypoints", ln.getNamespace());
if (wyps != null) {
for (Element pt : wyps.getChildren("Point", wyps.getNamespace())) {
String elementId = pt.getAttributeValue("elementId");
ArrowHeadType arrowHead = ArrowHeadType.register(pt.getAttributeValue("elementId"));
Coordinate xy = new Coordinate(Double.parseDouble(pt.getAttributeValue("x")),
Double.parseDouble(pt.getAttributeValue("y")));
Point point = new Point(elementId, lineElement.getPathwayModel(), arrowHead, xy);
/* set optional properties */
String elementRef = pt.getAttributeValue("elementRef");
double relX = Double.parseDouble(pt.getAttributeValue("relX"));
double relY = Double.parseDouble(pt.getAttributeValue("relY"));
if (elementRef != null && !elementRef.equals(""))
point.setElementRef(point.getPathwayModel().getPathwayElement(elementRef));
point.setRelX(relX);
point.setRelY(relY);
if (point != null)
lineElement.addPoint(point);
}
}
}
private void readElementInfo(ElementInfo elementInfo, Element e) throws ConverterException {
readComments(elementInfo, e);
readDynamicProperties(elementInfo, e);
readAnnotationRefs(elementInfo, e);
readCitationRefs(elementInfo, e);
readEvidenceRefs(elementInfo, e);
}
protected void readComments(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element cmt : e.getChildren("Comment", e.getNamespace())) {
String source = cmt.getAttributeValue("Source");
String content = cmt.getText();
if (content != null && !content.equals("")) {
Comment comment = new Comment(content); // TODO needs parent pathwayModel?
if (source != null && !source.equals(""))
comment.setSource(source);
elementInfo.addComment(new Comment(source, content));
}
}
}
protected void readDynamicProperties(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element dp : e.getChildren("Property", e.getNamespace())) {
String key = dp.getAttributeValue("key");
String value = dp.getAttributeValue("value");
elementInfo.setDynamicProperty(key, value);
}
}
protected void readAnnotationRefs(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element anntRef : e.getChildren("AnnotationRef", e.getNamespace())) {
Annotation annotation = (Annotation) elementInfo.getPathwayModel()
.getPathwayElement(anntRef.getAttributeValue("elementRef"));
AnnotationRef annotationRef = new AnnotationRef(annotation);
for (Element citRef : anntRef.getChildren("CitationRef", anntRef.getNamespace())) {
Citation citationRef = (Citation) elementInfo.getPathwayModel()
.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null)
annotationRef.addCitationRef(citationRef);
}
for (Element evidRef : anntRef.getChildren("EvidenceRef", anntRef.getNamespace())) {
Evidence evidenceRef = (Evidence) elementInfo.getPathwayModel()
.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
annotationRef.addEvidenceRef(evidenceRef);
}
elementInfo.addAnnotationRef(annotationRef);
}
}
protected void readCitationRefs(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element citRef : e.getChildren("CitationRef", e.getNamespace())) {
Citation citationRef = (Citation) elementInfo.getPathwayModel()
.getPathwayElement(citRef.getAttributeValue("elementRef"));
if (citationRef != null) {
elementInfo.addCitationRef(citationRef);
}
}
}
protected void readEvidenceRefs(ElementInfo elementInfo, Element e) throws ConverterException {
for (Element evidRef : e.getChildren("EvidenceRef", e.getNamespace())) {
Evidence evidenceRef = (Evidence) elementInfo.getPathwayModel()
.getPathwayElement(evidRef.getAttributeValue("elementRef"));
if (evidenceRef != null)
elementInfo.addEvidenceRef(evidenceRef);
}
}
/**
* Reads gpml RectAttributes from Graphics element and returns RectProperty.
* Default schema values are automatically handled by jdom
*/
protected RectProperty readRectProperty(Element gfx) throws ConverterException {
double centerX = Double.parseDouble(gfx.getAttributeValue("centerX"));
double centerY = Double.parseDouble(gfx.getAttributeValue("centerY"));
double width = Double.parseDouble(gfx.getAttributeValue("width"));
double height = Double.parseDouble(gfx.getAttributeValue("height"));
return new RectProperty(new Coordinate(centerX, centerY), width, height);
}
/**
* Reads gpml FontAttributes from Graphics element and returns FontProperty.
* Default schema values are automatically handled by jdom
*/
protected FontProperty readFontProperty(Element gfx) throws ConverterException {
Color textColor = ColorUtils.stringToColor(gfx.getAttributeValue("textColor"));
String fontName = gfx.getAttributeValue("fontName");
boolean fontWeight = gfx.getAttributeValue("fontWeight").equals("Bold");
boolean fontStyle = gfx.getAttributeValue("fontStyle").equals("Italic");
boolean fontDecoration = gfx.getAttributeValue("fontDecoration").equals("Underline");
boolean fontStrikethru = gfx.getAttributeValue("fontStrikethru").equals("Strikethru");
int fontSize = Integer.parseInt(gfx.getAttributeValue("fontSize"));
HAlignType hAlignType = HAlignType.fromName(gfx.getAttributeValue("hAlign"));
VAlignType vAlignType = VAlignType.fromName(gfx.getAttributeValue("vAlign"));
return new FontProperty(textColor, fontName, fontWeight, fontStyle, fontDecoration, fontStrikethru, fontSize,
hAlignType, vAlignType);
}
/**
* Reads gpml ShapeStyleAttributes from Graphics element and returns
* ShapeStyleProperty. Default schema values are automatically handled by jdom
*/
protected ShapeStyleProperty readShapeStyleProperty(Element gfx) throws ConverterException {
Color borderColor = ColorUtils.stringToColor(gfx.getAttributeValue("borderColor"));
LineStyleType borderStyle = LineStyleType.register(gfx.getAttributeValue("borderStyle"));
double borderWidth = Double.parseDouble(gfx.getAttributeValue("borderWidth"));
Color fillColor = ColorUtils.stringToColor(gfx.getAttributeValue("fillColor"));
ShapeType shapeType = ShapeType.register(gfx.getAttributeValue("shapeType"));
String zOrder = gfx.getAttributeValue("zOrder");
ShapeStyleProperty shapeStyleProperty = new ShapeStyleProperty(borderColor, borderStyle, borderWidth, fillColor,
shapeType);
if (zOrder != null) {
shapeStyleProperty.setZOrder(Integer.parseInt(zOrder));
}
return shapeStyleProperty;
}
/**
* Reads gpml LineStyleAttributes from Graphics element and returns
* LineStyleProperty. Default schema values are automatically handled by jdom
*/
protected LineStyleProperty readLineStyleProperty(Element gfx) throws ConverterException {
Color lineColor = ColorUtils.stringToColor(gfx.getAttributeValue("lineColor"));
LineStyleType lineStyle = LineStyleType.register(gfx.getAttributeValue("lineStyle"));
double lineWidth = Double.parseDouble(gfx.getAttributeValue("lineWidth"));
ConnectorType connectorType = ConnectorType.register(gfx.getAttributeValue("connectorType"));
String zOrder = gfx.getAttributeValue("zOrder");
LineStyleProperty lineStyleProperty = new LineStyleProperty(lineColor, lineStyle, lineWidth, connectorType);
if (zOrder != null) {
lineStyleProperty.setZOrder(Integer.parseInt(zOrder));
}
return lineStyleProperty;
}
/*---------------------------------------------------------------------------*/
protected void readGroupRefs(PathwayModel pathwayModel, Element root) {
List<String> shpElements = Collections
.unmodifiableList(Arrays.asList("DataNodes", "Labels", "Shapes", "Groups"));
List<String> shpElement = Collections.unmodifiableList(Arrays.asList("DataNode", "Label", "Shape", "Group"));
for (int i = 0; i < shpElements.size(); i++) {
Element grps = root.getChild(shpElements.get(i), root.getNamespace());
for (Element grp : grps.getChildren(shpElement.get(i), grps.getNamespace())) {
String groupRef = grp.getAttributeValue("groupRef");
if (groupRef != null && !groupRef.equals("")) {
String elementId = grp.getAttributeValue("elementId");
ShapedElement shapedElement = (ShapedElement) pathwayModel.getPathwayElement(elementId);
shapedElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
}
}
}
List<String> lnElements = Collections.unmodifiableList(Arrays.asList("Interactions", "GraphicalLines"));
List<String> lnElement = Collections.unmodifiableList(Arrays.asList("Interaction", "GraphicalLine"));
for (int i = 0; i < shpElements.size(); i++) {
Element grps = root.getChild(lnElements.get(i), root.getNamespace());
for (Element grp : grps.getChildren(lnElement.get(i), grps.getNamespace())) {
String groupRef = grp.getAttributeValue("groupRef");
if (groupRef != null && !groupRef.equals("")) {
String elementId = grp.getAttributeValue("elementId");
LineElement lineElement = (LineElement) pathwayModel.getPathwayElement(elementId);
lineElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
}
}
}
}
}
| Modified readElementRef methods
| org.pathvisio.lib/src/main/java/org/pathvisio/io/GPML2021Reader.java | Modified readElementRef methods | <ide><path>rg.pathvisio.lib/src/main/java/org/pathvisio/io/GPML2021Reader.java
<ide>
<ide> readInteractions(pathwayModel, root);
<ide> readGraphicalLines(pathwayModel, root);
<del> readLinePoints(pathwayModel, root); // TODO reads points last due to possible reference to anchor
<add>
<add> // Read ElementRefs last
<add> readDataNodeElementRef(pathwayModel, root); // TODO reads points last due to possible reference to anchor
<add> readPointElementRef(pathwayModel, root); // TODO reads points last due to possible reference to anchor
<ide>
<ide> Logger.log.trace("End reading gpml");
<ide>
<ide> readElementInfo(label, lb);
<ide> /* set optional properties */
<ide> String href = lb.getAttributeValue("href");
<del> String groupRef = lb.getAttributeValue("grouRef");
<add> String groupRef = lb.getAttributeValue("groupRef");
<ide> if (href != null)
<ide> label.setHref(href);
<ide> if (groupRef != null && !groupRef.equals(""))
<ide> readElementInfo(shape, shp);
<ide> /* set optional properties */
<ide> String textLabel = shp.getAttributeValue("textLabel");
<del> String groupRef = shp.getAttributeValue("grouRef");
<add> String groupRef = shp.getAttributeValue("groupRef");
<ide> if (textLabel != null)
<ide> shape.setTextLabel(textLabel);
<ide> if (groupRef != null && !groupRef.equals(""))
<ide> Element gfx = gln.getChild("Graphics", gln.getNamespace());
<ide> LineStyleProperty lineStyleProperty = readLineStyleProperty(gfx);
<ide> GraphicalLine graphicalLine = new GraphicalLine(elementId, pathwayModel, lineStyleProperty);
<del> /* read comment group, evidenceRefs */
<del> readElementInfo(graphicalLine, gln);
<del> /* read anchors (NB: points are read later) */
<del> readAnchors(graphicalLine, gln);
<del> /* set optional properties */
<del> String groupRef = gln.getAttributeValue("groupRef");
<del> if (groupRef != null && !groupRef.equals(""))
<del> graphicalLine.setGroupRef((Group) graphicalLine.getPathwayModel().getPathwayElement(groupRef));
<add> readLineElement(graphicalLine, gln);
<ide> if (graphicalLine != null)
<del> pathwayModel.addGraphicalLine(graphicalLine);
<del> }
<del> }
<add> if (graphicalLine.getPoints().size() < 2) {
<add> System.out.println("GraphicalLine elementId:" + elementId + "has"
<add> + graphicalLine.getPoints().size() + " points, must have at least 2 points");// TODO //
<add> // error!
<add> }
<add> pathwayModel.addGraphicalLine(graphicalLine);
<add> }
<add> }
<add> }
<add>
<add> protected void readLineElement(LineElement lineElement, Element ln) throws ConverterException {
<add> readElementInfo(lineElement, ln); // comment group and evidence Ref
<add> Element wyps = ln.getChild("Waypoints", ln.getNamespace());
<add> readPoints(lineElement, wyps);
<add> readAnchors(lineElement, wyps);
<add> /* set optional properties */
<add> String groupRef = ln.getAttributeValue("groupRef");
<add> if (groupRef != null && !groupRef.equals(""))
<add> lineElement.setGroupRef((Group) lineElement.getPathwayModel().getPathwayElement(groupRef));
<ide> }
<ide>
<ide> protected void readInteractions(PathwayModel pathwayModel, Element root) throws ConverterException {
<ide> Xref xref = readXref(ia);
<ide> Interaction interaction = new Interaction(elementId, pathwayModel, lineStyleProperty, xref);
<ide> /* read comment group, evidenceRefs */
<del> readElementInfo(interaction, ia);
<del> /* read anchors (NB: points are read later) */
<del> readAnchors(interaction, ia);
<del> /* set optional properties */
<del> String groupRef = ia.getAttributeValue("groupRef");
<del> if (groupRef != null && !groupRef.equals(""))
<del> interaction.setGroupRef((Group) interaction.getPathwayModel().getPathwayElement(groupRef));
<del> if (interaction != null)
<add> readLineElement(interaction, ia);
<add> if (interaction != null) {
<add> if (interaction.getPoints().size() < 2) {
<add> System.out.println("Interaction elementId:" + elementId + "has" + interaction.getPoints().size()
<add> + " points, must have at least 2 points");// TODO error!
<add> }
<ide> pathwayModel.addInteraction(interaction);
<del> }
<del> }
<del> }
<del>
<del> protected void readAnchors(LineElement lineElement, Element ln) throws ConverterException {
<del> Element wyps = ln.getChild("Waypoints", ln.getNamespace());
<del> if (wyps != null) {
<del> for (Element an : wyps.getChildren("Anchor", wyps.getNamespace())) {
<del> String elementId = an.getAttributeValue("elementId");
<del> double position = Double.parseDouble(an.getAttributeValue("position"));
<del> Coordinate xy = new Coordinate(Double.parseDouble(an.getAttributeValue("x")),
<del> Double.parseDouble(an.getAttributeValue("y")));
<del> AnchorType shapeType = AnchorType.register(an.getAttributeValue("shapeType"));
<del> Anchor anchor = new Anchor(elementId, lineElement.getPathwayModel(), position, xy, shapeType);
<del> if (anchor != null)
<del> lineElement.addAnchor(anchor);
<del> }
<del> }
<del> }
<del>
<del> // TODO can cast to LinedElement? to reduce duplicate code
<del> protected void readLinePoints(PathwayModel pathwayModel, Element root) throws ConverterException {
<del> Element ias = root.getChild("Interactions", root.getNamespace());
<del> if (ias != null) {
<del> for (Element ia : ias.getChildren("Interaction", ias.getNamespace())) {
<del> String elementId = ia.getAttributeValue("elementId");
<del> System.out.println(elementId);
<del> Interaction interaction = (Interaction) pathwayModel.getPathwayElement(elementId);
<del> System.out.println(interaction);
<del> readPoints(interaction, ia);
<del> // TODO check here
<del> if (interaction.getPoints().size() <= 2) {
<del> System.out.println("Interaction has" + interaction.getPoints().size()
<del> + " points, must have at least 2 points");// TODO error!
<ide> }
<ide> }
<ide> }
<del> Element glns = root.getChild("GraphicaLines", root.getNamespace());
<del> if (glns != null) {
<del> for (Element gln : glns.getChildren("GraphicaLine", glns.getNamespace())) {
<del> String elementId = gln.getAttributeValue("elementId");
<del> GraphicalLine graphicalLine = (GraphicalLine) pathwayModel.getPathwayElement(elementId);
<del> readPoints(graphicalLine, gln);
<del> // TODO check here
<del> if (graphicalLine.getPoints().size() <= 2) {
<del> System.out.println("Graphical line" + graphicalLine.getPoints().size()
<del> + " points, must have at least 2 points");// TODO error!
<del> }
<del> }
<del> }
<del> }
<del>
<del> protected void readPoints(LineElement lineElement, Element ln) throws ConverterException {
<del> Element wyps = ln.getChild("Waypoints", ln.getNamespace());
<del> if (wyps != null) {
<del> for (Element pt : wyps.getChildren("Point", wyps.getNamespace())) {
<del> String elementId = pt.getAttributeValue("elementId");
<del> ArrowHeadType arrowHead = ArrowHeadType.register(pt.getAttributeValue("elementId"));
<del> Coordinate xy = new Coordinate(Double.parseDouble(pt.getAttributeValue("x")),
<del> Double.parseDouble(pt.getAttributeValue("y")));
<del> Point point = new Point(elementId, lineElement.getPathwayModel(), arrowHead, xy);
<del> /* set optional properties */
<del> String elementRef = pt.getAttributeValue("elementRef");
<del> double relX = Double.parseDouble(pt.getAttributeValue("relX"));
<del> double relY = Double.parseDouble(pt.getAttributeValue("relY"));
<del> if (elementRef != null && !elementRef.equals(""))
<del> point.setElementRef(point.getPathwayModel().getPathwayElement(elementRef));
<del> point.setRelX(relX);
<del> point.setRelY(relY);
<del> if (point != null)
<del> lineElement.addPoint(point);
<del> }
<add> }
<add>
<add> protected void readAnchors(LineElement lineElement, Element wyps) throws ConverterException {
<add> for (Element an : wyps.getChildren("Anchor", wyps.getNamespace())) {
<add> String elementId = an.getAttributeValue("elementId");
<add> double position = Double.parseDouble(an.getAttributeValue("position"));
<add> Coordinate xy = new Coordinate(Double.parseDouble(an.getAttributeValue("x")),
<add> Double.parseDouble(an.getAttributeValue("y")));
<add> AnchorType shapeType = AnchorType.register(an.getAttributeValue("shapeType"));
<add> Anchor anchor = new Anchor(elementId, lineElement.getPathwayModel(), position, xy, shapeType);
<add> if (anchor != null)
<add> lineElement.addAnchor(anchor);
<add> }
<add> }
<add>
<add> protected void readPoints(LineElement lineElement, Element wyps) throws ConverterException {
<add> for (Element pt : wyps.getChildren("Point", wyps.getNamespace())) {
<add> String elementId = pt.getAttributeValue("elementId");
<add> ArrowHeadType arrowHead = ArrowHeadType.register(pt.getAttributeValue("elementId"));
<add> Coordinate xy = new Coordinate(Double.parseDouble(pt.getAttributeValue("x")),
<add> Double.parseDouble(pt.getAttributeValue("y")));
<add> Point point = new Point(elementId, lineElement.getPathwayModel(), arrowHead, xy);
<add> if (point != null) // set elementRef and optional properties later
<add> lineElement.addPoint(point);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> /*---------------------------------------------------------------------------*/
<del> protected void readGroupRefs(PathwayModel pathwayModel, Element root) {
<del> List<String> shpElements = Collections
<del> .unmodifiableList(Arrays.asList("DataNodes", "Labels", "Shapes", "Groups"));
<del> List<String> shpElement = Collections.unmodifiableList(Arrays.asList("DataNode", "Label", "Shape", "Group"));
<del> for (int i = 0; i < shpElements.size(); i++) {
<del> Element grps = root.getChild(shpElements.get(i), root.getNamespace());
<del> for (Element grp : grps.getChildren(shpElement.get(i), grps.getNamespace())) {
<del> String groupRef = grp.getAttributeValue("groupRef");
<del> if (groupRef != null && !groupRef.equals("")) {
<del> String elementId = grp.getAttributeValue("elementId");
<del> ShapedElement shapedElement = (ShapedElement) pathwayModel.getPathwayElement(elementId);
<del> shapedElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
<add>
<add> protected void readPointElementRef(PathwayModel pathwayModel, Element root) throws ConverterException {
<add> List<String> lnElementNames = Collections.unmodifiableList(Arrays.asList("Interactions", "GraphicalLines"));
<add> List<String> lnElementName = Collections.unmodifiableList(Arrays.asList("Interaction", "GraphicalLine"));
<add> for (int i = 0; i < lnElementNames.size(); i++) {
<add> Element ias = root.getChild(lnElementNames.get(i), root.getNamespace());
<add> if (ias != null) {
<add> for (Element ia : ias.getChildren(lnElementName.get(i), ias.getNamespace())) {
<add> Element wyps = ia.getChild("Waypoints", ia.getNamespace());
<add> for (Element pt : wyps.getChildren("Point", wyps.getNamespace())) {
<add> String elementRef = pt.getAttributeValue("elementRef");
<add> if (elementRef != null && !elementRef.equals("")) {
<add> PathwayElement elemRf = pathwayModel.getPathwayElement(elementRef);
<add> if (elemRf != null) {
<add> String elementId = pt.getAttributeValue("elementId");
<add> Point point = (Point) pathwayModel.getPathwayElement(elementId);
<add> point.setElementRef(elemRf);
<add> point.setRelX(Double.parseDouble(pt.getAttributeValue("relX")));
<add> point.setRelY(Double.parseDouble(pt.getAttributeValue("relY")));
<add> }
<add> }
<add> }
<ide> }
<ide> }
<ide> }
<del> List<String> lnElements = Collections.unmodifiableList(Arrays.asList("Interactions", "GraphicalLines"));
<del> List<String> lnElement = Collections.unmodifiableList(Arrays.asList("Interaction", "GraphicalLine"));
<del> for (int i = 0; i < shpElements.size(); i++) {
<del> Element grps = root.getChild(lnElements.get(i), root.getNamespace());
<del> for (Element grp : grps.getChildren(lnElement.get(i), grps.getNamespace())) {
<del> String groupRef = grp.getAttributeValue("groupRef");
<del> if (groupRef != null && !groupRef.equals("")) {
<del> String elementId = grp.getAttributeValue("elementId");
<del> LineElement lineElement = (LineElement) pathwayModel.getPathwayElement(elementId);
<del> lineElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
<add> }
<add>
<add> protected void readDataNodeElementRef(PathwayModel pathwayModel, Element root) throws ConverterException {
<add> Element dns = root.getChild("DataNodes", root.getNamespace());
<add> for (Element dn : dns.getChildren("DataNode", dns.getNamespace())) {
<add> String elementRef = dn.getAttributeValue("elementRef");
<add> if (elementRef != null && !elementRef.equals("")) {
<add> PathwayElement elemRf = pathwayModel.getPathwayElement(elementRef);
<add> if (elemRf != null) {
<add> String elementId = dn.getAttributeValue("elementId");
<add> DataNode dataNode = (DataNode) pathwayModel.getPathwayElement(elementId);
<add> dataNode.setElementRef(elemRf);
<ide> }
<ide> }
<ide> }
<ide> }
<ide>
<add> // TODO PROBLEM CASTING?
<add>// protected void readGroupRefs(PathwayModel pathwayModel, Element root) {
<add>// List<String> shpElements = Collections
<add>// .unmodifiableList(Arrays.asList("DataNodes", "Labels", "Shapes", "Groups"));
<add>// List<String> shpElement = Collections.unmodifiableList(Arrays.asList("DataNode", "Label", "Shape", "Group"));
<add>// for (int i = 0; i < shpElements.size(); i++) {
<add>// Element grps = root.getChild(shpElements.get(i), root.getNamespace());
<add>// for (Element grp : grps.getChildren(shpElement.get(i), grps.getNamespace())) {
<add>// String groupRef = grp.getAttributeValue("groupRef");
<add>// if (groupRef != null && !groupRef.equals("")) {
<add>// String elementId = grp.getAttributeValue("elementId");
<add>// ShapedElement shapedElement = (ShapedElement) pathwayModel.getPathwayElement(elementId);
<add>// shapedElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
<add>// }
<add>// }
<add>// }
<add>// List<String> lnElements = Collections.unmodifiableList(Arrays.asList("Interactions", "GraphicalLines"));
<add>// List<String> lnElement = Collections.unmodifiableList(Arrays.asList("Interaction", "GraphicalLine"));
<add>// for (int i = 0; i < shpElements.size(); i++) {
<add>// Element grps = root.getChild(lnElements.get(i), root.getNamespace());
<add>// for (Element grp : grps.getChildren(lnElement.get(i), grps.getNamespace())) {
<add>// String groupRef = grp.getAttributeValue("groupRef");
<add>// if (groupRef != null && !groupRef.equals("")) {
<add>// String elementId = grp.getAttributeValue("elementId");
<add>// LineElement lineElement = (LineElement) pathwayModel.getPathwayElement(elementId);
<add>// lineElement.setGroupRef((Group) pathwayModel.getPathwayElement(groupRef));
<add>// }
<add>// }
<add>// }
<add>// }
<add>
<ide> } |
|
Java | epl-1.0 | fa7158a4ab8af8296d03bb20ed87766d934dea99 | 0 | gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime | /*******************************************************************************
* Copyright (c) 1998, 2009 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.jpa.metamodel;
import java.util.Set;
import javax.persistence.metamodel.*;
import org.eclipse.persistence.descriptors.CMPPolicy;
import org.eclipse.persistence.descriptors.RelationalDescriptor;
import org.eclipse.persistence.internal.jpa.CMP3Policy;
import org.eclipse.persistence.mappings.DatabaseMapping;
/**
* <p>
* <b>Purpose</b>: Provides the implementation for the EntityType interface
* of the JPA 2.0 Metamodel API (part of the JSR-317 EJB 3.1 Criteria API)
* <p>
* <b>Description</b>:
*
* @see javax.persistence.metamodel.EntityType
*
* @since EclipseLink 2.0 - JPA 2.0
*
* Contributors:
* 03/19/2009-2.0 dclarke - initial API start
* 04/30/2009-2.0 mobrien - finish implementation for EclipseLink 2.0 release
* - 266912: JPA 2.0 Metamodel API (part of the JSR-317 EJB 3.1 Criteria API)
*/
public class EntityTypeImpl<X> extends ManagedTypeImpl<X> implements EntityType<X>, Bindable<X> {
//public class EntityTypeImpl<X> extends IdentifiableTypeImpl<X> implements EntityType<X>, Bindable<X> {
// TODO: getSet(String) and getSet(String, Class) need to be overridden here
protected EntityTypeImpl(MetamodelImpl metamodel, RelationalDescriptor descriptor) {
super(metamodel, descriptor);
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.Entity#getName(java.lang.Class)
*/
public String getName() {
return getDescriptor().getAlias();
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getDeclaredId(java.lang.Class)
*/
//@Override
//public <Y> Attribute<X, Y> getDeclaredId(Class<Y> type) {
public <Y> SingularAttribute<X, Y> getDeclaredId(Class<Y> type) {
// TODO Auto-generated method stub
// return the Id only if it is declared on this entity
//if(this.metamodel != null);
return null;
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getDeclaredVersion(java.lang.Class)
*/
//@Override
public <Y> SingularAttribute<X, Y> getDeclaredVersion(Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getId(java.lang.Class)
*/
//@Override
public <Y> SingularAttribute<? super X, Y> getId(Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getVersion(java.lang.Class)
*/
//@Override
public <Y> SingularAttribute<? super X, Y> getVersion(Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
public javax.persistence.metamodel.Type.PersistenceType getPersistenceType() {
return javax.persistence.metamodel.Type.PersistenceType.ENTITY;
}
public CollectionAttribute<X, ?> getDeclaredCollection(String name) {
// TODO Auto-generated method stub
return null;//(Collection<X, ?>) this.getMembers().get(name);
}
@Override
public <E> CollectionAttribute<? super X, E> getCollection(String name, Class<E> elementType) {
return getCollectionHelper(name, elementType, false);
/*
//Set aSet = this.metamodel.getEntities();
Member aMember = this.getMembers().get(name);
//java.lang.reflect.Member javaMember = aMember.getJavaMember();
javax.persistence.metamodel.Collection<? super X, E> aSet =
new CollectionAttributeImpl((ManagedTypeImpl)aMember.getDeclaringType(),
(CollectionMapping)((MemberImpl)aMember).getMapping());
return aSet;*/
}
/*
@Override
// TODO: Why is get*Collections the only function that returns a java.util.Set instead of a javax.persistence.metamodel.Set
public java.util.Set<AbstractCollection<? super X, ?, ?>> getCollections() {
// TODO Auto-generated method stub
return null;//(java.util.Set<AbstractCollection<? super X,?, ?>>) this.getMembers();
}*/
/**
* INTERNAL:
* @param <E>
* @param name
* @param elementType
* @param isDeclared
* @return
*/
private <E> CollectionAttribute<X, E> getCollectionHelper(String name, Class<E> elementType, boolean isDeclared) {
// verify existence and java element type
if(null != name && this.getMembers().containsKey(name)) {
if(this.getMembers().get(name).getJavaType() == elementType ) {
// we assume that the member is of type Collection otherwise we throw a CCE
// return the attribute parameterized by <Owning type, return Type>
Attribute member = this.getMembers().get(name);
// check whether the member is declared here or is inherited
if(isDeclared) {
// OPTION 3: rely on ManagedType.superType upward tree navigation
// superType implementation is in-progress - just return for now
return (CollectionAttribute<X,E>) member;
/*
// OPTION 2: via reflection - discarded
// check the class on the attributeAccessor - if it is different then we are !declared here
AttributeAccessor attributeAccessor = member.getMapping().getAttributeAccessor();
// We cannot rely on whether the accessor if field or method based
Field field = ((InstanceVariableAttributeAccessor)attributeAccessor).getAttributeField();
// field.clazz is not accessible
// OPTION 1: via mappedSuperclass Set - discarded
// iterate the mappedSuperclass set and check for this member
Set<MappedSuperclassTypeImpl<?>> mappedSuperclasses = ((MetamodelImpl)metamodel).getMappedSuperclasses();
DatabaseMapping memberMapping = member.getMapping();
for(Iterator<MappedSuperclassTypeImpl<?>> msIterator = mappedSuperclasses.iterator(); msIterator.hasNext();) {
MappedSuperclassTypeImpl msType = msIterator.next();
RelationalDescriptor descriptor = msType.getDescriptor();
for(Iterator<DatabaseMapping> mappingIterator = descriptor.getMappings().iterator(); mappingIterator.hasNext();) {
DatabaseMapping msMapping = mappingIterator.next();
// this test fails because the child mapping is a copy of the declared parent
// org.eclipse.persistence.mappings.DirectToFieldMapping[name-->CMP3_MM_MANUF.NAME]
// org.eclipse.persistence.mappings.DirectToFieldMapping[name-->CMP3_MM_USER.NAME]
if(msMapping == memberMapping) {
return null;
} else {
return (Collection<X,E>) member;
}
}
}*/
} else {
return (CollectionAttribute<X,E>) member;
}
} else {
throw new IllegalArgumentException("The attribute named [" + name + "] is not of the java type [" + elementType + "].");
}
} else {
throw new IllegalArgumentException("The attribute named [" + name + "] is not present in the managedType [" + this + "].");
}
}
@Override
public <E> CollectionAttribute<X, E> getDeclaredCollection(String name, Class<E> elementType) {
return getCollectionHelper(name, elementType, true);
}
/*
@Override
// TODO: Why is get*Collections the only function that returns a java.util.Set instead of a javax.persistence.metamodel.Set
public java.util.Set<AbstractCollection<X, ?, ?>> getDeclaredCollections() {
// TODO Auto-generated method stub
return (java.util.Set<AbstractCollection<X, ?, ?>>) this.getMembers();
}*/
@Override
public <E> ListAttribute<X, E> getDeclaredList(String name, Class<E> elementType) {
// TODO: What is the difference between getDeclaredList and getList
return (ListAttribute<X,E>) this.getMembers().get(name);
}
@Override
public <K, V> MapAttribute<X, K, V> getDeclaredMap(String name, Class<K> keyType, Class<V> valueType) {
// TODO: What is the difference between getDeclaredMap and getMap
// TODO: we are ignoring keyType and valueType here
return (MapAttribute<X, K, V>) this.getMembers().get(name);
}
@Override
public <E> ListAttribute<? super X, E> getList(String name, Class<E> elementType) {
// TODO: we are ignoring elementType here
return (ListAttribute<X,E>) this.getMembers().get(name);
}
public MapAttribute<? super X, ?, ?> getMap(String name) {
// TODO Auto-generated method stub
return (MapAttribute<X, ?, ?>) this.getMembers().get(name);
}
@Override
public <K, V> MapAttribute<? super X, K, V> getMap(String name, Class<K> keyType, Class<V> valueType) {
// TODO: we are ignoring keyType and valueType here
return (MapAttribute<X, K, V>) this.getMembers().get(name);
}
@Override
public javax.persistence.metamodel.SetAttribute<? super X, ?> getSet(String name) {
// TODO: we are ignoring elementType here
return (javax.persistence.metamodel.SetAttribute<? super X, ?>) this.getMembers().get(name);
}
public javax.persistence.metamodel.SetAttribute<X, ?> getDeclaredSet(String name) {
// TODO Auto-generated method stub
return (javax.persistence.metamodel.SetAttribute<X, ?>) this.getMembers().get(name);
}
@Override
public <E> javax.persistence.metamodel.SetAttribute<X, E> getSet(String name, Class<E> elementType) {
// TODO: we are ignoring elementType here
return (javax.persistence.metamodel.SetAttribute<X, E>) this.getMembers().get(name);
}
@Override
public <E> javax.persistence.metamodel.SetAttribute<X, E> getDeclaredSet(String name, Class<E> elementType) {
// TODO: What is the difference between getDeclaredMap and getMap
// TODO: we are ignoring elementType here
return (javax.persistence.metamodel.SetAttribute<X, E>) this.getMembers().get(name);
}
public boolean hasIdAttribute() {
return false;
}
public ListAttribute<X, ?> getDeclaredList(String name) {
// TODO: What is the difference between getDeclaredList and getList
return (ListAttribute<X, ?>) this.getMembers().get(name);
}
public MapAttribute<X, ?, ?> getDeclaredMap(String name) {
return (MapAttribute<X, ?, ?>) this.getMembers().get(name);
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getIdType()
*/
public Type<?> getIdType() {
// NOTE: This code is another good reason to abstract out a PKPolicy on the descriptor
// descriptor.getPrimaryKeyPolicy().getIdClass();
CMPPolicy cmpPolicy = getDescriptor().getCMPPolicy();
if (cmpPolicy == null) {
java.util.List<DatabaseMapping> pkMappings = getDescriptor().getObjectBuilder().getPrimaryKeyMappings();
if (pkMappings.size() == 1) {
@SuppressWarnings("unused")
Class aClass = pkMappings.get(0).getAttributeClassification();
// Basic Type?
return null;//new BasicImpl(aClass);
}
}
if (cmpPolicy instanceof CMP3Policy) {
// EntityType or IdentifiableType?
@SuppressWarnings("unused")
Class aClass = ((CMP3Policy) cmpPolicy).getPKClass();
return this.getSupertype();
}
// TODO: Error message for incompatible JPA config
throw new IllegalStateException("?");
}
public Attribute<X, ?> getDeclaredAttribute(String name) {
// TODO Auto-generated method stub
return (Attribute<X, ?>) this.getMembers().get(name);
}
public Set<SingularAttribute<? super X, ?>> getIdClassAttributes() {
// TODO Auto-generated method stub
return null;
}
public boolean hasSingleIdAttribute() {
// TODO Auto-generated method stub
return false;
}
public boolean hasVersionAttribute() {
// TODO Auto-generated method stub
return false;
}
public Set<PluralAttribute<? super X, ?, ?>> getCollections() {
// TODO Auto-generated method stub
return null;
}
public Set<PluralAttribute<X, ?, ?>> getDeclaredCollections() {
// TODO Auto-generated method stub
return null;
}
public <Y> SingularAttribute<X, Y> getDeclaredSingularAttribute(String name,
Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
public SingularAttribute<X, ?> getDeclaredSingularAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
public Set<SingularAttribute<X, ?>> getDeclaredSingularAttributes() {
// TODO Auto-generated method stub
return null;
}
public <Y> SingularAttribute<? super X, Y> getSingularAttribute(String name,
Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
public SingularAttribute<? super X, ?> getSingularAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
public Set<SingularAttribute<? super X, ?>> getSingularAttributes() {
// TODO Auto-generated method stub
return null;
}
public Class<X> getBindableJavaType() {
// TODO Auto-generated method stub
return null;
}
public javax.persistence.metamodel.Bindable.BindableType getBindableType() {
// TODO Auto-generated method stub
return null;
}
}
| jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/metamodel/EntityTypeImpl.java | /*******************************************************************************
* Copyright (c) 1998, 2009 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.jpa.metamodel;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Set;
import javax.persistence.metamodel.*;
import javax.persistence.metamodel.Type.PersistenceType;
import org.eclipse.persistence.descriptors.CMPPolicy;
import org.eclipse.persistence.descriptors.RelationalDescriptor;
import org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor;
import org.eclipse.persistence.internal.jpa.CMP3Policy;
import org.eclipse.persistence.mappings.AttributeAccessor;
import org.eclipse.persistence.mappings.CollectionMapping;
import org.eclipse.persistence.mappings.DatabaseMapping;
/**
* <p>
* <b>Purpose</b>: Provides the implementation for the EntityType interface
* of the JPA 2.0 Metamodel API (part of the JSR-317 EJB 3.1 Criteria API)
* <p>
* <b>Description</b>:
*
* @see javax.persistence.metamodel.EntityType
*
* @since EclipseLink 2.0 - JPA 2.0
*
* Contributors:
* 03/19/2009-2.0 dclarke - initial API start
* 04/30/2009-2.0 mobrien - finish implementation for EclipseLink 2.0 release
* - 266912: JPA 2.0 Metamodel API (part of the JSR-317 EJB 3.1 Criteria API)
*/
public class EntityTypeImpl<X> extends ManagedTypeImpl<X> implements EntityType<X>, Bindable<X> {
//public class EntityTypeImpl<X> extends IdentifiableTypeImpl<X> implements EntityType<X>, Bindable<X> {
// TODO: getSet(String) and getSet(String, Class) need to be overridden here
protected EntityTypeImpl(MetamodelImpl metamodel, RelationalDescriptor descriptor) {
super(metamodel, descriptor);
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.Entity#getName(java.lang.Class)
*/
public String getName() {
return getDescriptor().getAlias();
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getDeclaredId(java.lang.Class)
*/
//@Override
//public <Y> Attribute<X, Y> getDeclaredId(Class<Y> type) {
public <Y> SingularAttribute<X, Y> getDeclaredId(Class<Y> type) {
// TODO Auto-generated method stub
// return the Id only if it is declared on this entity
//if(this.metamodel != null);
return null;
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getDeclaredVersion(java.lang.Class)
*/
//@Override
public <Y> SingularAttribute<X, Y> getDeclaredVersion(Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getId(java.lang.Class)
*/
//@Override
public <Y> SingularAttribute<? super X, Y> getId(Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getVersion(java.lang.Class)
*/
//@Override
public <Y> SingularAttribute<? super X, Y> getVersion(Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
public javax.persistence.metamodel.Type.PersistenceType getPersistenceType() {
return javax.persistence.metamodel.Type.PersistenceType.ENTITY;
}
public CollectionAttribute<X, ?> getDeclaredCollection(String name) {
// TODO Auto-generated method stub
return null;//(Collection<X, ?>) this.getMembers().get(name);
}
@Override
public <E> CollectionAttribute<? super X, E> getCollection(String name, Class<E> elementType) {
return getCollectionHelper(name, elementType, false);
/*
//Set aSet = this.metamodel.getEntities();
Member aMember = this.getMembers().get(name);
//java.lang.reflect.Member javaMember = aMember.getJavaMember();
javax.persistence.metamodel.Collection<? super X, E> aSet =
new CollectionAttributeImpl((ManagedTypeImpl)aMember.getDeclaringType(),
(CollectionMapping)((MemberImpl)aMember).getMapping());
return aSet;*/
}
/*
@Override
// TODO: Why is get*Collections the only function that returns a java.util.Set instead of a javax.persistence.metamodel.Set
public java.util.Set<AbstractCollection<? super X, ?, ?>> getCollections() {
// TODO Auto-generated method stub
return null;//(java.util.Set<AbstractCollection<? super X,?, ?>>) this.getMembers();
}*/
/**
* INTERNAL:
* @param <E>
* @param name
* @param elementType
* @param isDeclared
* @return
*/
private <E> CollectionAttribute<X, E> getCollectionHelper(String name, Class<E> elementType, boolean isDeclared) {
// verify existence and java element type
if(null != name && this.getMembers().containsKey(name)) {
if(this.getMembers().get(name).getJavaType() == elementType ) {
// we assume that the member is of type Collection otherwise we throw a CCE
// return the attribute parameterized by <Owning type, return Type>
Attribute member = this.getMembers().get(name);
// check whether the member is declared here or is inherited
if(isDeclared) {
// OPTION 3: rely on ManagedType.superType upward tree navigation
// superType implementation is in-progress - just return for now
return (CollectionAttribute<X,E>) member;
/*
// OPTION 2: via reflection - discarded
// check the class on the attributeAccessor - if it is different then we are !declared here
AttributeAccessor attributeAccessor = member.getMapping().getAttributeAccessor();
// We cannot rely on whether the accessor if field or method based
Field field = ((InstanceVariableAttributeAccessor)attributeAccessor).getAttributeField();
// field.clazz is not accessible
// OPTION 1: via mappedSuperclass Set - discarded
// iterate the mappedSuperclass set and check for this member
Set<MappedSuperclassTypeImpl<?>> mappedSuperclasses = ((MetamodelImpl)metamodel).getMappedSuperclasses();
DatabaseMapping memberMapping = member.getMapping();
for(Iterator<MappedSuperclassTypeImpl<?>> msIterator = mappedSuperclasses.iterator(); msIterator.hasNext();) {
MappedSuperclassTypeImpl msType = msIterator.next();
RelationalDescriptor descriptor = msType.getDescriptor();
for(Iterator<DatabaseMapping> mappingIterator = descriptor.getMappings().iterator(); mappingIterator.hasNext();) {
DatabaseMapping msMapping = mappingIterator.next();
// this test fails because the child mapping is a copy of the declared parent
// org.eclipse.persistence.mappings.DirectToFieldMapping[name-->CMP3_MM_MANUF.NAME]
// org.eclipse.persistence.mappings.DirectToFieldMapping[name-->CMP3_MM_USER.NAME]
if(msMapping == memberMapping) {
return null;
} else {
return (Collection<X,E>) member;
}
}
}*/
} else {
return (CollectionAttribute<X,E>) member;
}
} else {
throw new IllegalArgumentException("The attribute named [" + name + "] is not of the java type [" + elementType + "].");
}
} else {
throw new IllegalArgumentException("The attribute named [" + name + "] is not present in the managedType [" + this + "].");
}
}
@Override
public <E> CollectionAttribute<X, E> getDeclaredCollection(String name, Class<E> elementType) {
return getCollectionHelper(name, elementType, true);
}
/*
@Override
// TODO: Why is get*Collections the only function that returns a java.util.Set instead of a javax.persistence.metamodel.Set
public java.util.Set<AbstractCollection<X, ?, ?>> getDeclaredCollections() {
// TODO Auto-generated method stub
return (java.util.Set<AbstractCollection<X, ?, ?>>) this.getMembers();
}*/
@Override
public <E> ListAttribute<X, E> getDeclaredList(String name, Class<E> elementType) {
// TODO: What is the difference between getDeclaredList and getList
return (ListAttribute<X,E>) this.getMembers().get(name);
}
@Override
public <K, V> MapAttribute<X, K, V> getDeclaredMap(String name, Class<K> keyType, Class<V> valueType) {
// TODO: What is the difference between getDeclaredMap and getMap
// TODO: we are ignoring keyType and valueType here
return (MapAttribute<X, K, V>) this.getMembers().get(name);
}
@Override
public <E> ListAttribute<? super X, E> getList(String name, Class<E> elementType) {
// TODO: we are ignoring elementType here
return (ListAttribute<X,E>) this.getMembers().get(name);
}
public MapAttribute<? super X, ?, ?> getMap(String name) {
// TODO Auto-generated method stub
return (MapAttribute<X, ?, ?>) this.getMembers().get(name);
}
@Override
public <K, V> MapAttribute<? super X, K, V> getMap(String name, Class<K> keyType, Class<V> valueType) {
// TODO: we are ignoring keyType and valueType here
return (MapAttribute<X, K, V>) this.getMembers().get(name);
}
@Override
public javax.persistence.metamodel.SetAttribute<? super X, ?> getSet(String name) {
// TODO: we are ignoring elementType here
return (javax.persistence.metamodel.SetAttribute<? super X, ?>) this.getMembers().get(name);
}
public javax.persistence.metamodel.SetAttribute<X, ?> getDeclaredSet(String name) {
// TODO Auto-generated method stub
return (javax.persistence.metamodel.SetAttribute<X, ?>) this.getMembers().get(name);
}
@Override
public <E> javax.persistence.metamodel.SetAttribute<X, E> getSet(String name, Class<E> elementType) {
// TODO: we are ignoring elementType here
return (javax.persistence.metamodel.SetAttribute<X, E>) this.getMembers().get(name);
}
@Override
public <E> javax.persistence.metamodel.SetAttribute<X, E> getDeclaredSet(String name, Class<E> elementType) {
// TODO: What is the difference between getDeclaredMap and getMap
// TODO: we are ignoring elementType here
return (javax.persistence.metamodel.SetAttribute<X, E>) this.getMembers().get(name);
}
public boolean hasIdAttribute() {
return false;
}
public ListAttribute<X, ?> getDeclaredList(String name) {
// TODO: What is the difference between getDeclaredList and getList
return (ListAttribute<X, ?>) this.getMembers().get(name);
}
public MapAttribute<X, ?, ?> getDeclaredMap(String name) {
return (MapAttribute<X, ?, ?>) this.getMembers().get(name);
}
/* (non-Javadoc)
* @see javax.persistence.metamodel.IdentifiableType#getIdType()
*/
public Type<?> getIdType() {
// NOTE: This code is another good reason to abstract out a PKPolicy on the descriptor
// descriptor.getPrimaryKeyPolicy().getIdClass();
CMPPolicy cmpPolicy = getDescriptor().getCMPPolicy();
if (cmpPolicy == null) {
java.util.List<DatabaseMapping> pkMappings = getDescriptor().getObjectBuilder().getPrimaryKeyMappings();
if (pkMappings.size() == 1) {
Class aClass = pkMappings.get(0).getAttributeClassification();
// Basic Type?
return null;//new BasicImpl(aClass);
}
}
if (cmpPolicy instanceof CMP3Policy) {
// EntityType or IdentifiableType?
Class aClass = ((CMP3Policy) cmpPolicy).getPKClass();
return this.getSupertype();
}
// TODO: Error message for incompatible JPA config
throw new IllegalStateException("?");
}
public Attribute<X, ?> getDeclaredAttribute(String name) {
// TODO Auto-generated method stub
return (Attribute<X, ?>) this.getMembers().get(name);
}
public Set<SingularAttribute<? super X, ?>> getIdClassAttributes() {
// TODO Auto-generated method stub
return null;
}
public boolean hasSingleIdAttribute() {
// TODO Auto-generated method stub
return false;
}
public boolean hasVersionAttribute() {
// TODO Auto-generated method stub
return false;
}
public Set<PluralAttribute<? super X, ?, ?>> getCollections() {
// TODO Auto-generated method stub
return null;
}
public Set<PluralAttribute<X, ?, ?>> getDeclaredCollections() {
// TODO Auto-generated method stub
return null;
}
public <Y> SingularAttribute<X, Y> getDeclaredSingularAttribute(String name,
Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
public SingularAttribute<X, ?> getDeclaredSingularAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
public Set<SingularAttribute<X, ?>> getDeclaredSingularAttributes() {
// TODO Auto-generated method stub
return null;
}
public <Y> SingularAttribute<? super X, Y> getSingularAttribute(String name,
Class<Y> type) {
// TODO Auto-generated method stub
return null;
}
public SingularAttribute<? super X, ?> getSingularAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
public Set<SingularAttribute<? super X, ?>> getSingularAttributes() {
// TODO Auto-generated method stub
return null;
}
public Class<X> getBindableJavaType() {
// TODO Auto-generated method stub
return null;
}
public javax.persistence.metamodel.Bindable.BindableType getBindableType() {
// TODO Auto-generated method stub
return null;
}
}
| trivial fix - remove unused imports
- test SVN connectivity in new Galileo environment
| jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/metamodel/EntityTypeImpl.java | trivial fix - remove unused imports - test SVN connectivity in new Galileo environment | <ide><path>pa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/metamodel/EntityTypeImpl.java
<ide> ******************************************************************************/
<ide> package org.eclipse.persistence.internal.jpa.metamodel;
<ide>
<del>import java.lang.reflect.Field;
<del>import java.util.Iterator;
<ide> import java.util.Set;
<ide>
<ide> import javax.persistence.metamodel.*;
<del>import javax.persistence.metamodel.Type.PersistenceType;
<ide>
<ide> import org.eclipse.persistence.descriptors.CMPPolicy;
<ide> import org.eclipse.persistence.descriptors.RelationalDescriptor;
<del>import org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor;
<ide> import org.eclipse.persistence.internal.jpa.CMP3Policy;
<del>import org.eclipse.persistence.mappings.AttributeAccessor;
<del>import org.eclipse.persistence.mappings.CollectionMapping;
<ide> import org.eclipse.persistence.mappings.DatabaseMapping;
<ide>
<ide> /**
<ide> java.util.List<DatabaseMapping> pkMappings = getDescriptor().getObjectBuilder().getPrimaryKeyMappings();
<ide>
<ide> if (pkMappings.size() == 1) {
<del> Class aClass = pkMappings.get(0).getAttributeClassification();
<add> @SuppressWarnings("unused")
<add> Class aClass = pkMappings.get(0).getAttributeClassification();
<ide> // Basic Type?
<ide> return null;//new BasicImpl(aClass);
<ide> }
<ide>
<ide> if (cmpPolicy instanceof CMP3Policy) {
<ide> // EntityType or IdentifiableType?
<del> Class aClass = ((CMP3Policy) cmpPolicy).getPKClass();
<add> @SuppressWarnings("unused")
<add> Class aClass = ((CMP3Policy) cmpPolicy).getPKClass();
<ide> return this.getSupertype();
<ide> }
<ide> |
|
Java | apache-2.0 | ea38016aeab137597f9f71fe9a153a4a74fab435 | 0 | jankotek/JDBM3,binarytemple/JDBM3,peter-lawrey/JDBM3,binarytemple/JDBM3 | /*******************************************************************************
* Copyright 2010 Cees De Groot, Alex Boisvert, Jan Kotek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package jdbm.btree;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import jdbm.RecordListener;
import jdbm.RecordManager;
import jdbm.Serializer;
import jdbm.helper.ComparableComparator;
import jdbm.helper.JdbmBase;
import jdbm.helper.Tuple;
import jdbm.helper.TupleBrowser;
/**
* B+Tree persistent indexing data structure. B+Trees are optimized for
* block-based, random I/O storage because they store multiple keys on
* one tree node (called <code>BPage</code>). In addition, the leaf nodes
* directly contain (inline) the values associated with the keys, allowing a
* single (or sequential) disk read of all the values on the page.
* <p>
* B+Trees are n-airy, yeilding log(N) search cost. They are self-balancing,
* preventing search performance degradation when the size of the tree grows.
* <p>
* Keys and associated values must be <code>Serializable</code> objects. The
* user is responsible to supply a serializable <code>Comparator</code> object
* to be used for the ordering of entries, which are also called <code>Tuple</code>.
* The B+Tree allows traversing the keys in forward and reverse order using a
* TupleBrowser obtained from the browse() methods.
* <p>
* This implementation does not directly support duplicate keys, but it is
* possible to handle duplicates by inlining or referencing an object collection
* as a value.
* <p>
* There is no limit on key size or value size, but it is recommended to keep
* both as small as possible to reduce disk I/O. This is especially true for
* the key size, which impacts all non-leaf <code>BPage</code> objects.
*
* @author <a href="mailto:[email protected]">Alex Boisvert</a>
* @version $Id: BTree.java,v 1.6 2005/06/25 23:12:31 doomdark Exp $
*/
public class BTree<K,V>
implements Externalizable, JdbmBase<K,V>
{
private static final long serialVersionUID = 8883213742777032628L;
private static final boolean DEBUG = false;
/**
* Default page size (number of entries per node)
*/
public static final int DEFAULT_SIZE = 32;
/**
* Page manager used to persist changes in BPages
*/
protected transient RecordManager _recman;
/**
* This BTree's record ID in the PageManager.
*/
private transient long _recid;
/**
* Comparator used to index entries.
*/
protected Comparator<K> _comparator;
/**
* Serializer used to serialize index keys (optional)
*/
protected Serializer<K> keySerializer;
/**
* Serializer used to serialize index values (optional)
*/
protected Serializer<V> valueSerializer;
public Serializer<K> getKeySerializer() {
return keySerializer;
}
public void setKeySerializer(Serializer<K> keySerializer) {
this.keySerializer = keySerializer;
}
public Serializer<V> getValueSerializer() {
return valueSerializer;
}
public void setValueSerializer(Serializer<V> valueSerializer) {
this.valueSerializer = valueSerializer;
}
/**
* Height of the B+Tree. This is the number of BPages you have to traverse
* to get to a leaf BPage, starting from the root.
*/
private int _height;
/**
* Recid of the root BPage
*/
private transient long _root;
/**
* Number of entries in each BPage.
*/
protected int _pageSize;
/**
* Total number of entries in the BTree
*/
protected volatile int _entries;
/**
* Serializer used for BPages of this tree
*/
private transient BPage<K,V> _bpageSerializer;
/**
* Listeners which are notified about changes in records
*/
protected List<RecordListener<K,V>> recordListeners = new CopyOnWriteArrayList<RecordListener<K, V>>();
protected ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* No-argument constructor used by serialization.
*/
public BTree()
{
// empty
}
/**
* Create a new persistent BTree, with 16 entries per node.
*
* @param recman Record manager used for persistence.
* @param comparator Comparator used to order index entries
*/
public static <K,V> BTree<K,V> createInstance( RecordManager recman,
Comparator<K> comparator)
throws IOException
{
return createInstance( recman, comparator, null, null, DEFAULT_SIZE );
}
/**
* Create a new persistent BTree, with 16 entries per node.
*
* @param recman Record manager used for persistence.
* @param comparator Comparator used to order index entries
*/
@SuppressWarnings("unchecked")
public static <K extends Comparable,V> BTree<K,V> createInstance( RecordManager recman)
throws IOException
{
BTree<K,V> ret = createInstance( recman, ComparableComparator.INSTANCE, null, null, DEFAULT_SIZE );
return ret;
}
/**
* Create a new persistent BTree, with 16 entries per node.
*
* @param recman Record manager used for persistence.
* @param keySerializer Serializer used to serialize index keys (optional)
* @param valueSerializer Serializer used to serialize index values (optional)
* @param comparator Comparator used to order index entries
*/
public static <K,V> BTree<K,V> createInstance( RecordManager recman,
Comparator<K> comparator,
Serializer<K> keySerializer,
Serializer<V> valueSerializer )
throws IOException
{
return createInstance( recman, comparator, keySerializer,
valueSerializer, DEFAULT_SIZE );
}
/**
* Create a new persistent BTree with the given number of entries per node.
*
* @param recman Record manager used for persistence.
* @param comparator Comparator used to order index entries
* @param keySerializer Serializer used to serialize index keys (optional)
* @param valueSerializer Serializer used to serialize index values (optional)
* @param pageSize Number of entries per page (must be even).
*/
public static <K,V> BTree<K,V> createInstance( RecordManager recman,
Comparator<K> comparator,
Serializer<K> keySerializer,
Serializer<V> valueSerializer,
int pageSize )
throws IOException
{
BTree<K,V> btree;
if ( recman == null ) {
throw new IllegalArgumentException( "Argument 'recman' is null" );
}
if ( comparator == null ) {
throw new IllegalArgumentException( "Argument 'comparator' is null" );
}
if ( ! ( comparator instanceof Serializable ) ) {
throw new IllegalArgumentException( "Argument 'comparator' must be serializable" );
}
// make sure there's an even number of entries per BPage
if ( ( pageSize & 1 ) != 0 ) {
throw new IllegalArgumentException( "Argument 'pageSize' must be even" );
}
btree = new BTree<K,V>();
btree._recman = recman;
btree._comparator = comparator;
btree.keySerializer = keySerializer;
btree.valueSerializer = valueSerializer;
btree._pageSize = pageSize;
btree._bpageSerializer = new BPage<K,V>();
btree._bpageSerializer._btree = btree;
btree._recid = recman.insert( btree );
return btree;
}
/**
* Load a persistent BTree.
*
* @param recman RecordManager used to store the persistent btree
* @param recid Record id of the BTree
*/
@SuppressWarnings("unchecked")
public static <K,V> BTree<K,V> load( RecordManager recman, long recid )
throws IOException
{
BTree<K,V> btree = (BTree<K,V>) recman.fetch( recid );
btree._recid = recid;
btree._recman = recman;
btree._bpageSerializer = new BPage<K,V>();
btree._bpageSerializer._btree = btree;
return btree;
}
/**
* Get the {@link ReadWriteLock} associated with this BTree.
* This should be used with browsing operations to ensure
* consistency.
* @return
*/
public ReadWriteLock getLock() {
return lock;
}
/**
* Insert an entry in the BTree.
* <p>
* The BTree cannot store duplicate entries. An existing entry can be
* replaced using the <code>replace</code> flag. If an entry with the
* same key already exists in the BTree, its value is returned.
*
* @param key Insert key
* @param value Insert value
* @param replace Set to true to replace an existing key-value pair.
* @return Existing value, if any.
*/
public V insert(final K key, final V value,
final boolean replace )
throws IOException
{
if ( key == null ) {
throw new IllegalArgumentException( "Argument 'key' is null" );
}
if ( value == null ) {
throw new IllegalArgumentException( "Argument 'value' is null" );
}
try {
lock.writeLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
// BTree is currently empty, create a new root BPage
if (DEBUG) {
System.out.println( "BTree.insert() new root BPage" );
}
rootPage = new BPage<K,V>( this, key, value );
_root = rootPage._recid;
_height = 1;
_entries = 1;
_recman.update( _recid, this );
//notifi listeners
for(RecordListener<K,V> l : recordListeners){
l.recordInserted(key, value);
}
return null;
} else {
BPage.InsertResult<K,V> insert = rootPage.insert( _height, key, value, replace );
boolean dirty = false;
if ( insert._overflow != null ) {
// current root page overflowed, we replace with a new root page
if ( DEBUG ) {
System.out.println( "BTree.insert() replace root BPage due to overflow" );
}
rootPage = new BPage<K,V>( this, rootPage, insert._overflow );
_root = rootPage._recid;
_height += 1;
dirty = true;
}
if ( insert._existing == null ) {
_entries++;
dirty = true;
}
if ( dirty ) {
_recman.update( _recid, this );
}
//notify listeners
for(RecordListener<K,V> l : recordListeners){
if(insert._existing==null)
l.recordInserted(key, value);
else
l.recordUpdated(key, insert._existing, value);
}
// insert might have returned an existing value
return insert._existing;
}
} finally {
lock.writeLock().unlock();
}
}
/**
* Remove an entry with the given key from the BTree.
*
* @param key Removal key
* @return Value associated with the key, or null if no entry with given
* key existed in the BTree.
*/
public V remove( K key )
throws IOException
{
if ( key == null ) {
throw new IllegalArgumentException( "Argument 'key' is null" );
}
try {
lock.writeLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return null;
}
boolean dirty = false;
BPage.RemoveResult<K,V> remove = rootPage.remove( _height, key );
if ( remove._underflow && rootPage.isEmpty() ) {
_height -= 1;
dirty = true;
_recman.delete(_root);
if ( _height == 0 ) {
_root = 0;
} else {
_root = rootPage.childBPage( _pageSize-1 )._recid;
}
}
if ( remove._value != null ) {
_entries--;
dirty = true;
}
if ( dirty ) {
_recman.update( _recid, this );
}
if(remove._value!=null)
for(RecordListener<K,V> l : recordListeners)
l.recordRemoved(key,remove._value);
return remove._value;
} finally {
lock.writeLock().unlock();
}
}
/**
* Find the value associated with the given key.
*
* @param key Lookup key.
* @return Value associated with the key, or null if not found.
*/
public V find( K key )
throws IOException
{
if ( key == null ) {
throw new IllegalArgumentException( "Argument 'key' is null" );
}
try {
lock.readLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return null;
}
return rootPage.findValue( _height, key );
} finally {
lock.readLock().unlock();
}
// Tuple<K,V> tuple = new Tuple<K,V>( null, null );
// TupleBrowser<K,V> browser = rootPage.find( _height, key );
//
// if ( browser.getNext( tuple ) ) {
// // find returns the matching key or the next ordered key, so we must
// // check if we have an exact match
// if ( _comparator.compare( key, tuple.getKey() ) != 0 ) {
// return null;
// } else {
// return tuple.getValue();
// }
// } else {
// return null;
// }
}
/**
* Find the value associated with the given key, or the entry immediately
* following this key in the ordered BTree.
*
* @param key Lookup key.
* @return Value associated with the key, or a greater entry, or null if no
* greater entry was found.
*/
public Tuple<K,V> findGreaterOrEqual( K key )
throws IOException
{
Tuple<K,V> tuple;
TupleBrowser<K,V> browser;
if ( key == null ) {
// there can't be a key greater than or equal to "null"
// because null is considered an infinite key.
return null;
}
tuple = new Tuple<K,V>( null, null );
browser = browse( key );
if ( browser.getNext( tuple ) ) {
return tuple;
} else {
return null;
}
}
/**
* Get a browser initially positioned at the beginning of the BTree.
* <p><b>
* WARNING: �If you make structural modifications to the BTree during
* browsing, you will get inconsistent browing results.
* </b>
*
* @return Browser positionned at the beginning of the BTree.
*/
@SuppressWarnings("unchecked")
public TupleBrowser<K,V> browse()
throws IOException
{
try {
lock.readLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return EmptyBrowser.INSTANCE;
}
TupleBrowser<K,V> browser = rootPage.findFirst();
return browser;
} finally {
lock.readLock().unlock();
}
}
/**
* Get a browser initially positioned just before the given key.
* <p><b>
* WARNING: �If you make structural modifications to the BTree during
* browsing, you will get inconsistent browing results.
* </b>
*
* @param key Key used to position the browser. If null, the browser
* will be positionned after the last entry of the BTree.
* (Null is considered to be an "infinite" key)
* @return Browser positionned just before the given key.
*/
@SuppressWarnings("unchecked")
public TupleBrowser<K,V> browse( K key )
throws IOException
{
try {
lock.readLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return EmptyBrowser.INSTANCE;
}
TupleBrowser<K,V> browser = rootPage.find( _height, key );
return browser;
} finally {
lock.readLock().unlock();
}
}
/**
* Return the number of entries (size) of the BTree.
*/
public int size()
{
return _entries;
}
/**
* Return the persistent record identifier of the BTree.
*/
public long getRecid()
{
return _recid;
}
/**
* Return the root BPage, or null if it doesn't exist.
*/
BPage<K,V> getRoot()
throws IOException
{
if ( _root == 0 ) {
return null;
}
BPage<K,V> root = (BPage<K,V>) _recman.fetch( _root, _bpageSerializer );
if (root != null) {
root._recid = _root;
root._btree = this;
}
return root;
}
/**
* Implement Externalizable interface.
*/
@SuppressWarnings("unchecked")
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException
{
_comparator = (Comparator<K>) in.readObject();
//serializer is not persistent from 2.0
// _keySerializer = (Serializer<K>) in.readObject();
// _valueSerializer = (Serializer<V>) in.readObject();
_height = in.readInt();
_root = in.readLong();
_pageSize = in.readInt();
_entries = in.readInt();
}
/**
* Implement Externalizable interface.
*/
public void writeExternal( ObjectOutput out )
throws IOException
{
out.writeObject( _comparator );
//serializer is not persistent from 2.0
// out.writeObject( _keySerializer );
// out.writeObject( _valueSerializer );
out.writeInt( _height );
out.writeLong( _root );
out.writeInt( _pageSize );
out.writeInt( _entries );
}
/*
public void assert() throws IOException {
BPage root = getRoot();
if ( root != null ) {
root.assertRecursive( _height );
}
}
*/
/*
public void dump() throws IOException {
BPage root = getRoot();
if ( root != null ) {
root.dumpRecursive( _height, 0 );
}
}
*/
/** PRIVATE INNER CLASS
* Browser returning no element.
*/
static class EmptyBrowser<K,V>
implements TupleBrowser<K,V> {
@SuppressWarnings("unchecked")
static TupleBrowser INSTANCE = new EmptyBrowser();
private EmptyBrowser(){}
public boolean getNext( Tuple<K,V> tuple )
{
return false;
}
public boolean getPrevious( Tuple<K,V> tuple )
{
return false;
}
}
public BTreeSortedMap<K,V> asMap(){
return new BTreeSortedMap<K, V>(this,false);
}
/**
* add RecordListener which is notified about record changes
* @param listener
*/
public void addRecordListener(RecordListener<K,V> listener){
recordListeners.add(listener);
}
/**
* remove RecordListener which is notified about record changes
* @param listener
*/
public void removeRecordListener(RecordListener<K,V> listener){
recordListeners.remove(listener);
}
public RecordManager getRecordManager() {
return _recman;
}
public Comparator<K> getComparator() {
return _comparator;
}
/**
* Deletes all BPages in this BTree, then deletes the tree from the record manager
*/
public void delete()
throws IOException
{
try {
lock.writeLock().lock();
BPage<K,V> rootPage = getRoot();
if (rootPage != null)
rootPage.delete();
_recman.delete(_recid);
} finally {
lock.writeLock().unlock();
}
}
/**
* Used for debugging and testing only. Populates the 'out' list with
* the recids of all child pages in the BTree.
* @param out
* @throws IOException
*/
void dumpChildPageRecIDs(List<Long> out) throws IOException{
BPage<K,V> root = getRoot();
if ( root != null ) {
out.add(root._recid);
root.dumpChildPageRecIDs( out, _height);
}
}
}
| src/main/jdbm/btree/BTree.java | /*******************************************************************************
* Copyright 2010 Cees De Groot, Alex Boisvert, Jan Kotek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package jdbm.btree;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import jdbm.RecordListener;
import jdbm.RecordManager;
import jdbm.Serializer;
import jdbm.helper.ComparableComparator;
import jdbm.helper.JdbmBase;
import jdbm.helper.Tuple;
import jdbm.helper.TupleBrowser;
/**
* B+Tree persistent indexing data structure. B+Trees are optimized for
* block-based, random I/O storage because they store multiple keys on
* one tree node (called <code>BPage</code>). In addition, the leaf nodes
* directly contain (inline) the values associated with the keys, allowing a
* single (or sequential) disk read of all the values on the page.
* <p>
* B+Trees are n-airy, yeilding log(N) search cost. They are self-balancing,
* preventing search performance degradation when the size of the tree grows.
* <p>
* Keys and associated values must be <code>Serializable</code> objects. The
* user is responsible to supply a serializable <code>Comparator</code> object
* to be used for the ordering of entries, which are also called <code>Tuple</code>.
* The B+Tree allows traversing the keys in forward and reverse order using a
* TupleBrowser obtained from the browse() methods.
* <p>
* This implementation does not directly support duplicate keys, but it is
* possible to handle duplicates by inlining or referencing an object collection
* as a value.
* <p>
* There is no limit on key size or value size, but it is recommended to keep
* both as small as possible to reduce disk I/O. This is especially true for
* the key size, which impacts all non-leaf <code>BPage</code> objects.
*
* @author <a href="mailto:[email protected]">Alex Boisvert</a>
* @version $Id: BTree.java,v 1.6 2005/06/25 23:12:31 doomdark Exp $
*/
public class BTree<K,V>
implements Externalizable, JdbmBase<K,V>
{
private static final long serialVersionUID = 8883213742777032628L;
private static final boolean DEBUG = false;
/**
* Default page size (number of entries per node)
*/
public static final int DEFAULT_SIZE = 32;
/**
* Page manager used to persist changes in BPages
*/
protected transient RecordManager _recman;
/**
* This BTree's record ID in the PageManager.
*/
private transient long _recid;
/**
* Comparator used to index entries.
*/
protected Comparator<K> _comparator;
/**
* Serializer used to serialize index keys (optional)
*/
protected Serializer<K> keySerializer;
/**
* Serializer used to serialize index values (optional)
*/
protected Serializer<V> valueSerializer;
public Serializer<K> getKeySerializer() {
return keySerializer;
}
public void setKeySerializer(Serializer<K> keySerializer) {
this.keySerializer = keySerializer;
}
public Serializer<V> getValueSerializer() {
return valueSerializer;
}
public void setValueSerializer(Serializer<V> valueSerializer) {
this.valueSerializer = valueSerializer;
}
/**
* Height of the B+Tree. This is the number of BPages you have to traverse
* to get to a leaf BPage, starting from the root.
*/
private int _height;
/**
* Recid of the root BPage
*/
private transient long _root;
/**
* Number of entries in each BPage.
*/
protected int _pageSize;
/**
* Total number of entries in the BTree
*/
protected volatile int _entries;
/**
* Serializer used for BPages of this tree
*/
private transient BPage<K,V> _bpageSerializer;
/**
* Listeners which are notified about changes in records
*/
protected List<RecordListener<K,V>> recordListeners = new CopyOnWriteArrayList<RecordListener<K, V>>();
protected ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* No-argument constructor used by serialization.
*/
public BTree()
{
// empty
}
/**
* Create a new persistent BTree, with 16 entries per node.
*
* @param recman Record manager used for persistence.
* @param comparator Comparator used to order index entries
*/
public static <K,V> BTree<K,V> createInstance( RecordManager recman,
Comparator<K> comparator)
throws IOException
{
return createInstance( recman, comparator, null, null, DEFAULT_SIZE );
}
/**
* Create a new persistent BTree, with 16 entries per node.
*
* @param recman Record manager used for persistence.
* @param comparator Comparator used to order index entries
*/
@SuppressWarnings("unchecked")
public static <K extends Comparable,V> BTree<K,V> createInstance( RecordManager recman)
throws IOException
{
BTree<K,V> ret = createInstance( recman, ComparableComparator.INSTANCE, null, null, DEFAULT_SIZE );
return ret;
}
/**
* Create a new persistent BTree, with 16 entries per node.
*
* @param recman Record manager used for persistence.
* @param keySerializer Serializer used to serialize index keys (optional)
* @param valueSerializer Serializer used to serialize index values (optional)
* @param comparator Comparator used to order index entries
*/
public static <K,V> BTree<K,V> createInstance( RecordManager recman,
Comparator<K> comparator,
Serializer<K> keySerializer,
Serializer<V> valueSerializer )
throws IOException
{
return createInstance( recman, comparator, keySerializer,
valueSerializer, DEFAULT_SIZE );
}
/**
* Create a new persistent BTree with the given number of entries per node.
*
* @param recman Record manager used for persistence.
* @param comparator Comparator used to order index entries
* @param keySerializer Serializer used to serialize index keys (optional)
* @param valueSerializer Serializer used to serialize index values (optional)
* @param pageSize Number of entries per page (must be even).
*/
public static <K,V> BTree<K,V> createInstance( RecordManager recman,
Comparator<K> comparator,
Serializer<K> keySerializer,
Serializer<V> valueSerializer,
int pageSize )
throws IOException
{
BTree<K,V> btree;
if ( recman == null ) {
throw new IllegalArgumentException( "Argument 'recman' is null" );
}
if ( comparator == null ) {
throw new IllegalArgumentException( "Argument 'comparator' is null" );
}
if ( ! ( comparator instanceof Serializable ) ) {
throw new IllegalArgumentException( "Argument 'comparator' must be serializable" );
}
// make sure there's an even number of entries per BPage
if ( ( pageSize & 1 ) != 0 ) {
throw new IllegalArgumentException( "Argument 'pageSize' must be even" );
}
btree = new BTree<K,V>();
btree._recman = recman;
btree._comparator = comparator;
btree.keySerializer = keySerializer;
btree.valueSerializer = valueSerializer;
btree._pageSize = pageSize;
btree._bpageSerializer = new BPage<K,V>();
btree._bpageSerializer._btree = btree;
btree._recid = recman.insert( btree );
return btree;
}
/**
* Load a persistent BTree.
*
* @param recman RecordManager used to store the persistent btree
* @param recid Record id of the BTree
*/
@SuppressWarnings("unchecked")
public static <K,V> BTree<K,V> load( RecordManager recman, long recid )
throws IOException
{
BTree<K,V> btree = (BTree<K,V>) recman.fetch( recid );
btree._recid = recid;
btree._recman = recman;
btree._bpageSerializer = new BPage<K,V>();
btree._bpageSerializer._btree = btree;
return btree;
}
/**
* Get the {@link ReadWriteLock} associated with this BTree.
* This should be used with browsing operations to ensure
* consistency.
* @return
*/
public ReadWriteLock getLock() {
return lock;
}
/**
* Insert an entry in the BTree.
* <p>
* The BTree cannot store duplicate entries. An existing entry can be
* replaced using the <code>replace</code> flag. If an entry with the
* same key already exists in the BTree, its value is returned.
*
* @param key Insert key
* @param value Insert value
* @param replace Set to true to replace an existing key-value pair.
* @return Existing value, if any.
*/
public V insert(final K key, final V value,
final boolean replace )
throws IOException
{
if ( key == null ) {
throw new IllegalArgumentException( "Argument 'key' is null" );
}
if ( value == null ) {
throw new IllegalArgumentException( "Argument 'value' is null" );
}
try {
lock.writeLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
// BTree is currently empty, create a new root BPage
if (DEBUG) {
System.out.println( "BTree.insert() new root BPage" );
}
rootPage = new BPage<K,V>( this, key, value );
_root = rootPage._recid;
_height = 1;
_entries = 1;
_recman.update( _recid, this );
//notifi listeners
for(RecordListener<K,V> l : recordListeners){
l.recordInserted(key, value);
}
return null;
} else {
BPage.InsertResult<K,V> insert = rootPage.insert( _height, key, value, replace );
boolean dirty = false;
if ( insert._overflow != null ) {
// current root page overflowed, we replace with a new root page
if ( DEBUG ) {
System.out.println( "BTree.insert() replace root BPage due to overflow" );
}
rootPage = new BPage<K,V>( this, rootPage, insert._overflow );
_root = rootPage._recid;
_height += 1;
dirty = true;
}
if ( insert._existing == null ) {
_entries++;
dirty = true;
}
if ( dirty ) {
_recman.update( _recid, this );
}
//notify listeners
for(RecordListener<K,V> l : recordListeners){
if(insert._existing==null)
l.recordInserted(key, value);
else
l.recordUpdated(key, insert._existing, value);
}
// insert might have returned an existing value
return insert._existing;
}
} finally {
lock.writeLock().unlock();
}
}
/**
* Remove an entry with the given key from the BTree.
*
* @param key Removal key
* @return Value associated with the key, or null if no entry with given
* key existed in the BTree.
*/
public V remove( K key )
throws IOException
{
if ( key == null ) {
throw new IllegalArgumentException( "Argument 'key' is null" );
}
try {
lock.writeLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return null;
}
boolean dirty = false;
BPage.RemoveResult<K,V> remove = rootPage.remove( _height, key );
if ( remove._underflow && rootPage.isEmpty() ) {
_height -= 1;
dirty = true;
// TODO: check contract for BPages to be removed from recman.
if ( _height == 0 ) {
_root = 0;
} else {
_root = rootPage.childBPage( _pageSize-1 )._recid;
}
}
if ( remove._value != null ) {
_entries--;
dirty = true;
}
if ( dirty ) {
_recman.update( _recid, this );
}
if(remove._value!=null)
for(RecordListener<K,V> l : recordListeners)
l.recordRemoved(key,remove._value);
return remove._value;
} finally {
lock.writeLock().unlock();
}
}
/**
* Find the value associated with the given key.
*
* @param key Lookup key.
* @return Value associated with the key, or null if not found.
*/
public V find( K key )
throws IOException
{
if ( key == null ) {
throw new IllegalArgumentException( "Argument 'key' is null" );
}
try {
lock.readLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return null;
}
return rootPage.findValue( _height, key );
} finally {
lock.readLock().unlock();
}
// Tuple<K,V> tuple = new Tuple<K,V>( null, null );
// TupleBrowser<K,V> browser = rootPage.find( _height, key );
//
// if ( browser.getNext( tuple ) ) {
// // find returns the matching key or the next ordered key, so we must
// // check if we have an exact match
// if ( _comparator.compare( key, tuple.getKey() ) != 0 ) {
// return null;
// } else {
// return tuple.getValue();
// }
// } else {
// return null;
// }
}
/**
* Find the value associated with the given key, or the entry immediately
* following this key in the ordered BTree.
*
* @param key Lookup key.
* @return Value associated with the key, or a greater entry, or null if no
* greater entry was found.
*/
public Tuple<K,V> findGreaterOrEqual( K key )
throws IOException
{
Tuple<K,V> tuple;
TupleBrowser<K,V> browser;
if ( key == null ) {
// there can't be a key greater than or equal to "null"
// because null is considered an infinite key.
return null;
}
tuple = new Tuple<K,V>( null, null );
browser = browse( key );
if ( browser.getNext( tuple ) ) {
return tuple;
} else {
return null;
}
}
/**
* Get a browser initially positioned at the beginning of the BTree.
* <p><b>
* WARNING: �If you make structural modifications to the BTree during
* browsing, you will get inconsistent browing results.
* </b>
*
* @return Browser positionned at the beginning of the BTree.
*/
@SuppressWarnings("unchecked")
public TupleBrowser<K,V> browse()
throws IOException
{
try {
lock.readLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return EmptyBrowser.INSTANCE;
}
TupleBrowser<K,V> browser = rootPage.findFirst();
return browser;
} finally {
lock.readLock().unlock();
}
}
/**
* Get a browser initially positioned just before the given key.
* <p><b>
* WARNING: �If you make structural modifications to the BTree during
* browsing, you will get inconsistent browing results.
* </b>
*
* @param key Key used to position the browser. If null, the browser
* will be positionned after the last entry of the BTree.
* (Null is considered to be an "infinite" key)
* @return Browser positionned just before the given key.
*/
@SuppressWarnings("unchecked")
public TupleBrowser<K,V> browse( K key )
throws IOException
{
try {
lock.readLock().lock();
BPage<K,V> rootPage = getRoot();
if ( rootPage == null ) {
return EmptyBrowser.INSTANCE;
}
TupleBrowser<K,V> browser = rootPage.find( _height, key );
return browser;
} finally {
lock.readLock().unlock();
}
}
/**
* Return the number of entries (size) of the BTree.
*/
public int size()
{
return _entries;
}
/**
* Return the persistent record identifier of the BTree.
*/
public long getRecid()
{
return _recid;
}
/**
* Return the root BPage, or null if it doesn't exist.
*/
BPage<K,V> getRoot()
throws IOException
{
if ( _root == 0 ) {
return null;
}
BPage<K,V> root = (BPage<K,V>) _recman.fetch( _root, _bpageSerializer );
if (root != null) {
root._recid = _root;
root._btree = this;
}
return root;
}
/**
* Implement Externalizable interface.
*/
@SuppressWarnings("unchecked")
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException
{
_comparator = (Comparator<K>) in.readObject();
//serializer is not persistent from 2.0
// _keySerializer = (Serializer<K>) in.readObject();
// _valueSerializer = (Serializer<V>) in.readObject();
_height = in.readInt();
_root = in.readLong();
_pageSize = in.readInt();
_entries = in.readInt();
}
/**
* Implement Externalizable interface.
*/
public void writeExternal( ObjectOutput out )
throws IOException
{
out.writeObject( _comparator );
//serializer is not persistent from 2.0
// out.writeObject( _keySerializer );
// out.writeObject( _valueSerializer );
out.writeInt( _height );
out.writeLong( _root );
out.writeInt( _pageSize );
out.writeInt( _entries );
}
/*
public void assert() throws IOException {
BPage root = getRoot();
if ( root != null ) {
root.assertRecursive( _height );
}
}
*/
/*
public void dump() throws IOException {
BPage root = getRoot();
if ( root != null ) {
root.dumpRecursive( _height, 0 );
}
}
*/
/** PRIVATE INNER CLASS
* Browser returning no element.
*/
static class EmptyBrowser<K,V>
implements TupleBrowser<K,V> {
@SuppressWarnings("unchecked")
static TupleBrowser INSTANCE = new EmptyBrowser();
private EmptyBrowser(){}
public boolean getNext( Tuple<K,V> tuple )
{
return false;
}
public boolean getPrevious( Tuple<K,V> tuple )
{
return false;
}
}
public BTreeSortedMap<K,V> asMap(){
return new BTreeSortedMap<K, V>(this,false);
}
/**
* add RecordListener which is notified about record changes
* @param listener
*/
public void addRecordListener(RecordListener<K,V> listener){
recordListeners.add(listener);
}
/**
* remove RecordListener which is notified about record changes
* @param listener
*/
public void removeRecordListener(RecordListener<K,V> listener){
recordListeners.remove(listener);
}
public RecordManager getRecordManager() {
return _recman;
}
public Comparator<K> getComparator() {
return _comparator;
}
/**
* Deletes all BPages in this BTree, then deletes the tree from the record manager
*/
public void delete()
throws IOException
{
try {
lock.writeLock().lock();
BPage<K,V> rootPage = getRoot();
if (rootPage != null)
rootPage.delete();
_recman.delete(_recid);
} finally {
lock.writeLock().unlock();
}
}
/**
* Used for debugging and testing only. Populates the 'out' list with
* the recids of all child pages in the BTree.
* @param out
* @throws IOException
*/
void dumpChildPageRecIDs(List<Long> out) throws IOException{
BPage<K,V> root = getRoot();
if ( root != null ) {
out.add(root._recid);
root.dumpChildPageRecIDs( out, _height);
}
}
}
| Fixed BTree leak
Fixed Issue 10. This fix comes from ApacheDS
| src/main/jdbm/btree/BTree.java | Fixed BTree leak | <ide><path>rc/main/jdbm/btree/BTree.java
<ide> _height -= 1;
<ide> dirty = true;
<ide>
<del> // TODO: check contract for BPages to be removed from recman.
<add> _recman.delete(_root);
<ide> if ( _height == 0 ) {
<ide> _root = 0;
<ide> } else { |
|
Java | lgpl-2.1 | ff9c47ca209e24c312ca42c687f8f978f4147740 | 0 | exedio/copernica,exedio/copernica,exedio/copernica | /*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope.util;
public final class ConnectionPoolInfo
{
private final int idleCount;
private final int activeCount;
private final PoolCounter counter;
public ConnectionPoolInfo(
final int idleCount, final int activeCount,
final PoolCounter counter)
{
if(counter==null)
throw new NullPointerException();
this.idleCount = idleCount;
this.activeCount = activeCount;
this.counter = counter;
}
public int getIdleCounter()
{
return idleCount;
}
public int getActiveCounter()
{
return activeCount;
}
public PoolCounter getCounter()
{
return counter;
}
}
| lib/src/com/exedio/cope/util/ConnectionPoolInfo.java | /*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope.util;
public final class ConnectionPoolInfo
{
private final int idleCount;
private final int activeCount;
private final PoolCounter counter;
public ConnectionPoolInfo(
final int idleCount, final int activeCount,
final PoolCounter counter)
{
if(counter==null)
throw new NullPointerException();
this.idleCount = idleCount;
this.activeCount = activeCount;
this.counter = counter;
}
public int getIdleCount()
{
return idleCount;
}
public int getActiveCount()
{
return activeCount;
}
public PoolCounter getCounter()
{
return counter;
}
}
| rename getXXCount to getXXCounter, is more consistent with the rest
git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@3790 e7d4fc99-c606-0410-b9bf-843393a9eab7
| lib/src/com/exedio/cope/util/ConnectionPoolInfo.java | rename getXXCount to getXXCounter, is more consistent with the rest | <ide><path>ib/src/com/exedio/cope/util/ConnectionPoolInfo.java
<ide> this.counter = counter;
<ide> }
<ide>
<del> public int getIdleCount()
<add> public int getIdleCounter()
<ide> {
<ide> return idleCount;
<ide> }
<ide>
<del> public int getActiveCount()
<add> public int getActiveCounter()
<ide> {
<ide> return activeCount;
<ide> } |
|
Java | mit | df0724972391fe34c36d59277c67582e6aedba44 | 0 | andham97/IIE-rally | package main;
import lejos.hardware.BrickFinder;
import lejos.hardware.Keys;
import lejos.hardware.motor.Motor;
import main.parts.EngineController;
import main.parts.MainSensorController;
import main.parts.MainSensorController.SensorSide;
import main.parts.MainSensorController.SensorType;
public class Brain {
private Keys keys;
private MainSensorController sensorController;
private EngineController engine;
private int engineSpeed = 200;
private float lastRColor = 0;
private float lastLColor = 0;
private boolean isRunning = false;
private boolean inRTurn = false;
private boolean inLTurn = false;
private boolean rightLast = false;
private boolean forceForward = false;
/**
* The color value of the track line.
*/
private final int REACT_COLOR_VALUE = 7;
/**
* Constructor for this class, initializes a bunch of important stuff
*/
public Brain() {
sensorController = new MainSensorController("S1", SensorType.NXT, "S4", SensorType.EV3);
// EngineController(Bak venstre, bak høyre, forran venstre, forran høyre)
engine = new EngineController(Motor.D, Motor.A);
engine.setSpeed(engineSpeed, true, true);
keys = BrickFinder.getLocal().getKeys();
this.start();
sensorController.start();
}
/**
* Sets the running boolean to true
*/
public void start() {
isRunning = true;
Motor.D.forward();
}
public void stop() {
Motor.D.stop();
isRunning = false;
System.exit(0);
}
/**
* Checks if a button on the Lejos device has been pushed, intended to stop
* the running loop
*/
public void checkInterruptButton() {
if (keys.getButtons() != 0) {
System.exit(0);
}
}
/**
* The main running loop for the brain
*/
public void run() throws Exception {
// Start a thread to check if any terminate buttons are pressed
new Thread("InterruptButtonMoitor") {
@Override
public void run() {
while (isRunning) {
checkInterruptButton();
}
}
}.start();
while (isRunning) {
engine.forward(5, true);
this.colorCheck(SensorSide.RIGHT, lastRColor);
this.colorCheck(SensorSide.LEFT, lastLColor);
Thread.sleep(20);
}
}
/**
* Reaction for when the color sensor discovers the black tape.
*
* @throws InterruptedException
*/
public void blackTapeRightReaction() throws InterruptedException {
inRTurn = true;
if (!inLTurn && rightLast) {
wiggleStraighteningSpeed = 0;
engine.rightTurn();
engine.stopLeftTurn(engineSpeed);
} else if (!inLTurn) {
blackTapeStraightReaction(true);
}
rightLast = true;
}
public void blackTapeLeftReaction() throws InterruptedException {
inLTurn = true;
if (!inRTurn && !rightLast) {
wiggleStraighteningSpeed = 0;
engine.leftTurn();
engine.stopRightTurn(engineSpeed);
} else if (!inRTurn) {
blackTapeStraightReaction(false);
}
rightLast = false;
}
public void noTapeRightReaction() throws InterruptedException {
if (inRTurn) {
engine.stopRightTurn(engineSpeed);
}
inRTurn = false;
}
public void noTapeLeftReaction() throws InterruptedException {
if (inLTurn) {
engine.stopLeftTurn(engineSpeed);
}
inLTurn = false;
}
float wiggleStraighteningSpeed = 0;
public void blackTapeStraightReaction(boolean rightTurn) throws InterruptedException {
wiggleStraighteningSpeed += engineSpeed / 10;
if (wiggleStraighteningSpeed > engineSpeed) {
wiggleStraighteningSpeed = engineSpeed;
}
forceForward = true;
if (rightTurn) {
//engine.rightTurn();
engine.setSpeed(wiggleStraighteningSpeed, false, true);
} else {
//engine.leftTurn();
engine.setSpeed(wiggleStraighteningSpeed, true, false);
}
engine.forward(5, true);
//Thread.sleep(100);
engine.forward(5, true);
//engine.stopLeftTurn(engineSpeed);
//engine.stopRightTurn(engineSpeed);
//Thread.sleep(200);
forceForward = false;
}
/**
* Checks if the recorded color is black or not
*
* @param side
* @param lastColor
* @throws InterruptedException
*/
public void colorCheck(SensorSide side, float lastColor) throws InterruptedException {
if (!forceForward) {
float currentColor = sensorController.getValue(side);
if (currentColor < 0.5 && side == SensorSide.RIGHT) {
currentColor = 7;
}
if (currentColor != lastColor && currentColor == REACT_COLOR_VALUE) {
if (side == SensorSide.RIGHT) {
lastRColor = currentColor;
blackTapeRightReaction();
} else {
lastLColor = currentColor;
blackTapeLeftReaction();
}
} else if (currentColor != lastColor) {
if (side == SensorSide.RIGHT) {
lastRColor = currentColor;
noTapeRightReaction();
} else {
lastLColor = currentColor;
noTapeLeftReaction();
}
}
}
}
}
| main/Brain.java | package main;
import lejos.hardware.BrickFinder;
import lejos.hardware.Keys;
import lejos.hardware.motor.Motor;
import main.parts.EngineController;
import main.parts.MainSensorController;
import main.parts.MainSensorController.SensorSide;
import main.parts.MainSensorController.SensorType;
public class Brain {
private Keys keys;
private MainSensorController sensorController;
private EngineController engine;
private int engineSpeed = 200;
private float lastRColor = 0;
private float lastLColor = 0;
private boolean isRunning = false;
private boolean inRTurn = false;
private boolean inLTurn = false;
private boolean rightLast = false;
private boolean forceForward = false;
/**
* The color value of the track line.
*/
private final int REACT_COLOR_VALUE = 7;
/**
* Constructor for this class, initializes a bunch of important stuff
*/
public Brain(){
sensorController = new MainSensorController("S1", SensorType.NXT, "S4", SensorType.EV3);
// EngineController(Bak venstre, bak høyre, forran venstre, forran høyre)
engine = new EngineController(Motor.D, Motor.A);
engine.setSpeed(engineSpeed, true, true);
keys = BrickFinder.getLocal().getKeys();
this.start();
sensorController.start();
}
/**
* Sets the running boolean to true
*/
public void start(){
isRunning = true;
Motor.D.forward();
}
public void stop(){
Motor.D.stop();
isRunning = false;
System.exit(0);
}
/**
* Checks if a button on the Lejos device has been pushed, intended to stop the running loop
*/
public void checkInterruptButton(){
if(keys.getButtons() != 0){
System.exit(0);
}
}
/**
* The main running loop for the brain
*/
public void run() throws Exception{
// Start a thread to check if any terminate buttons are pressed
new Thread("InterruptButtonMoitor") {
@Override
public void run() {
while(isRunning){
checkInterruptButton();
}
}
}.start();
while(isRunning){
engine.forward(5, true);
this.colorCheck(SensorSide.RIGHT, lastRColor);
this.colorCheck(SensorSide.LEFT, lastLColor);
Thread.sleep(20);
}
}
/**
* Reaction for when the color sensor discovers the black tape.
* @throws InterruptedException
*/
public void blackTapeRightReaction() throws InterruptedException{
inRTurn = true;
if(!inLTurn && rightLast){
engine.rightTurn();
}else{
blackTapeBothReaction(true);
}
rightLast = true;
}
public void blackTapeLeftReaction() throws InterruptedException{
inLTurn = true;
if(!inRTurn && !rightLast){
engine.leftTurn();
}else{
blackTapeBothReaction(false);
}
rightLast = false;
}
public void noTapeRightReaction() throws InterruptedException{
if(inRTurn)
engine.stopRightTurn(engineSpeed);
inRTurn = false;
}
public void noTapeLeftReaction() throws InterruptedException{
if(inLTurn)
engine.stopLeftTurn(engineSpeed);
inLTurn = false;
}
public void blackTapeBothReaction(boolean rightTurn) throws InterruptedException{
forceForward = true;
if(rightTurn)
engine.rightTurn();
else
engine.leftTurn();
engine.forward(5, true);
Thread.sleep(100);
engine.forward(5, true);
engine.stopLeftTurn(engineSpeed);
engine.stopRightTurn(engineSpeed);
Thread.sleep(200);
forceForward = false;
}
/**
* Checks if the recorded color is black or not
* @throws InterruptedException
*/
public void colorCheck(SensorSide side, float lastColor) throws InterruptedException{
if(!forceForward){
float currentColor = sensorController.getValue(side);
if(currentColor < 0.5 && side == SensorSide.RIGHT)
currentColor = 7;
if (currentColor != lastColor && currentColor == REACT_COLOR_VALUE) {
lastColor = currentColor;
if(side == SensorSide.RIGHT)
blackTapeRightReaction();
else
blackTapeLeftReaction();
}
else if(currentColor != lastColor){
lastColor = currentColor;
if(side == SensorSide.RIGHT)
noTapeRightReaction();
else
noTapeLeftReaction();
}
}
}
} | Wiggle stabilizer
Wiggle wiggle wiggle no more!
| main/Brain.java | Wiggle stabilizer | <ide><path>ain/Brain.java
<ide> import main.parts.MainSensorController.SensorType;
<ide>
<ide> public class Brain {
<del> private Keys keys;
<del> private MainSensorController sensorController;
<del> private EngineController engine;
<del> private int engineSpeed = 200;
<del> private float lastRColor = 0;
<del> private float lastLColor = 0;
<del> private boolean isRunning = false;
<del> private boolean inRTurn = false;
<del> private boolean inLTurn = false;
<del> private boolean rightLast = false;
<del> private boolean forceForward = false;
<del>
<del> /**
<del> * The color value of the track line.
<del> */
<del> private final int REACT_COLOR_VALUE = 7;
<del>
<del>
<del> /**
<del> * Constructor for this class, initializes a bunch of important stuff
<del> */
<del> public Brain(){
<del> sensorController = new MainSensorController("S1", SensorType.NXT, "S4", SensorType.EV3);
<del> // EngineController(Bak venstre, bak høyre, forran venstre, forran høyre)
<del> engine = new EngineController(Motor.D, Motor.A);
<del> engine.setSpeed(engineSpeed, true, true);
<del> keys = BrickFinder.getLocal().getKeys();
<del> this.start();
<del> sensorController.start();
<del> }
<del>
<del> /**
<del> * Sets the running boolean to true
<del> */
<del> public void start(){
<del> isRunning = true;
<del> Motor.D.forward();
<del> }
<del>
<del> public void stop(){
<add>
<add> private Keys keys;
<add> private MainSensorController sensorController;
<add> private EngineController engine;
<add> private int engineSpeed = 200;
<add> private float lastRColor = 0;
<add> private float lastLColor = 0;
<add> private boolean isRunning = false;
<add> private boolean inRTurn = false;
<add> private boolean inLTurn = false;
<add> private boolean rightLast = false;
<add> private boolean forceForward = false;
<add>
<add> /**
<add> * The color value of the track line.
<add> */
<add> private final int REACT_COLOR_VALUE = 7;
<add>
<add> /**
<add> * Constructor for this class, initializes a bunch of important stuff
<add> */
<add> public Brain() {
<add> sensorController = new MainSensorController("S1", SensorType.NXT, "S4", SensorType.EV3);
<add> // EngineController(Bak venstre, bak høyre, forran venstre, forran høyre)
<add> engine = new EngineController(Motor.D, Motor.A);
<add> engine.setSpeed(engineSpeed, true, true);
<add> keys = BrickFinder.getLocal().getKeys();
<add> this.start();
<add> sensorController.start();
<add> }
<add>
<add> /**
<add> * Sets the running boolean to true
<add> */
<add> public void start() {
<add> isRunning = true;
<add> Motor.D.forward();
<add> }
<add>
<add> public void stop() {
<ide> Motor.D.stop();
<ide> isRunning = false;
<ide> System.exit(0);
<del> }
<del>
<del> /**
<del> * Checks if a button on the Lejos device has been pushed, intended to stop the running loop
<del> */
<del> public void checkInterruptButton(){
<del> if(keys.getButtons() != 0){
<del> System.exit(0);
<del> }
<del> }
<del>
<del> /**
<del> * The main running loop for the brain
<del> */
<del> public void run() throws Exception{
<add> }
<add>
<add> /**
<add> * Checks if a button on the Lejos device has been pushed, intended to stop
<add> * the running loop
<add> */
<add> public void checkInterruptButton() {
<add> if (keys.getButtons() != 0) {
<add> System.exit(0);
<add> }
<add> }
<add>
<add> /**
<add> * The main running loop for the brain
<add> */
<add> public void run() throws Exception {
<ide> // Start a thread to check if any terminate buttons are pressed
<del> new Thread("InterruptButtonMoitor") {
<add> new Thread("InterruptButtonMoitor") {
<ide> @Override
<ide> public void run() {
<del> while(isRunning){
<del> checkInterruptButton();
<del> }
<add> while (isRunning) {
<add> checkInterruptButton();
<add> }
<ide> }
<ide> }.start();
<del>
<del> while(isRunning){
<add>
<add> while (isRunning) {
<ide> engine.forward(5, true);
<del>
<add>
<ide> this.colorCheck(SensorSide.RIGHT, lastRColor);
<ide> this.colorCheck(SensorSide.LEFT, lastLColor);
<ide>
<ide> Thread.sleep(20);
<ide> }
<ide> }
<del>
<del> /**
<del> * Reaction for when the color sensor discovers the black tape.
<del> * @throws InterruptedException
<del> */
<del> public void blackTapeRightReaction() throws InterruptedException{
<del> inRTurn = true;
<del> if(!inLTurn && rightLast){
<del> engine.rightTurn();
<del> }else{
<del> blackTapeBothReaction(true);
<del> }
<del> rightLast = true;
<del> }
<del> public void blackTapeLeftReaction() throws InterruptedException{
<del> inLTurn = true;
<del> if(!inRTurn && !rightLast){
<del> engine.leftTurn();
<del> }else{
<del> blackTapeBothReaction(false);
<del> }
<del> rightLast = false;
<del> }
<del>
<del> public void noTapeRightReaction() throws InterruptedException{
<del> if(inRTurn)
<del> engine.stopRightTurn(engineSpeed);
<del> inRTurn = false;
<del> }
<del> public void noTapeLeftReaction() throws InterruptedException{
<del> if(inLTurn)
<del> engine.stopLeftTurn(engineSpeed);
<del> inLTurn = false;
<del> }
<del>
<del> public void blackTapeBothReaction(boolean rightTurn) throws InterruptedException{
<del> forceForward = true;
<del> if(rightTurn)
<del> engine.rightTurn();
<del> else
<del> engine.leftTurn();
<del> engine.forward(5, true);
<del> Thread.sleep(100);
<del> engine.forward(5, true);
<del> engine.stopLeftTurn(engineSpeed);
<del> engine.stopRightTurn(engineSpeed);
<del> Thread.sleep(200);
<del> forceForward = false;
<del> }
<del>
<del> /**
<del> * Checks if the recorded color is black or not
<del> * @throws InterruptedException
<del> */
<del> public void colorCheck(SensorSide side, float lastColor) throws InterruptedException{
<del> if(!forceForward){
<del> float currentColor = sensorController.getValue(side);
<del> if(currentColor < 0.5 && side == SensorSide.RIGHT)
<del> currentColor = 7;
<del> if (currentColor != lastColor && currentColor == REACT_COLOR_VALUE) {
<del> lastColor = currentColor;
<del> if(side == SensorSide.RIGHT)
<del> blackTapeRightReaction();
<del> else
<del> blackTapeLeftReaction();
<del> }
<del> else if(currentColor != lastColor){
<del> lastColor = currentColor;
<del> if(side == SensorSide.RIGHT)
<del> noTapeRightReaction();
<del> else
<del> noTapeLeftReaction();
<del> }
<del> }
<del> }
<add>
<add> /**
<add> * Reaction for when the color sensor discovers the black tape.
<add> *
<add> * @throws InterruptedException
<add> */
<add> public void blackTapeRightReaction() throws InterruptedException {
<add> inRTurn = true;
<add> if (!inLTurn && rightLast) {
<add> wiggleStraighteningSpeed = 0;
<add> engine.rightTurn();
<add> engine.stopLeftTurn(engineSpeed);
<add> } else if (!inLTurn) {
<add> blackTapeStraightReaction(true);
<add> }
<add> rightLast = true;
<add> }
<add>
<add> public void blackTapeLeftReaction() throws InterruptedException {
<add> inLTurn = true;
<add> if (!inRTurn && !rightLast) {
<add> wiggleStraighteningSpeed = 0;
<add> engine.leftTurn();
<add> engine.stopRightTurn(engineSpeed);
<add>
<add> } else if (!inRTurn) {
<add> blackTapeStraightReaction(false);
<add> }
<add> rightLast = false;
<add> }
<add>
<add> public void noTapeRightReaction() throws InterruptedException {
<add> if (inRTurn) {
<add> engine.stopRightTurn(engineSpeed);
<add> }
<add> inRTurn = false;
<add> }
<add>
<add> public void noTapeLeftReaction() throws InterruptedException {
<add> if (inLTurn) {
<add> engine.stopLeftTurn(engineSpeed);
<add> }
<add> inLTurn = false;
<add> }
<add>
<add> float wiggleStraighteningSpeed = 0;
<add>
<add> public void blackTapeStraightReaction(boolean rightTurn) throws InterruptedException {
<add> wiggleStraighteningSpeed += engineSpeed / 10;
<add> if (wiggleStraighteningSpeed > engineSpeed) {
<add> wiggleStraighteningSpeed = engineSpeed;
<add> }
<add>
<add> forceForward = true;
<add> if (rightTurn) {
<add> //engine.rightTurn();
<add> engine.setSpeed(wiggleStraighteningSpeed, false, true);
<add> } else {
<add> //engine.leftTurn();
<add> engine.setSpeed(wiggleStraighteningSpeed, true, false);
<add> }
<add> engine.forward(5, true);
<add> //Thread.sleep(100);
<add> engine.forward(5, true);
<add> //engine.stopLeftTurn(engineSpeed);
<add> //engine.stopRightTurn(engineSpeed);
<add> //Thread.sleep(200);
<add> forceForward = false;
<add> }
<add>
<add> /**
<add> * Checks if the recorded color is black or not
<add> *
<add> * @param side
<add> * @param lastColor
<add> * @throws InterruptedException
<add> */
<add> public void colorCheck(SensorSide side, float lastColor) throws InterruptedException {
<add> if (!forceForward) {
<add> float currentColor = sensorController.getValue(side);
<add> if (currentColor < 0.5 && side == SensorSide.RIGHT) {
<add> currentColor = 7;
<add> }
<add> if (currentColor != lastColor && currentColor == REACT_COLOR_VALUE) {
<add> if (side == SensorSide.RIGHT) {
<add> lastRColor = currentColor;
<add> blackTapeRightReaction();
<add> } else {
<add> lastLColor = currentColor;
<add> blackTapeLeftReaction();
<add> }
<add> } else if (currentColor != lastColor) {
<add> if (side == SensorSide.RIGHT) {
<add> lastRColor = currentColor;
<add> noTapeRightReaction();
<add> } else {
<add> lastLColor = currentColor;
<add> noTapeLeftReaction();
<add> }
<add> }
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java' did not match any file(s) known to git
| 049d0a3e00e71844b612eb9a62c131517d3fe58c | 1 | apache/velocity-engine,apache/velocity-engine | package org.apache.velocity.runtime.resource.loader;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.util.Map;
import java.util.Hashtable;
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.runtime.resource.Resource;
/**
* This is a simple template file loader that loads templates
* from a DataSource instead of plain files.
*
* It can be configured with a datasource name, a table name,
* id column (name), content column (the template body) and a
* timestamp column (for last modification info).
* <br>
* <br>
* Example configuration snippet for velocity.properties:
* <br>
* <br>
* resource.loader.1.public.name = DataSource <br>
* resource.loader.1.description = Velocity DataSource Resource Loader <br>
* resource.loader.1.class = org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader <br>
* resource.loader.1.resource.datasource = jdbc/SomeDS <br>
* resource.loader.1.resource.table = template_table <br>
* resource.loader.1.resource.keycolumn = template_id <br>
* resource.loader.1.resource.templatecolumn = template_definition <br>
* resource.loader.1.resource.timestampcolumn = template_timestamp <br>
* resource.loader.1.cache = false <br>
* resource.loader.1.modificationCheckInterval = 60<br>
*
* @author <a href="mailto:[email protected]">David Kinnvall</a>
* @author <a href="Paulo Gaspar <[email protected]">Paulo Gaspar</a>
* @version $Id: DataSourceResourceLoader.java,v 1.1 2001/02/25 19:54:30 geirm Exp $
*/
public class DataSourceResourceLoader extends ResourceLoader
{
private String dataSourceName;
private String tableName;
private String keyColumn;
private String templateColumn;
private String timestampColumn;
private InitialContext ctx;
private DataSource dataSource;
/*
* This should probably be moved into the super class,
* the stand init stuff. For the properties that all
* loaders will probably share.
*/
public void init(Map initializer)
{
dataSourceName = (String) initializer.get("resource.datasource");
tableName = (String) initializer.get("resource.table");
keyColumn = (String) initializer.get("resource.keycolumn");
templateColumn = (String) initializer.get("resource.templatecolumn");
timestampColumn = (String) initializer.get("resource.timestampcolumn");
Runtime.info("Resources Loaded From: " + dataSourceName + "/" + tableName);
Runtime.info( "Resource Loader using columns: " + keyColumn + ", "
+ templateColumn + " and " + timestampColumn);
Runtime.info("Resource Loader Initalized.");
}
public boolean isSourceModified(Resource resource)
{
return (resource.getLastModified() !=
readLastModified(resource, "checking timestamp"));
}
public long getLastModified(Resource resource)
{
return readLastModified(resource, "getting timestamp");
}
/**
* Get an InputStream so that the Runtime can build a
* template with it.
*
* @param name name of template
* @return InputStream containing template
*/
public synchronized InputStream getResourceStream( String name )
throws Exception
{
if (name == null || name.length() == 0)
{
throw new Exception ("Need to specify a template name!");
}
try
{
Connection conn = openDbConnection();
try
{
ResultSet rs = readData(conn, templateColumn, name);
try
{
if (rs.next())
{
return new
BufferedInputStream(rs.getAsciiStream(templateColumn));
}
else
{
Runtime.error(
"DataSourceResourceLoader Error: cannot find resource "
+ name);
}
}
finally
{
rs.close();
}
}
finally
{
closeDbConnection(conn);
}
}
catch(Exception e)
{
Runtime.error(
"DataSourceResourceLoader Error: database problem trying to load resource "
+ name + ": " + e.toString() );
}
return null;
}
/**
* Fetches the last modification time of the resource
*
* @param resource Resource object we are finding timestamp of
* @param i_operation string for logging, indicating caller's intention
*
* @return timestamp as long
*/
private long readLastModified(Resource resource, String i_operation)
{
/*
* get the template name from the resource
*/
String name = resource.getName();
try
{
Connection conn = openDbConnection();
try
{
ResultSet rs = readData(conn, timestampColumn, name);
try
{
if (rs.next())
{
return rs.getLong(timestampColumn);
}
else
{
Runtime.error("DataSourceResourceLoader Error: while "
+ i_operation
+ " could not find resource " + name);
}
}
finally
{
rs.close();
}
}
finally
{
closeDbConnection(conn);
}
}
catch(Exception e)
{
Runtime.error( "DataSourceResourceLoader Error: error while "
+ i_operation + " when trying to load resource "
+ name + ": " + e.toString() );
}
return 0;
}
/**
* gets connection to the datasource specified through the configuration
* parameters.
*
* @return connection
*/
private Connection openDbConnection()
throws Exception
{
if(ctx == null)
{
ctx = new InitialContext();
}
if(dataSource == null)
{
dataSource = (DataSource)ctx.lookup(dataSourceName);
}
return dataSource.getConnection();
}
/**
* Closes connection to the datasource
*/
private void closeDbConnection(Connection conn)
{
try
{
conn.close();
}
catch (Exception e)
{
Runtime.info(
"DataSourceResourceLoader Quirk: problem when closing connection: "
+ e.toString());
}
}
/**
* Reads the data from the datasource. It simply does the following query :
* <br>
* SELECT <i>columnNames</i> FROM <i>tableName</i> WHERE <i>keyColumn</i>
* = '<i>templateName</i>'
* <br>
* where <i>keyColumn</i> is a class member set in init()
*
* @param conn connection to datasource
* @param columnNames columns to fetch from datasource
* @param templateName name of template to fetch
* @return result set from query
*/
private ResultSet readData(Connection conn, String columnNames, String templateName)
throws SQLException
{
Statement stmt = conn.createStatement();
String sql = "SELECT " + columnNames
+ " FROM " + tableName
+ " WHERE " + keyColumn + " = '" + templateName + "'";
return stmt.executeQuery(sql);
}
}
| src/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java | Changed name of class, incorporated author, doc, and naming changes.
PR:
Obtained from:
Submitted by:
Reviewed by:
git-svn-id: 7267684f36935cb3df12efc1f4c0216d758271d4@74277 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java | Changed name of class, incorporated author, doc, and naming changes. | <ide><path>rc/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java
<add>package org.apache.velocity.runtime.resource.loader;
<add>
<add>/*
<add> * The Apache Software License, Version 1.1
<add> *
<add> * Copyright (c) 2001 The Apache Software Foundation. All rights
<add> * reserved.
<add> *
<add> * Redistribution and use in source and binary forms, with or without
<add> * modification, are permitted provided that the following conditions
<add> * are met:
<add> *
<add> * 1. Redistributions of source code must retain the above copyright
<add> * notice, this list of conditions and the following disclaimer.
<add> *
<add> * 2. Redistributions in binary form must reproduce the above copyright
<add> * notice, this list of conditions and the following disclaimer in
<add> * the documentation and/or other materials provided with the
<add> * distribution.
<add> *
<add> * 3. The end-user documentation included with the redistribution, if
<add> * any, must include the following acknowlegement:
<add> * "This product includes software developed by the
<add> * Apache Software Foundation (http://www.apache.org/)."
<add> * Alternately, this acknowlegement may appear in the software itself,
<add> * if and wherever such third-party acknowlegements normally appear.
<add> *
<add> * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
<add> * Foundation" must not be used to endorse or promote products derived
<add> * from this software without prior written permission. For written
<add> * permission, please contact [email protected].
<add> *
<add> * 5. Products derived from this software may not be called "Apache"
<add> * nor may "Apache" appear in their names without prior written
<add> * permission of the Apache Group.
<add> *
<add> * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
<add> * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
<add> * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
<add> * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
<add> * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
<add> * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
<add> * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
<add> * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
<add> * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
<add> * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
<add> * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
<add> * SUCH DAMAGE.
<add> * ====================================================================
<add> *
<add> * This software consists of voluntary contributions made by many
<add> * individuals on behalf of the Apache Software Foundation. For more
<add> * information on the Apache Software Foundation, please see
<add> * <http://www.apache.org/>.
<add> */
<add>
<add>import java.io.InputStream;
<add>import java.io.BufferedInputStream;
<add>import java.util.Map;
<add>import java.util.Hashtable;
<add>
<add>import java.sql.*;
<add>import javax.sql.DataSource;
<add>import javax.naming.InitialContext;
<add>
<add>import org.apache.velocity.runtime.Runtime;
<add>import org.apache.velocity.runtime.resource.Resource;
<add>
<add>/**
<add> * This is a simple template file loader that loads templates
<add> * from a DataSource instead of plain files.
<add> *
<add> * It can be configured with a datasource name, a table name,
<add> * id column (name), content column (the template body) and a
<add> * timestamp column (for last modification info).
<add> * <br>
<add> * <br>
<add> * Example configuration snippet for velocity.properties:
<add> * <br>
<add> * <br>
<add> * resource.loader.1.public.name = DataSource <br>
<add> * resource.loader.1.description = Velocity DataSource Resource Loader <br>
<add> * resource.loader.1.class = org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader <br>
<add> * resource.loader.1.resource.datasource = jdbc/SomeDS <br>
<add> * resource.loader.1.resource.table = template_table <br>
<add> * resource.loader.1.resource.keycolumn = template_id <br>
<add> * resource.loader.1.resource.templatecolumn = template_definition <br>
<add> * resource.loader.1.resource.timestampcolumn = template_timestamp <br>
<add> * resource.loader.1.cache = false <br>
<add> * resource.loader.1.modificationCheckInterval = 60<br>
<add> *
<add> * @author <a href="mailto:[email protected]">David Kinnvall</a>
<add> * @author <a href="Paulo Gaspar <[email protected]">Paulo Gaspar</a>
<add> * @version $Id: DataSourceResourceLoader.java,v 1.1 2001/02/25 19:54:30 geirm Exp $
<add> */
<add>public class DataSourceResourceLoader extends ResourceLoader
<add>{
<add> private String dataSourceName;
<add> private String tableName;
<add> private String keyColumn;
<add> private String templateColumn;
<add> private String timestampColumn;
<add> private InitialContext ctx;
<add> private DataSource dataSource;
<add>
<add> /*
<add> * This should probably be moved into the super class,
<add> * the stand init stuff. For the properties that all
<add> * loaders will probably share.
<add> */
<add> public void init(Map initializer)
<add> {
<add> dataSourceName = (String) initializer.get("resource.datasource");
<add> tableName = (String) initializer.get("resource.table");
<add> keyColumn = (String) initializer.get("resource.keycolumn");
<add> templateColumn = (String) initializer.get("resource.templatecolumn");
<add> timestampColumn = (String) initializer.get("resource.timestampcolumn");
<add> Runtime.info("Resources Loaded From: " + dataSourceName + "/" + tableName);
<add> Runtime.info( "Resource Loader using columns: " + keyColumn + ", "
<add> + templateColumn + " and " + timestampColumn);
<add> Runtime.info("Resource Loader Initalized.");
<add> }
<add>
<add> public boolean isSourceModified(Resource resource)
<add> {
<add> return (resource.getLastModified() !=
<add> readLastModified(resource, "checking timestamp"));
<add> }
<add>
<add> public long getLastModified(Resource resource)
<add> {
<add> return readLastModified(resource, "getting timestamp");
<add> }
<add>
<add> /**
<add> * Get an InputStream so that the Runtime can build a
<add> * template with it.
<add> *
<add> * @param name name of template
<add> * @return InputStream containing template
<add> */
<add> public synchronized InputStream getResourceStream( String name )
<add> throws Exception
<add> {
<add> if (name == null || name.length() == 0)
<add> {
<add> throw new Exception ("Need to specify a template name!");
<add> }
<add>
<add> try
<add> {
<add> Connection conn = openDbConnection();
<add>
<add> try
<add> {
<add> ResultSet rs = readData(conn, templateColumn, name);
<add>
<add> try
<add> {
<add> if (rs.next())
<add> {
<add> return new
<add> BufferedInputStream(rs.getAsciiStream(templateColumn));
<add> }
<add> else
<add> {
<add> Runtime.error(
<add> "DataSourceResourceLoader Error: cannot find resource "
<add> + name);
<add> }
<add> }
<add> finally
<add> {
<add> rs.close();
<add> }
<add> }
<add> finally
<add> {
<add> closeDbConnection(conn);
<add> }
<add> }
<add> catch(Exception e)
<add> {
<add> Runtime.error(
<add> "DataSourceResourceLoader Error: database problem trying to load resource "
<add> + name + ": " + e.toString() );
<add> }
<add> return null;
<add> }
<add>
<add> /**
<add> * Fetches the last modification time of the resource
<add> *
<add> * @param resource Resource object we are finding timestamp of
<add> * @param i_operation string for logging, indicating caller's intention
<add> *
<add> * @return timestamp as long
<add> */
<add> private long readLastModified(Resource resource, String i_operation)
<add> {
<add> /*
<add> * get the template name from the resource
<add> */
<add>
<add> String name = resource.getName();
<add> try
<add> {
<add> Connection conn = openDbConnection();
<add>
<add> try
<add> {
<add> ResultSet rs = readData(conn, timestampColumn, name);
<add> try
<add> {
<add> if (rs.next())
<add> {
<add> return rs.getLong(timestampColumn);
<add> }
<add> else
<add> {
<add> Runtime.error("DataSourceResourceLoader Error: while "
<add> + i_operation
<add> + " could not find resource " + name);
<add> }
<add> }
<add> finally
<add> {
<add> rs.close();
<add> }
<add> }
<add> finally
<add> {
<add> closeDbConnection(conn);
<add> }
<add> }
<add> catch(Exception e)
<add> {
<add> Runtime.error( "DataSourceResourceLoader Error: error while "
<add> + i_operation + " when trying to load resource "
<add> + name + ": " + e.toString() );
<add> }
<add> return 0;
<add> }
<add>
<add> /**
<add> * gets connection to the datasource specified through the configuration
<add> * parameters.
<add> *
<add> * @return connection
<add> */
<add> private Connection openDbConnection()
<add> throws Exception
<add> {
<add> if(ctx == null)
<add> {
<add> ctx = new InitialContext();
<add> }
<add>
<add> if(dataSource == null)
<add> {
<add> dataSource = (DataSource)ctx.lookup(dataSourceName);
<add> }
<add>
<add> return dataSource.getConnection();
<add> }
<add>
<add> /**
<add> * Closes connection to the datasource
<add> */
<add> private void closeDbConnection(Connection conn)
<add> {
<add> try
<add> {
<add> conn.close();
<add> }
<add> catch (Exception e)
<add> {
<add> Runtime.info(
<add> "DataSourceResourceLoader Quirk: problem when closing connection: "
<add> + e.toString());
<add> }
<add> }
<add>
<add> /**
<add> * Reads the data from the datasource. It simply does the following query :
<add> * <br>
<add> * SELECT <i>columnNames</i> FROM <i>tableName</i> WHERE <i>keyColumn</i>
<add> * = '<i>templateName</i>'
<add> * <br>
<add> * where <i>keyColumn</i> is a class member set in init()
<add> *
<add> * @param conn connection to datasource
<add> * @param columnNames columns to fetch from datasource
<add> * @param templateName name of template to fetch
<add> * @return result set from query
<add> */
<add> private ResultSet readData(Connection conn, String columnNames, String templateName)
<add> throws SQLException
<add> {
<add> Statement stmt = conn.createStatement();
<add>
<add> String sql = "SELECT " + columnNames
<add> + " FROM " + tableName
<add> + " WHERE " + keyColumn + " = '" + templateName + "'";
<add>
<add> return stmt.executeQuery(sql);
<add> }
<add>}
<add>
<add>
<add>
<add> |
|
Java | apache-2.0 | 0fbee34c30319425bf6a7e4639e135b10f22da23 | 0 | sangramjadhav/testrs | 2295fcee-2ece-11e5-905b-74de2bd44bed | hello.java | 22956e82-2ece-11e5-905b-74de2bd44bed | 2295fcee-2ece-11e5-905b-74de2bd44bed | hello.java | 2295fcee-2ece-11e5-905b-74de2bd44bed | <ide><path>ello.java
<del>22956e82-2ece-11e5-905b-74de2bd44bed
<add>2295fcee-2ece-11e5-905b-74de2bd44bed |
|
Java | apache-2.0 | 2c47237030906fbf189b6aef7e62618c7237034a | 0 | OrBin/SynClock-Android,dseuss/deskclock,dseuss/deskclock | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.deskclock.timer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.TextView;
import com.android.deskclock.Log;
import com.android.deskclock.R;
import com.android.deskclock.Utils;
public class CountingTimerView extends View {
private static final String TWO_DIGITS = "%02d";
private static final String ONE_DIGIT = "%01d";
private static final String NEG_TWO_DIGITS = "-%02d";
private static final String NEG_ONE_DIGIT = "-%01d";
private static final float TEXT_SIZE_TO_WIDTH_RATIO = 0.75f;
// This is the ratio of the font typeface we need to offset the font by vertically to align it
// vertically center.
private static final float FONT_VERTICAL_OFFSET = 0.14f;
private String mHours, mMinutes, mSeconds, mHundredths;
private boolean mShowTimeStr = true;
private final Typeface mAndroidClockMonoThin, mAndroidClockMonoBold, mAndroidClockMonoLight;
private final Typeface mRobotoLabel;
private final Paint mPaintBig = new Paint();
private final Paint mPaintBigThin = new Paint();
private final Paint mPaintMed = new Paint();
private final Paint mPaintLabel = new Paint();
private final float mBigFontSize, mSmallFontSize;
private SignedTime mBigHours, mBigMinutes;
private UnsignedTime mBigThinSeconds;
private Hundredths mMedHundredths;
private float mTextHeight = 0;
private float mTotalTextWidth;
private static final String HUNDREDTH_SEPERATOR = ".";
private boolean mRemeasureText = true;
private int mDefaultColor;
private final int mPressedColor;
private final int mWhiteColor;
private final int mRedColor;
private TextView mStopStartTextView;
private final AccessibilityManager mAccessibilityManager;
// Fields for the text serving as a virtual button.
private boolean mVirtualButtonEnabled = false;
private boolean mVirtualButtonPressedOn = false;
Runnable mBlinkThread = new Runnable() {
private boolean mVisible = true;
@Override
public void run() {
mVisible = !mVisible;
CountingTimerView.this.showTime(mVisible);
postDelayed(mBlinkThread, 500);
}
};
class UnsignedTime {
protected Paint mPaint;
protected float mEm;
protected float mWidth = 0;
private String mWidest;
protected String mLabel;
private float mLabelWidth = 0;
public UnsignedTime(Paint paint, final String label, String allDigits) {
mPaint = paint;
mLabel = label;
if (TextUtils.isEmpty(allDigits)) {
Log.wtf("Locale digits missing - using English");
allDigits = "0123456789";
}
float widths[] = new float[allDigits.length()];
int ll = mPaint.getTextWidths(allDigits, widths);
int largest = 0;
for (int ii = 1; ii < ll; ii++) {
if (widths[ii] > widths[largest]) {
largest = ii;
}
}
mEm = widths[largest];
mWidest = allDigits.substring(largest, largest + 1);
}
public UnsignedTime(UnsignedTime unsignedTime, final String label) {
this.mPaint = unsignedTime.mPaint;
this.mEm = unsignedTime.mEm;
this.mWidth = unsignedTime.mWidth;
this.mWidest = unsignedTime.mWidest;
this.mLabel = label;
}
protected void updateWidth(final String time) {
mEm = mPaint.measureText(mWidest);
mLabelWidth = mLabel == null ? 0 : mPaintLabel.measureText(mLabel);
mWidth = time.length() * mEm;
}
protected void resetWidth() {
mWidth = mLabelWidth = 0;
}
public float calcTotalWidth(final String time) {
if (time != null) {
updateWidth(time);
return mWidth + mLabelWidth;
} else {
resetWidth();
return 0;
}
}
public float getWidth() {
return mWidth;
}
public float getLabelWidth() {
return mLabelWidth;
}
protected float drawTime(Canvas canvas, final String time, int ii, float x, float y) {
float textEm = mEm / 2f;
while (ii < time.length()) {
x += textEm;
canvas.drawText(time.substring(ii, ii + 1), x, y, mPaint);
x += textEm;
ii++;
}
return x;
}
public float draw(Canvas canvas, final String time, float x, float y, float yLabel) {
x = drawTime(canvas, time, 0, x, y);
if (mLabel != null ) {
canvas.drawText(mLabel, x, yLabel, mPaintLabel);
}
return x + getLabelWidth();
}
}
class Hundredths extends UnsignedTime {
public Hundredths(Paint paint, final String label, final String allDigits) {
super(paint, label, allDigits);
}
@Override
public float draw(Canvas canvas, final String time, float x, float y, float yLabel) {
if (mLabel != null) {
canvas.drawText(mLabel, x, yLabel, mPaintLabel);
}
return drawTime(canvas, time, 0, x + getLabelWidth(), y);
}
}
class SignedTime extends UnsignedTime {
private float mMinusWidth = 0;
public SignedTime(Paint paint, final String label, final String allDigits) {
super(paint, label, allDigits);
}
public SignedTime (SignedTime signedTime, final String label) {
super(signedTime, label);
}
@Override
protected void updateWidth(final String time) {
super.updateWidth(time);
if (time.contains("-")) {
mMinusWidth = mPaint.measureText("-");
mWidth += (mMinusWidth - mEm);
} else {
mMinusWidth = 0;
}
}
@Override
protected void resetWidth() {
super.resetWidth();
mMinusWidth = 0;
}
@Override
public float draw(Canvas canvas, final String time, float x, float y, float yLabel) {
int ii = 0;
if (mMinusWidth != 0f) {
float minusWidth = mMinusWidth / 2;
x += minusWidth;
canvas.drawText(time.substring(ii, ii + 1), x, y, mPaint);
x += minusWidth;
ii++;
}
x = drawTime(canvas, time, ii, x, y);
if (mLabel != null) {
canvas.drawText(mLabel, x, yLabel, mPaintLabel);
}
return x + getLabelWidth();
}
}
public CountingTimerView(Context context) {
this(context, null);
}
public CountingTimerView(Context context, AttributeSet attrs) {
super(context, attrs);
mAndroidClockMonoThin = Typeface.createFromAsset(
context.getAssets(), "fonts/AndroidClockMono-Thin.ttf");
mAndroidClockMonoBold = Typeface.createFromAsset(
context.getAssets(), "fonts/AndroidClockMono-Bold.ttf");
mAndroidClockMonoLight = Typeface.createFromAsset(
context.getAssets(), "fonts/AndroidClockMono-Light.ttf");
mAccessibilityManager =
(AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
mRobotoLabel= Typeface.create("sans-serif-condensed", Typeface.BOLD);
Resources r = context.getResources();
mWhiteColor = r.getColor(R.color.clock_white);
mDefaultColor = mWhiteColor;
mPressedColor = r.getColor(Utils.getPressedColorId());
mRedColor = r.getColor(R.color.clock_red);
mPaintBig.setAntiAlias(true);
mPaintBig.setStyle(Paint.Style.STROKE);
mPaintBig.setTextAlign(Paint.Align.CENTER);
mPaintBig.setTypeface(mAndroidClockMonoBold);
mBigFontSize = r.getDimension(R.dimen.big_font_size);
mSmallFontSize = r.getDimension(R.dimen.small_font_size);
mPaintBigThin.setAntiAlias(true);
mPaintBigThin.setStyle(Paint.Style.STROKE);
mPaintBigThin.setTextAlign(Paint.Align.CENTER);
mPaintBigThin.setTypeface(mAndroidClockMonoThin);
mPaintMed.setAntiAlias(true);
mPaintMed.setStyle(Paint.Style.STROKE);
mPaintMed.setTextAlign(Paint.Align.CENTER);
mPaintMed.setTypeface(mAndroidClockMonoLight);
mPaintLabel.setAntiAlias(true);
mPaintLabel.setStyle(Paint.Style.STROKE);
mPaintLabel.setTextAlign(Paint.Align.LEFT);
mPaintLabel.setTypeface(mRobotoLabel);
mPaintLabel.setTextSize(r.getDimension(R.dimen.label_font_size));
resetTextSize();
setTextColor(mDefaultColor);
// allDigits will contain ten digits: "0123456789" in the default locale
final String allDigits = String.format("%010d", 123456789);
mBigHours = new SignedTime(mPaintBig,
r.getString(R.string.hours_label).toUpperCase(), allDigits);
mBigMinutes = new SignedTime(mBigHours,
r.getString(R.string.minutes_label).toUpperCase());
mBigThinSeconds = new UnsignedTime(mPaintBigThin,
r.getString(R.string.seconds_label).toUpperCase(), allDigits);
mMedHundredths = new Hundredths(mPaintMed, HUNDREDTH_SEPERATOR, allDigits);
}
protected void resetTextSize() {
mPaintBig.setTextSize(mBigFontSize);
mTextHeight = mBigFontSize;
mPaintBigThin.setTextSize(mBigFontSize);
mPaintMed.setTextSize(mSmallFontSize);
}
protected void setTextColor(int textColor) {
mPaintBig.setColor(textColor);
mPaintBigThin.setColor(textColor);
mPaintMed.setColor(textColor);
mPaintLabel.setColor(textColor);
}
public void setTime(long time, boolean showHundredths, boolean update) {
boolean neg = false, showNeg = false;
String format = null;
if (time < 0) {
time = -time;
neg = showNeg = true;
}
long hundreds, seconds, minutes, hours;
seconds = time / 1000;
hundreds = (time - seconds * 1000) / 10;
minutes = seconds / 60;
seconds = seconds - minutes * 60;
hours = minutes / 60;
minutes = minutes - hours * 60;
if (hours > 99) {
hours = 0;
}
// time may less than a second below zero, since we do not show fractions of seconds
// when counting down, do not show the minus sign.
if (hours ==0 && minutes == 0 && seconds == 0) {
showNeg = false;
}
if (!showHundredths) {
if (!neg && hundreds != 0) {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}
}
}
if (hundreds < 10 || hundreds > 90) {
update = true;
}
}
int oldLength = getDigitsLength();
if (hours >= 10) {
format = showNeg ? NEG_TWO_DIGITS : TWO_DIGITS;
mHours = String.format(format, hours);
} else if (hours > 0) {
format = showNeg ? NEG_ONE_DIGIT : ONE_DIGIT;
mHours = String.format(format, hours);
} else {
mHours = null;
}
if (minutes >= 10 || hours > 0) {
format = (showNeg && hours == 0) ? NEG_TWO_DIGITS : TWO_DIGITS;
mMinutes = String.format(format, minutes);
} else {
format = (showNeg && hours == 0) ? NEG_ONE_DIGIT : ONE_DIGIT;
mMinutes = String.format(format, minutes);
}
mSeconds = String.format(TWO_DIGITS, seconds);
if (showHundredths) {
mHundredths = String.format(TWO_DIGITS, hundreds);
} else {
mHundredths = null;
}
int newLength = getDigitsLength();
if (oldLength != newLength) {
if (oldLength > newLength) {
resetTextSize();
}
mRemeasureText = true;
}
if (update) {
setContentDescription(getTimeStringForAccessibility((int) hours, (int) minutes,
(int) seconds, showNeg, getResources()));
invalidate();
}
}
private int getDigitsLength() {
return ((mHours == null) ? 0 : mHours.length())
+ ((mMinutes == null) ? 0 : mMinutes.length())
+ ((mSeconds == null) ? 0 : mSeconds.length())
+ ((mHundredths == null) ? 0 : mHundredths.length());
}
private void calcTotalTextWidth() {
mTotalTextWidth = mBigHours.calcTotalWidth(mHours) + mBigMinutes.calcTotalWidth(mMinutes)
+ mBigThinSeconds.calcTotalWidth(mSeconds)
+ mMedHundredths.calcTotalWidth(mHundredths);
}
private void setTotalTextWidth() {
calcTotalTextWidth();
// To determine the maximum width, we find the minimum of the height and width (since the
// circle we are trying to fit the text into has its radius sized to the smaller of the
// two.
int width = Math.min(getWidth(), getHeight());
if (width != 0) {
float wantWidth = (int)(TEXT_SIZE_TO_WIDTH_RATIO * width);
// If the text is too wide, reduce all the paint text sizes
while (mTotalTextWidth > wantWidth) {
// Get fixed and variant parts of the total size
float fixedWidths = mBigHours.getLabelWidth() + mBigMinutes.getLabelWidth()
+ mBigThinSeconds.getLabelWidth() + mMedHundredths.getLabelWidth();
float varWidths = mBigHours.getWidth() + mBigMinutes.getWidth()
+ mBigThinSeconds.getWidth() + mMedHundredths.getWidth();
// Avoid divide by zero || sizeRatio == 1 || sizeRatio <= 0
if (varWidths == 0 || fixedWidths == 0 || fixedWidths >= wantWidth) {
break;
}
// Variant-section reduction
float sizeRatio = (wantWidth - fixedWidths) / varWidths;
mPaintBig.setTextSize(mPaintBig.getTextSize() * sizeRatio);
mPaintBigThin.setTextSize(mPaintBigThin.getTextSize() * sizeRatio);
mPaintMed.setTextSize(mPaintMed.getTextSize() * sizeRatio);
//recalculate the new total text width and half text height
mTextHeight = mPaintBig.getTextSize();
calcTotalTextWidth();
}
}
}
public void blinkTimeStr(boolean blink) {
if (blink) {
removeCallbacks(mBlinkThread);
postDelayed(mBlinkThread, 1000);
} else {
removeCallbacks(mBlinkThread);
showTime(true);
}
}
public void showTime(boolean visible) {
mShowTimeStr = visible;
invalidate();
}
public void redTimeStr(boolean red, boolean forceUpdate) {
mDefaultColor = red ? mRedColor : mWhiteColor;
setTextColor(mDefaultColor);
if (forceUpdate) {
invalidate();
}
}
public String getTimeString() {
// Though only called from Stopwatch Share, so hundredth are never null,
// protect the future and check for null mHundredths
if (mHundredths == null) {
if (mHours == null) {
return String.format("%s:%s", mMinutes, mSeconds);
}
return String.format("%s:%s:%s", mHours, mMinutes, mSeconds);
} else if (mHours == null) {
return String.format("%s:%s.%s", mMinutes, mSeconds, mHundredths);
}
return String.format("%s:%s:%s.%s", mHours, mMinutes, mSeconds, mHundredths);
}
private static String getTimeStringForAccessibility(int hours, int minutes, int seconds,
boolean showNeg, Resources r) {
StringBuilder s = new StringBuilder();
if (showNeg) {
// This must be followed by a non-zero number or it will be audible as "hyphen"
// instead of "minus".
s.append("-");
}
if (showNeg && hours == 0 && minutes == 0) {
// Non-negative time will always have minutes, eg. "0 minutes 7 seconds", but negative
// time must start with non-zero digit, eg. -0m7s will be audible as just "-7 seconds"
s.append(String.format(
r.getQuantityText(R.plurals.Nseconds_description, seconds).toString(),
seconds));
} else if (hours == 0) {
s.append(String.format(
r.getQuantityText(R.plurals.Nminutes_description, minutes).toString(),
minutes));
s.append(" ");
s.append(String.format(
r.getQuantityText(R.plurals.Nseconds_description, seconds).toString(),
seconds));
} else {
s.append(String.format(
r.getQuantityText(R.plurals.Nhours_description, hours).toString(),
hours));
s.append(" ");
s.append(String.format(
r.getQuantityText(R.plurals.Nminutes_description, minutes).toString(),
minutes));
s.append(" ");
s.append(String.format(
r.getQuantityText(R.plurals.Nseconds_description, seconds).toString(),
seconds));
}
return s.toString();
}
public void setVirtualButtonEnabled(boolean enabled) {
mVirtualButtonEnabled = enabled;
}
private void virtualButtonPressed(boolean pressedOn) {
mVirtualButtonPressedOn = pressedOn;
mStopStartTextView.setTextColor(pressedOn ? mPressedColor : mWhiteColor);
invalidate();
}
private boolean withinVirtualButtonBounds(float x, float y) {
int width = getWidth();
int height = getHeight();
float centerX = width / 2;
float centerY = height / 2;
float radius = Math.min(width, height) / 2;
// Within the circle button if distance to the center is less than the radius.
double distance = Math.sqrt(Math.pow(centerX - x, 2) + Math.pow(centerY - y, 2));
return distance < radius;
}
public void registerVirtualButtonAction(final Runnable runnable) {
if (!mAccessibilityManager.isEnabled()) {
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mVirtualButtonEnabled) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (withinVirtualButtonBounds(event.getX(), event.getY())) {
virtualButtonPressed(true);
return true;
} else {
virtualButtonPressed(false);
return false;
}
case MotionEvent.ACTION_CANCEL:
virtualButtonPressed(false);
return true;
case MotionEvent.ACTION_OUTSIDE:
virtualButtonPressed(false);
return false;
case MotionEvent.ACTION_UP:
virtualButtonPressed(false);
if (withinVirtualButtonBounds(event.getX(), event.getY())) {
runnable.run();
}
return true;
}
}
return false;
}
});
} else {
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
runnable.run();
}
});
}
}
@Override
public void onDraw(Canvas canvas) {
// Blink functionality.
if (!mShowTimeStr && !mVirtualButtonPressedOn) {
return;
}
int width = getWidth();
if (mRemeasureText && width != 0) {
setTotalTextWidth();
width = getWidth();
mRemeasureText = false;
}
int xCenter = width / 2;
int yCenter = getHeight() / 2;
float textXstart = xCenter - mTotalTextWidth / 2;
float textYstart = yCenter + mTextHeight/2 - (mTextHeight * FONT_VERTICAL_OFFSET);
// align the labels vertically to the top of the rest of the text
float labelYStart = textYstart - (mTextHeight * (1 - 2 * FONT_VERTICAL_OFFSET))
+ (1 - 2 * FONT_VERTICAL_OFFSET) * mPaintLabel.getTextSize();
// Text color differs based on pressed state.
int textColor;
if (mVirtualButtonPressedOn) {
textColor = mPressedColor;
mStopStartTextView.setTextColor(mPressedColor);
} else {
textColor = mDefaultColor;
}
mPaintBig.setColor(textColor);
mPaintBigThin.setColor(textColor);
mPaintLabel.setColor(textColor);
mPaintMed.setColor(textColor);
if (mHours != null) {
textXstart = mBigHours.draw(canvas, mHours, textXstart, textYstart, labelYStart);
}
if (mMinutes != null) {
textXstart = mBigMinutes.draw(canvas, mMinutes, textXstart, textYstart, labelYStart);
}
if (mSeconds != null) {
textXstart = mBigThinSeconds.draw(canvas, mSeconds,
textXstart, textYstart, labelYStart);
}
if (mHundredths != null) {
textXstart = mMedHundredths.draw(canvas, mHundredths,
textXstart, textYstart, textYstart);
}
}
public void registerStopTextView(TextView stopStartTextView) {
mStopStartTextView = stopStartTextView;
}
}
| src/com/android/deskclock/timer/CountingTimerView.java | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.deskclock.timer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.TextView;
import com.android.deskclock.DeskClock;
import com.android.deskclock.R;
import com.android.deskclock.Utils;
public class CountingTimerView extends View {
private static final String TWO_DIGITS = "%02d";
private static final String ONE_DIGIT = "%01d";
private static final String NEG_TWO_DIGITS = "-%02d";
private static final String NEG_ONE_DIGIT = "-%01d";
private static final float TEXT_SIZE_TO_WIDTH_RATIO = 0.75f;
// This is the ratio of the font typeface we need to offset the font by vertically to align it
// vertically center.
private static final float FONT_VERTICAL_OFFSET = 0.14f;
private String mHours, mMinutes, mSeconds, mHunderdths;
private final String mHoursLabel, mMinutesLabel, mSecondsLabel;
private float mHoursWidth, mMinutesWidth, mSecondsWidth, mHundredthsWidth;
private float mHoursLabelWidth, mMinutesLabelWidth, mSecondsLabelWidth, mHundredthsSepWidth;
private boolean mShowTimeStr = true;
private final Typeface mAndroidClockMonoThin, mAndroidClockMonoBold, mRobotoLabel, mAndroidClockMonoLight;
private final Paint mPaintBig = new Paint();
private final Paint mPaintBigThin = new Paint();
private final Paint mPaintMed = new Paint();
private final Paint mPaintLabel = new Paint();
private float mTextHeight = 0;
private float mTotalTextWidth;
private static final String HUNDREDTH_SEPERATOR = ".";
private boolean mRemeasureText = true;
private int mDefaultColor;
private final int mPressedColor;
private final int mWhiteColor;
private final int mRedColor;
private TextView mStopStartTextView;
private final AccessibilityManager mAccessibilityManager;
// Fields for the text serving as a virtual button.
private boolean mVirtualButtonEnabled = false;
private boolean mVirtualButtonPressedOn = false;
Runnable mBlinkThread = new Runnable() {
private boolean mVisible = true;
@Override
public void run() {
mVisible = !mVisible;
CountingTimerView.this.showTime(mVisible);
postDelayed(mBlinkThread, 500);
}
};
public CountingTimerView(Context context) {
this(context, null);
}
public CountingTimerView(Context context, AttributeSet attrs) {
super(context, attrs);
mAndroidClockMonoThin = Typeface.createFromAsset(context.getAssets(),"fonts/AndroidClockMono-Thin.ttf");
mAndroidClockMonoBold = Typeface.createFromAsset(context.getAssets(),"fonts/AndroidClockMono-Bold.ttf");
mAndroidClockMonoLight = Typeface.createFromAsset(context.getAssets(),"fonts/AndroidClockMono-Light.ttf");
mAccessibilityManager =
(AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
mRobotoLabel= Typeface.create("sans-serif-condensed", Typeface.BOLD);
Resources r = context.getResources();
mHoursLabel = r.getString(R.string.hours_label).toUpperCase();
mMinutesLabel = r.getString(R.string.minutes_label).toUpperCase();
mSecondsLabel = r.getString(R.string.seconds_label).toUpperCase();
mWhiteColor = r.getColor(R.color.clock_white);
mDefaultColor = mWhiteColor;
mPressedColor = r.getColor(Utils.getPressedColorId());
mRedColor = r.getColor(R.color.clock_red);
mPaintBig.setAntiAlias(true);
mPaintBig.setStyle(Paint.Style.STROKE);
mPaintBig.setTextAlign(Paint.Align.LEFT);
mPaintBig.setTypeface(mAndroidClockMonoBold);
float bigFontSize = r.getDimension(R.dimen.big_font_size);
mPaintBig.setTextSize(bigFontSize);
mTextHeight = bigFontSize;
mPaintBigThin.setAntiAlias(true);
mPaintBigThin.setStyle(Paint.Style.STROKE);
mPaintBigThin.setTextAlign(Paint.Align.LEFT);
mPaintBigThin.setTypeface(mAndroidClockMonoThin);
mPaintBigThin.setTextSize(r.getDimension(R.dimen.big_font_size));
mPaintMed.setAntiAlias(true);
mPaintMed.setStyle(Paint.Style.STROKE);
mPaintMed.setTextAlign(Paint.Align.LEFT);
mPaintMed.setTypeface(mAndroidClockMonoLight);
mPaintMed.setTextSize(r.getDimension(R.dimen.small_font_size));
mPaintLabel.setAntiAlias(true);
mPaintLabel.setStyle(Paint.Style.STROKE);
mPaintLabel.setTextAlign(Paint.Align.LEFT);
mPaintLabel.setTypeface(mRobotoLabel);
mPaintLabel.setTextSize(r.getDimension(R.dimen.label_font_size));
setTextColor(mDefaultColor);
}
protected void setTextColor(int textColor) {
mPaintBig.setColor(textColor);
mPaintBigThin.setColor(textColor);
mPaintMed.setColor(textColor);
mPaintLabel.setColor(textColor);
}
public void setTime(long time, boolean showHundredths, boolean update) {
boolean neg = false, showNeg = false;
String format = null;
if (time < 0) {
time = -time;
neg = showNeg = true;
}
long hundreds, seconds, minutes, hours;
seconds = time / 1000;
hundreds = (time - seconds * 1000) / 10;
minutes = seconds / 60;
seconds = seconds - minutes * 60;
hours = minutes / 60;
minutes = minutes - hours * 60;
if (hours > 99) {
hours = 0;
}
// time may less than a second below zero, since we do not show fractions of seconds
// when counting down, do not show the minus sign.
if (hours ==0 && minutes == 0 && seconds == 0) {
showNeg = false;
}
// TODO: must build to account for localization
if (!showHundredths) {
if (!neg && hundreds != 0) {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}
}
}
if (hundreds < 10 || hundreds > 90) {
update = true;
}
}
if (hours >= 10) {
format = showNeg ? NEG_TWO_DIGITS : TWO_DIGITS;
mHours = String.format(format, hours);
} else if (hours > 0) {
format = showNeg ? NEG_ONE_DIGIT : ONE_DIGIT;
mHours = String.format(format, hours);
} else {
mHours = null;
}
if (minutes >= 10 || hours > 0) {
format = (showNeg && hours == 0) ? NEG_TWO_DIGITS : TWO_DIGITS;
mMinutes = String.format(format, minutes);
} else {
format = (showNeg && hours == 0) ? NEG_ONE_DIGIT : ONE_DIGIT;
mMinutes = String.format(format, minutes);
}
mSeconds = String.format(TWO_DIGITS, seconds);
if (showHundredths) {
mHunderdths = String.format(TWO_DIGITS, hundreds);
} else {
mHunderdths = null;
}
mRemeasureText = true;
if (update) {
setContentDescription(getTimeStringForAccessibility((int) hours, (int) minutes,
(int) seconds, showNeg, getResources()));
invalidate();
}
}
private void setTotalTextWidth() {
mTotalTextWidth = 0;
if (mHours != null) {
mHoursWidth = mPaintBig.measureText(mHours);
mTotalTextWidth += mHoursWidth;
mHoursLabelWidth = mPaintLabel.measureText(mHoursLabel);
mTotalTextWidth += mHoursLabelWidth;
}
if (mMinutes != null) {
mMinutesWidth = mPaintBig.measureText(mMinutes);
mTotalTextWidth += mMinutesWidth;
mMinutesLabelWidth = mPaintLabel.measureText(mMinutesLabel);
mTotalTextWidth += mMinutesLabelWidth;
}
if (mSeconds != null) {
mSecondsWidth = mPaintBigThin.measureText(mSeconds);
mTotalTextWidth += mSecondsWidth;
mSecondsLabelWidth = mPaintLabel.measureText(mSecondsLabel);
mTotalTextWidth += mSecondsLabelWidth;
}
if (mHunderdths != null) {
mHundredthsWidth = mPaintMed.measureText(mHunderdths);
mTotalTextWidth += mHundredthsWidth;
mHundredthsSepWidth = mPaintLabel.measureText(HUNDREDTH_SEPERATOR);
mTotalTextWidth += mHundredthsSepWidth;
}
// This is a hack: if the text is too wide, reduce all the paint text sizes
// To determine the maximum width, we find the minimum of the height and width (since the
// circle we are trying to fit the text into has its radius sized to the smaller of the
// two.
int width = Math.min(getWidth(), getHeight());
if (width != 0) {
float ratio = mTotalTextWidth / width;
if (ratio > TEXT_SIZE_TO_WIDTH_RATIO) {
float sizeRatio = (TEXT_SIZE_TO_WIDTH_RATIO / ratio);
mPaintBig.setTextSize( mPaintBig.getTextSize() * sizeRatio);
mPaintBigThin.setTextSize( mPaintBigThin.getTextSize() * sizeRatio);
mPaintMed.setTextSize( mPaintMed.getTextSize() * sizeRatio);
mTotalTextWidth *= sizeRatio;
mMinutesWidth *= sizeRatio;
mHoursWidth *= sizeRatio;
mSecondsWidth *= sizeRatio;
mHundredthsWidth *= sizeRatio;
mHundredthsSepWidth *= sizeRatio;
//recalculate the new total text width and half text height
mTotalTextWidth = mHoursWidth + mMinutesWidth + mSecondsWidth +
mHundredthsWidth + mHundredthsSepWidth + mHoursLabelWidth +
mMinutesLabelWidth + mSecondsLabelWidth;
mTextHeight = mPaintBig.getTextSize();
}
}
}
public void blinkTimeStr(boolean blink) {
if (blink) {
removeCallbacks(mBlinkThread);
postDelayed(mBlinkThread, 1000);
} else {
removeCallbacks(mBlinkThread);
showTime(true);
}
}
public void showTime(boolean visible) {
mShowTimeStr = visible;
invalidate();
mRemeasureText = true;
}
public void redTimeStr(boolean red, boolean forceUpdate) {
mDefaultColor = red ? mRedColor : mWhiteColor;
setTextColor(mDefaultColor);
if (forceUpdate) {
invalidate();
}
}
public String getTimeString() {
if (mHours == null) {
return String.format("%s:%s.%s",mMinutes, mSeconds, mHunderdths);
}
return String.format("%s:%s:%s.%s",mHours, mMinutes, mSeconds, mHunderdths);
}
private static String getTimeStringForAccessibility(int hours, int minutes, int seconds,
boolean showNeg, Resources r) {
StringBuilder s = new StringBuilder();
if (showNeg) {
// This must be followed by a non-zero number or it will be audible as "hyphen"
// instead of "minus".
s.append("-");
}
if (showNeg && hours == 0 && minutes == 0) {
// Non-negative time will always have minutes, eg. "0 minutes 7 seconds", but negative
// time must start with non-zero digit, eg. -0m7s will be audible as just "-7 seconds"
s.append(String.format(
r.getQuantityText(R.plurals.Nseconds_description, seconds).toString(),
seconds));
} else if (hours == 0) {
s.append(String.format(
r.getQuantityText(R.plurals.Nminutes_description, minutes).toString(),
minutes));
s.append(" ");
s.append(String.format(
r.getQuantityText(R.plurals.Nseconds_description, seconds).toString(),
seconds));
} else {
s.append(String.format(
r.getQuantityText(R.plurals.Nhours_description, hours).toString(),
hours));
s.append(" ");
s.append(String.format(
r.getQuantityText(R.plurals.Nminutes_description, minutes).toString(),
minutes));
s.append(" ");
s.append(String.format(
r.getQuantityText(R.plurals.Nseconds_description, seconds).toString(),
seconds));
}
return s.toString();
}
public void setVirtualButtonEnabled(boolean enabled) {
mVirtualButtonEnabled = enabled;
}
private void virtualButtonPressed(boolean pressedOn) {
mVirtualButtonPressedOn = pressedOn;
mStopStartTextView.setTextColor(pressedOn ? mPressedColor : mWhiteColor);
invalidate();
}
private boolean withinVirtualButtonBounds(float x, float y) {
int width = getWidth();
int height = getHeight();
float centerX = width / 2;
float centerY = height / 2;
float radius = Math.min(width, height) / 2;
// Within the circle button if distance to the center is less than the radius.
double distance = Math.sqrt(Math.pow(centerX - x, 2) + Math.pow(centerY - y, 2));
return distance < radius;
}
public void registerVirtualButtonAction(final Runnable runnable) {
if (!mAccessibilityManager.isEnabled()) {
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mVirtualButtonEnabled) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (withinVirtualButtonBounds(event.getX(), event.getY())) {
virtualButtonPressed(true);
return true;
} else {
virtualButtonPressed(false);
return false;
}
case MotionEvent.ACTION_CANCEL:
virtualButtonPressed(false);
return true;
case MotionEvent.ACTION_OUTSIDE:
virtualButtonPressed(false);
return false;
case MotionEvent.ACTION_UP:
virtualButtonPressed(false);
if (withinVirtualButtonBounds(event.getX(), event.getY())) {
runnable.run();
}
return true;
}
}
return false;
}
});
} else {
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
runnable.run();
}
});
}
}
@Override
public void onDraw(Canvas canvas) {
// Blink functionality.
if (!mShowTimeStr && !mVirtualButtonPressedOn) {
return;
}
int width = getWidth();
if (mRemeasureText && width != 0) {
setTotalTextWidth();
width = getWidth();
mRemeasureText = false;
}
int xCenter = width / 2;
int yCenter = getHeight() / 2;
float textXstart = xCenter - mTotalTextWidth / 2;
float textYstart = yCenter + mTextHeight/2 - (mTextHeight * FONT_VERTICAL_OFFSET);
// align the labels vertically to the top of the rest of the text
float labelYStart = textYstart - (mTextHeight * (1 - 2 * FONT_VERTICAL_OFFSET))
+ (1 - 2 * FONT_VERTICAL_OFFSET) * mPaintLabel.getTextSize();
// Text color differs based on pressed state.
int textColor;
if (mVirtualButtonPressedOn) {
textColor = mPressedColor;
mStopStartTextView.setTextColor(mPressedColor);
} else {
textColor = mDefaultColor;
}
mPaintBig.setColor(textColor);
mPaintBigThin.setColor(textColor);
mPaintLabel.setColor(textColor);
mPaintMed.setColor(textColor);
if (mHours != null) {
canvas.drawText(mHours, textXstart, textYstart, mPaintBig);
textXstart += mHoursWidth;
canvas.drawText(mHoursLabel, textXstart, labelYStart, mPaintLabel);
textXstart += mHoursLabelWidth;
}
if (mMinutes != null) {
canvas.drawText(mMinutes, textXstart, textYstart, mPaintBig);
textXstart += mMinutesWidth;
canvas.drawText(mMinutesLabel, textXstart, labelYStart, mPaintLabel);
textXstart += mMinutesLabelWidth;
}
if (mSeconds != null) {
canvas.drawText(mSeconds, textXstart, textYstart, mPaintBigThin);
textXstart += mSecondsWidth;
canvas.drawText(mSecondsLabel, textXstart, labelYStart, mPaintLabel);
textXstart += mSecondsLabelWidth;
}
if (mHunderdths != null) {
canvas.drawText(HUNDREDTH_SEPERATOR, textXstart, textYstart, mPaintLabel);
textXstart += mHundredthsSepWidth;
canvas.drawText(mHunderdths, textXstart, textYstart, mPaintMed);
}
}
public void registerStopTextView(TextView stopStartTextView) {
mStopStartTextView = stopStartTextView;
}
}
| am 6a47c31f: am 761d9917: Fixed scaling on timer/stopwatch time
* commit '6a47c31f32625fdf1352430917645bdefb1b68f1':
Fixed scaling on timer/stopwatch time
| src/com/android/deskclock/timer/CountingTimerView.java | am 6a47c31f: am 761d9917: Fixed scaling on timer/stopwatch time | <ide><path>rc/com/android/deskclock/timer/CountingTimerView.java
<ide> /*
<del> * Copyright (C) 2008 The Android Open Source Project
<add> * Copyright (C) 2012 The Android Open Source Project
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import android.graphics.Canvas;
<ide> import android.graphics.Paint;
<ide> import android.graphics.Typeface;
<add>import android.text.TextUtils;
<ide> import android.util.AttributeSet;
<ide> import android.view.MotionEvent;
<ide> import android.view.View;
<ide> import android.view.accessibility.AccessibilityManager;
<ide> import android.widget.TextView;
<ide>
<del>import com.android.deskclock.DeskClock;
<add>import com.android.deskclock.Log;
<ide> import com.android.deskclock.R;
<ide> import com.android.deskclock.Utils;
<ide>
<ide> // vertically center.
<ide> private static final float FONT_VERTICAL_OFFSET = 0.14f;
<ide>
<del> private String mHours, mMinutes, mSeconds, mHunderdths;
<del> private final String mHoursLabel, mMinutesLabel, mSecondsLabel;
<del> private float mHoursWidth, mMinutesWidth, mSecondsWidth, mHundredthsWidth;
<del> private float mHoursLabelWidth, mMinutesLabelWidth, mSecondsLabelWidth, mHundredthsSepWidth;
<add> private String mHours, mMinutes, mSeconds, mHundredths;
<ide>
<ide> private boolean mShowTimeStr = true;
<del> private final Typeface mAndroidClockMonoThin, mAndroidClockMonoBold, mRobotoLabel, mAndroidClockMonoLight;
<add> private final Typeface mAndroidClockMonoThin, mAndroidClockMonoBold, mAndroidClockMonoLight;
<add> private final Typeface mRobotoLabel;
<ide> private final Paint mPaintBig = new Paint();
<ide> private final Paint mPaintBigThin = new Paint();
<ide> private final Paint mPaintMed = new Paint();
<ide> private final Paint mPaintLabel = new Paint();
<add> private final float mBigFontSize, mSmallFontSize;
<add> private SignedTime mBigHours, mBigMinutes;
<add> private UnsignedTime mBigThinSeconds;
<add> private Hundredths mMedHundredths;
<ide> private float mTextHeight = 0;
<ide> private float mTotalTextWidth;
<ide> private static final String HUNDREDTH_SEPERATOR = ".";
<ide>
<ide> };
<ide>
<add> class UnsignedTime {
<add> protected Paint mPaint;
<add> protected float mEm;
<add> protected float mWidth = 0;
<add> private String mWidest;
<add> protected String mLabel;
<add> private float mLabelWidth = 0;
<add>
<add> public UnsignedTime(Paint paint, final String label, String allDigits) {
<add> mPaint = paint;
<add> mLabel = label;
<add>
<add> if (TextUtils.isEmpty(allDigits)) {
<add> Log.wtf("Locale digits missing - using English");
<add> allDigits = "0123456789";
<add> }
<add>
<add> float widths[] = new float[allDigits.length()];
<add> int ll = mPaint.getTextWidths(allDigits, widths);
<add> int largest = 0;
<add> for (int ii = 1; ii < ll; ii++) {
<add> if (widths[ii] > widths[largest]) {
<add> largest = ii;
<add> }
<add> }
<add>
<add> mEm = widths[largest];
<add> mWidest = allDigits.substring(largest, largest + 1);
<add> }
<add>
<add> public UnsignedTime(UnsignedTime unsignedTime, final String label) {
<add> this.mPaint = unsignedTime.mPaint;
<add> this.mEm = unsignedTime.mEm;
<add> this.mWidth = unsignedTime.mWidth;
<add> this.mWidest = unsignedTime.mWidest;
<add> this.mLabel = label;
<add> }
<add>
<add> protected void updateWidth(final String time) {
<add> mEm = mPaint.measureText(mWidest);
<add> mLabelWidth = mLabel == null ? 0 : mPaintLabel.measureText(mLabel);
<add> mWidth = time.length() * mEm;
<add> }
<add>
<add> protected void resetWidth() {
<add> mWidth = mLabelWidth = 0;
<add> }
<add>
<add> public float calcTotalWidth(final String time) {
<add> if (time != null) {
<add> updateWidth(time);
<add> return mWidth + mLabelWidth;
<add> } else {
<add> resetWidth();
<add> return 0;
<add> }
<add> }
<add>
<add> public float getWidth() {
<add> return mWidth;
<add> }
<add>
<add> public float getLabelWidth() {
<add> return mLabelWidth;
<add> }
<add>
<add> protected float drawTime(Canvas canvas, final String time, int ii, float x, float y) {
<add> float textEm = mEm / 2f;
<add> while (ii < time.length()) {
<add> x += textEm;
<add> canvas.drawText(time.substring(ii, ii + 1), x, y, mPaint);
<add> x += textEm;
<add> ii++;
<add> }
<add> return x;
<add> }
<add>
<add> public float draw(Canvas canvas, final String time, float x, float y, float yLabel) {
<add> x = drawTime(canvas, time, 0, x, y);
<add> if (mLabel != null ) {
<add> canvas.drawText(mLabel, x, yLabel, mPaintLabel);
<add> }
<add> return x + getLabelWidth();
<add> }
<add> }
<add>
<add> class Hundredths extends UnsignedTime {
<add> public Hundredths(Paint paint, final String label, final String allDigits) {
<add> super(paint, label, allDigits);
<add> }
<add>
<add> @Override
<add> public float draw(Canvas canvas, final String time, float x, float y, float yLabel) {
<add> if (mLabel != null) {
<add> canvas.drawText(mLabel, x, yLabel, mPaintLabel);
<add> }
<add> return drawTime(canvas, time, 0, x + getLabelWidth(), y);
<add> }
<add> }
<add>
<add> class SignedTime extends UnsignedTime {
<add> private float mMinusWidth = 0;
<add>
<add> public SignedTime(Paint paint, final String label, final String allDigits) {
<add> super(paint, label, allDigits);
<add> }
<add>
<add> public SignedTime (SignedTime signedTime, final String label) {
<add> super(signedTime, label);
<add> }
<add>
<add> @Override
<add> protected void updateWidth(final String time) {
<add> super.updateWidth(time);
<add> if (time.contains("-")) {
<add> mMinusWidth = mPaint.measureText("-");
<add> mWidth += (mMinusWidth - mEm);
<add> } else {
<add> mMinusWidth = 0;
<add> }
<add> }
<add>
<add> @Override
<add> protected void resetWidth() {
<add> super.resetWidth();
<add> mMinusWidth = 0;
<add> }
<add>
<add> @Override
<add> public float draw(Canvas canvas, final String time, float x, float y, float yLabel) {
<add> int ii = 0;
<add> if (mMinusWidth != 0f) {
<add> float minusWidth = mMinusWidth / 2;
<add> x += minusWidth;
<add> canvas.drawText(time.substring(ii, ii + 1), x, y, mPaint);
<add> x += minusWidth;
<add> ii++;
<add> }
<add> x = drawTime(canvas, time, ii, x, y);
<add> if (mLabel != null) {
<add> canvas.drawText(mLabel, x, yLabel, mPaintLabel);
<add> }
<add> return x + getLabelWidth();
<add> }
<add> }
<ide>
<ide> public CountingTimerView(Context context) {
<ide> this(context, null);
<ide>
<ide> public CountingTimerView(Context context, AttributeSet attrs) {
<ide> super(context, attrs);
<del> mAndroidClockMonoThin = Typeface.createFromAsset(context.getAssets(),"fonts/AndroidClockMono-Thin.ttf");
<del> mAndroidClockMonoBold = Typeface.createFromAsset(context.getAssets(),"fonts/AndroidClockMono-Bold.ttf");
<del> mAndroidClockMonoLight = Typeface.createFromAsset(context.getAssets(),"fonts/AndroidClockMono-Light.ttf");
<add> mAndroidClockMonoThin = Typeface.createFromAsset(
<add> context.getAssets(), "fonts/AndroidClockMono-Thin.ttf");
<add> mAndroidClockMonoBold = Typeface.createFromAsset(
<add> context.getAssets(), "fonts/AndroidClockMono-Bold.ttf");
<add> mAndroidClockMonoLight = Typeface.createFromAsset(
<add> context.getAssets(), "fonts/AndroidClockMono-Light.ttf");
<ide> mAccessibilityManager =
<ide> (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
<ide> mRobotoLabel= Typeface.create("sans-serif-condensed", Typeface.BOLD);
<ide> Resources r = context.getResources();
<del> mHoursLabel = r.getString(R.string.hours_label).toUpperCase();
<del> mMinutesLabel = r.getString(R.string.minutes_label).toUpperCase();
<del> mSecondsLabel = r.getString(R.string.seconds_label).toUpperCase();
<ide> mWhiteColor = r.getColor(R.color.clock_white);
<ide> mDefaultColor = mWhiteColor;
<ide> mPressedColor = r.getColor(Utils.getPressedColorId());
<ide>
<ide> mPaintBig.setAntiAlias(true);
<ide> mPaintBig.setStyle(Paint.Style.STROKE);
<del> mPaintBig.setTextAlign(Paint.Align.LEFT);
<add> mPaintBig.setTextAlign(Paint.Align.CENTER);
<ide> mPaintBig.setTypeface(mAndroidClockMonoBold);
<del> float bigFontSize = r.getDimension(R.dimen.big_font_size);
<del> mPaintBig.setTextSize(bigFontSize);
<del> mTextHeight = bigFontSize;
<add> mBigFontSize = r.getDimension(R.dimen.big_font_size);
<add> mSmallFontSize = r.getDimension(R.dimen.small_font_size);
<ide>
<ide> mPaintBigThin.setAntiAlias(true);
<ide> mPaintBigThin.setStyle(Paint.Style.STROKE);
<del> mPaintBigThin.setTextAlign(Paint.Align.LEFT);
<add> mPaintBigThin.setTextAlign(Paint.Align.CENTER);
<ide> mPaintBigThin.setTypeface(mAndroidClockMonoThin);
<del> mPaintBigThin.setTextSize(r.getDimension(R.dimen.big_font_size));
<ide>
<ide> mPaintMed.setAntiAlias(true);
<ide> mPaintMed.setStyle(Paint.Style.STROKE);
<del> mPaintMed.setTextAlign(Paint.Align.LEFT);
<add> mPaintMed.setTextAlign(Paint.Align.CENTER);
<ide> mPaintMed.setTypeface(mAndroidClockMonoLight);
<del> mPaintMed.setTextSize(r.getDimension(R.dimen.small_font_size));
<ide>
<ide> mPaintLabel.setAntiAlias(true);
<ide> mPaintLabel.setStyle(Paint.Style.STROKE);
<ide> mPaintLabel.setTypeface(mRobotoLabel);
<ide> mPaintLabel.setTextSize(r.getDimension(R.dimen.label_font_size));
<ide>
<add> resetTextSize();
<ide> setTextColor(mDefaultColor);
<add>
<add> // allDigits will contain ten digits: "0123456789" in the default locale
<add> final String allDigits = String.format("%010d", 123456789);
<add> mBigHours = new SignedTime(mPaintBig,
<add> r.getString(R.string.hours_label).toUpperCase(), allDigits);
<add> mBigMinutes = new SignedTime(mBigHours,
<add> r.getString(R.string.minutes_label).toUpperCase());
<add> mBigThinSeconds = new UnsignedTime(mPaintBigThin,
<add> r.getString(R.string.seconds_label).toUpperCase(), allDigits);
<add> mMedHundredths = new Hundredths(mPaintMed, HUNDREDTH_SEPERATOR, allDigits);
<add> }
<add>
<add> protected void resetTextSize() {
<add> mPaintBig.setTextSize(mBigFontSize);
<add> mTextHeight = mBigFontSize;
<add> mPaintBigThin.setTextSize(mBigFontSize);
<add> mPaintMed.setTextSize(mSmallFontSize);
<ide> }
<ide>
<ide> protected void setTextColor(int textColor) {
<ide> if (hours ==0 && minutes == 0 && seconds == 0) {
<ide> showNeg = false;
<ide> }
<del> // TODO: must build to account for localization
<add>
<ide> if (!showHundredths) {
<ide> if (!neg && hundreds != 0) {
<ide> seconds++;
<ide> }
<ide> }
<ide>
<add> int oldLength = getDigitsLength();
<add>
<ide> if (hours >= 10) {
<ide> format = showNeg ? NEG_TWO_DIGITS : TWO_DIGITS;
<ide> mHours = String.format(format, hours);
<ide>
<ide> mSeconds = String.format(TWO_DIGITS, seconds);
<ide> if (showHundredths) {
<del> mHunderdths = String.format(TWO_DIGITS, hundreds);
<add> mHundredths = String.format(TWO_DIGITS, hundreds);
<ide> } else {
<del> mHunderdths = null;
<del> }
<del> mRemeasureText = true;
<add> mHundredths = null;
<add> }
<add>
<add> int newLength = getDigitsLength();
<add> if (oldLength != newLength) {
<add> if (oldLength > newLength) {
<add> resetTextSize();
<add> }
<add> mRemeasureText = true;
<add> }
<ide>
<ide> if (update) {
<ide> setContentDescription(getTimeStringForAccessibility((int) hours, (int) minutes,
<ide> invalidate();
<ide> }
<ide> }
<add>
<add> private int getDigitsLength() {
<add> return ((mHours == null) ? 0 : mHours.length())
<add> + ((mMinutes == null) ? 0 : mMinutes.length())
<add> + ((mSeconds == null) ? 0 : mSeconds.length())
<add> + ((mHundredths == null) ? 0 : mHundredths.length());
<add> }
<add>
<add> private void calcTotalTextWidth() {
<add> mTotalTextWidth = mBigHours.calcTotalWidth(mHours) + mBigMinutes.calcTotalWidth(mMinutes)
<add> + mBigThinSeconds.calcTotalWidth(mSeconds)
<add> + mMedHundredths.calcTotalWidth(mHundredths);
<add> }
<add>
<ide> private void setTotalTextWidth() {
<del> mTotalTextWidth = 0;
<del> if (mHours != null) {
<del> mHoursWidth = mPaintBig.measureText(mHours);
<del> mTotalTextWidth += mHoursWidth;
<del> mHoursLabelWidth = mPaintLabel.measureText(mHoursLabel);
<del> mTotalTextWidth += mHoursLabelWidth;
<del> }
<del> if (mMinutes != null) {
<del> mMinutesWidth = mPaintBig.measureText(mMinutes);
<del> mTotalTextWidth += mMinutesWidth;
<del> mMinutesLabelWidth = mPaintLabel.measureText(mMinutesLabel);
<del> mTotalTextWidth += mMinutesLabelWidth;
<del> }
<del> if (mSeconds != null) {
<del> mSecondsWidth = mPaintBigThin.measureText(mSeconds);
<del> mTotalTextWidth += mSecondsWidth;
<del> mSecondsLabelWidth = mPaintLabel.measureText(mSecondsLabel);
<del> mTotalTextWidth += mSecondsLabelWidth;
<del> }
<del> if (mHunderdths != null) {
<del> mHundredthsWidth = mPaintMed.measureText(mHunderdths);
<del> mTotalTextWidth += mHundredthsWidth;
<del> mHundredthsSepWidth = mPaintLabel.measureText(HUNDREDTH_SEPERATOR);
<del> mTotalTextWidth += mHundredthsSepWidth;
<del> }
<del>
<del> // This is a hack: if the text is too wide, reduce all the paint text sizes
<add> calcTotalTextWidth();
<ide> // To determine the maximum width, we find the minimum of the height and width (since the
<ide> // circle we are trying to fit the text into has its radius sized to the smaller of the
<ide> // two.
<ide> int width = Math.min(getWidth(), getHeight());
<ide> if (width != 0) {
<del> float ratio = mTotalTextWidth / width;
<del> if (ratio > TEXT_SIZE_TO_WIDTH_RATIO) {
<del> float sizeRatio = (TEXT_SIZE_TO_WIDTH_RATIO / ratio);
<del> mPaintBig.setTextSize( mPaintBig.getTextSize() * sizeRatio);
<del> mPaintBigThin.setTextSize( mPaintBigThin.getTextSize() * sizeRatio);
<del> mPaintMed.setTextSize( mPaintMed.getTextSize() * sizeRatio);
<del> mTotalTextWidth *= sizeRatio;
<del> mMinutesWidth *= sizeRatio;
<del> mHoursWidth *= sizeRatio;
<del> mSecondsWidth *= sizeRatio;
<del> mHundredthsWidth *= sizeRatio;
<del> mHundredthsSepWidth *= sizeRatio;
<add> float wantWidth = (int)(TEXT_SIZE_TO_WIDTH_RATIO * width);
<add> // If the text is too wide, reduce all the paint text sizes
<add> while (mTotalTextWidth > wantWidth) {
<add> // Get fixed and variant parts of the total size
<add> float fixedWidths = mBigHours.getLabelWidth() + mBigMinutes.getLabelWidth()
<add> + mBigThinSeconds.getLabelWidth() + mMedHundredths.getLabelWidth();
<add> float varWidths = mBigHours.getWidth() + mBigMinutes.getWidth()
<add> + mBigThinSeconds.getWidth() + mMedHundredths.getWidth();
<add> // Avoid divide by zero || sizeRatio == 1 || sizeRatio <= 0
<add> if (varWidths == 0 || fixedWidths == 0 || fixedWidths >= wantWidth) {
<add> break;
<add> }
<add> // Variant-section reduction
<add> float sizeRatio = (wantWidth - fixedWidths) / varWidths;
<add> mPaintBig.setTextSize(mPaintBig.getTextSize() * sizeRatio);
<add> mPaintBigThin.setTextSize(mPaintBigThin.getTextSize() * sizeRatio);
<add> mPaintMed.setTextSize(mPaintMed.getTextSize() * sizeRatio);
<ide> //recalculate the new total text width and half text height
<del> mTotalTextWidth = mHoursWidth + mMinutesWidth + mSecondsWidth +
<del> mHundredthsWidth + mHundredthsSepWidth + mHoursLabelWidth +
<del> mMinutesLabelWidth + mSecondsLabelWidth;
<ide> mTextHeight = mPaintBig.getTextSize();
<add> calcTotalTextWidth();
<ide> }
<ide> }
<ide> }
<ide> public void showTime(boolean visible) {
<ide> mShowTimeStr = visible;
<ide> invalidate();
<del> mRemeasureText = true;
<ide> }
<ide>
<ide> public void redTimeStr(boolean red, boolean forceUpdate) {
<ide> }
<ide>
<ide> public String getTimeString() {
<del> if (mHours == null) {
<del> return String.format("%s:%s.%s",mMinutes, mSeconds, mHunderdths);
<del> }
<del> return String.format("%s:%s:%s.%s",mHours, mMinutes, mSeconds, mHunderdths);
<add> // Though only called from Stopwatch Share, so hundredth are never null,
<add> // protect the future and check for null mHundredths
<add> if (mHundredths == null) {
<add> if (mHours == null) {
<add> return String.format("%s:%s", mMinutes, mSeconds);
<add> }
<add> return String.format("%s:%s:%s", mHours, mMinutes, mSeconds);
<add> } else if (mHours == null) {
<add> return String.format("%s:%s.%s", mMinutes, mSeconds, mHundredths);
<add> }
<add> return String.format("%s:%s:%s.%s", mHours, mMinutes, mSeconds, mHundredths);
<ide> }
<ide>
<ide> private static String getTimeStringForAccessibility(int hours, int minutes, int seconds,
<ide> mPaintMed.setColor(textColor);
<ide>
<ide> if (mHours != null) {
<del> canvas.drawText(mHours, textXstart, textYstart, mPaintBig);
<del> textXstart += mHoursWidth;
<del> canvas.drawText(mHoursLabel, textXstart, labelYStart, mPaintLabel);
<del> textXstart += mHoursLabelWidth;
<add> textXstart = mBigHours.draw(canvas, mHours, textXstart, textYstart, labelYStart);
<ide> }
<ide> if (mMinutes != null) {
<del> canvas.drawText(mMinutes, textXstart, textYstart, mPaintBig);
<del> textXstart += mMinutesWidth;
<del> canvas.drawText(mMinutesLabel, textXstart, labelYStart, mPaintLabel);
<del> textXstart += mMinutesLabelWidth;
<add> textXstart = mBigMinutes.draw(canvas, mMinutes, textXstart, textYstart, labelYStart);
<ide> }
<ide> if (mSeconds != null) {
<del> canvas.drawText(mSeconds, textXstart, textYstart, mPaintBigThin);
<del> textXstart += mSecondsWidth;
<del> canvas.drawText(mSecondsLabel, textXstart, labelYStart, mPaintLabel);
<del> textXstart += mSecondsLabelWidth;
<del> }
<del> if (mHunderdths != null) {
<del> canvas.drawText(HUNDREDTH_SEPERATOR, textXstart, textYstart, mPaintLabel);
<del> textXstart += mHundredthsSepWidth;
<del> canvas.drawText(mHunderdths, textXstart, textYstart, mPaintMed);
<add> textXstart = mBigThinSeconds.draw(canvas, mSeconds,
<add> textXstart, textYstart, labelYStart);
<add> }
<add> if (mHundredths != null) {
<add> textXstart = mMedHundredths.draw(canvas, mHundredths,
<add> textXstart, textYstart, textYstart);
<ide> }
<ide> }
<ide> |
|
Java | unlicense | 5db0d2501d9f5ab0232111f12b7bafb7d2880fc2 | 0 | picodotdev/blog-ejemplos,picodotdev/blog-ejemplos,picodotdev/blog-ejemplos,picodotdev/blog-ejemplos,picodotdev/blog-ejemplos,picodotdev/blog-ejemplos,picodotdev/blog-ejemplos | package io.github.picodotdev.blogbitix.javaexception;
import io.vavr.control.Either;
import io.vavr.control.Try;
import java.util.Optional;
import java.util.concurrent.TransferQueue;
public class Main {
private static int errorCode(boolean error) {
return (error) ? 1 : 0;
}
private static Optional<Integer> optional(boolean error) {
return (error) ? Optional.empty() : Optional.of(0);
}
private static Integer exception(boolean error) throws Exception {
if (error) {
throw new Exception();
} else {
return 0;
}
}
private static Either<Exception, Integer> either(boolean error) {
return (error) ? Either.left(new Exception()) : Either.right(1);
}
public static void main(String[] args) {
int errorCode = errorCode(true);
if (errorCode != 0) {
System.out.printf("Error code: %d%n", errorCode);
}
Optional<Integer> value = optional(true);
if (!value.isPresent()) {
System.out.println("Optional empty");
}
try {
exception(true);
} catch (Exception e) {
e.printStackTrace();
}
Either<Exception, Integer> either = either(true);
if (either.isLeft()) {
System.out.printf("Either exception: %s%n", either.getLeft().getClass().getName());
}
Try.<Integer>of(() -> exception(true)).onFailure(e -> System.out.printf("Try exception: %s%n", e.getClass().getName()));
}
}
| JavaException/src/main/java/io/github/picodotdev/blogbitix/javaexception/Main.java | package io.github.picodotdev.blogbitix.javaexception;
import io.vavr.control.Either;
import java.util.Optional;
public class Main {
private static int errorCode(boolean error) {
return (error) ? 1 : 0;
}
private static Optional<Integer> optional(boolean error) {
return (error) ? Optional.empty() : Optional.of(0);
}
private static void exception(boolean error) throws Exception {
if (error) throw new Exception();
}
private static Either<Exception, Integer> either(boolean error) {
return (error) ? Either.left(new Exception()) : Either.right(1);
}
public static void main(String[] args) {
int errorCode = errorCode(true);
if (errorCode != 0) {
System.out.printf("Error code: %d%n", errorCode);
}
Optional<Integer> value = optional(true);
if (!value.isPresent()) {
System.out.println("Optional empty");
}
try {
exception(true);
} catch (Exception e) {
e.printStackTrace();
}
Either<Exception, Integer> either = either(true);
if (either.isLeft()) {
System.out.printf("Either exception: %s%n", either.getLeft().getClass().getName());
}
}
}
| Pequeños retoques
| JavaException/src/main/java/io/github/picodotdev/blogbitix/javaexception/Main.java | Pequeños retoques | <ide><path>avaException/src/main/java/io/github/picodotdev/blogbitix/javaexception/Main.java
<ide> package io.github.picodotdev.blogbitix.javaexception;
<ide>
<ide> import io.vavr.control.Either;
<add>import io.vavr.control.Try;
<ide>
<ide> import java.util.Optional;
<add>import java.util.concurrent.TransferQueue;
<ide>
<ide> public class Main {
<ide>
<ide> return (error) ? Optional.empty() : Optional.of(0);
<ide> }
<ide>
<del> private static void exception(boolean error) throws Exception {
<del> if (error) throw new Exception();
<add> private static Integer exception(boolean error) throws Exception {
<add> if (error) {
<add> throw new Exception();
<add> } else {
<add> return 0;
<add> }
<ide> }
<ide>
<ide> private static Either<Exception, Integer> either(boolean error) {
<ide> return (error) ? Either.left(new Exception()) : Either.right(1);
<ide> }
<add>
<ide>
<ide> public static void main(String[] args) {
<ide> int errorCode = errorCode(true);
<ide> if (either.isLeft()) {
<ide> System.out.printf("Either exception: %s%n", either.getLeft().getClass().getName());
<ide> }
<add>
<add> Try.<Integer>of(() -> exception(true)).onFailure(e -> System.out.printf("Try exception: %s%n", e.getClass().getName()));
<ide> }
<ide> } |
|
JavaScript | mpl-2.0 | e6844e094c9ed30af1f3bf663ff0f7bc9fa4816b | 0 | arlolra/otr,astorije/otr,nonconforme/otr,sualko/otr,mvayngrib/otr,sualko/otr,astorije/otr,arlolra/otr,mvayngrib/otr,arlolra/otr,nonconforme/otr,arlolra/otr,mvayngrib/otr,sualko/otr,nonconforme/otr,sualko/otr,astorije/otr,astorije/otr,mvayngrib/otr,nonconforme/otr | ;(function () {
"use strict";
var root = this
var CryptoJS, BigInt, EventEmitter, Worker, SMWPath
, CONST, HLP, Parse, AKE, SM, DSA
if (typeof module !== 'undefined' && module.exports) {
module.exports = OTR
CryptoJS = require('../vendor/crypto.js')
BigInt = require('../vendor/bigint.js')
EventEmitter = require('../vendor/eventemitter.js')
SMWPath = require('path').join(__dirname, '/sm-webworker.js')
CONST = require('./const.js')
HLP = require('./helpers.js')
Parse = require('./parse.js')
AKE = require('./ake.js')
SM = require('./sm.js')
DSA = require('./dsa.js')
// expose CONST for consistency with docs
OTR.CONST = CONST
} else {
// copy over and expose internals
Object.keys(root.OTR).forEach(function (k) {
OTR[k] = root.OTR[k]
})
root.OTR = OTR
CryptoJS = root.CryptoJS
BigInt = root.BigInt
EventEmitter = root.EventEmitter
Worker = root.Worker
SMWPath = 'sm-webworker.js'
CONST = OTR.CONST
HLP = OTR.HLP
Parse = OTR.Parse
AKE = OTR.AKE
SM = OTR.SM
DSA = root.DSA
}
// diffie-hellman modulus and generator
// see group 5, RFC 3526
var G = BigInt.str2bigInt(CONST.G, 10)
var N = BigInt.str2bigInt(CONST.N, 16)
// JavaScript integers
var MAX_INT = Math.pow(2, 53) - 1 // doubles
var MAX_UINT = Math.pow(2, 31) - 1 // bitwise operators
// OTR contructor
function OTR(options) {
if (!(this instanceof OTR)) return new OTR(options)
// options
options = options || {}
// private keys
if (options.priv && !(options.priv instanceof DSA))
throw new Error('Requires long-lived DSA key.')
this.priv = options.priv ? options.priv : new DSA()
this.fragment_size = options.fragment_size || 0
if (this.fragment_size < 0)
throw new Error('Fragment size must be a positive integer.')
this.send_interval = options.send_interval || 0
if (this.send_interval < 0)
throw new Error('Send interval must be a positive integer.')
this.outgoing = []
// instance tag
this.our_instance_tag = options.instance_tag || OTR.makeInstanceTag()
// debug
this.debug = !!options.debug
// smp in webworker options
// this is still experimental and undocumented
this.smw = options.smw
// init vals
this.init()
// bind methods
var self = this
;['sendMsg', 'receiveMsg'].forEach(function (meth) {
self[meth] = self[meth].bind(self)
})
EventEmitter.call(this)
}
// inherit from EE
HLP.extend(OTR, EventEmitter)
// add to prototype
OTR.prototype.init = function () {
this.msgstate = CONST.MSGSTATE_PLAINTEXT
this.authstate = CONST.AUTHSTATE_NONE
this.ALLOW_V2 = true
this.ALLOW_V3 = true
this.REQUIRE_ENCRYPTION = false
this.SEND_WHITESPACE_TAG = false
this.WHITESPACE_START_AKE = false
this.ERROR_START_AKE = false
Parse.initFragment(this)
// their keys
this.their_y = null
this.their_old_y = null
this.their_keyid = 0
this.their_priv_pk = null
this.their_instance_tag = '\x00\x00\x00\x00'
// our keys
this.our_dh = this.dh()
this.our_old_dh = this.dh()
this.our_keyid = 2
// session keys
this.sessKeys = [ new Array(2), new Array(2) ]
// saved
this.storedMgs = []
this.oldMacKeys = []
// smp
this.sm = null // initialized after AKE
// when ake is complete
// save their keys and the session
this._akeInit()
// receive plaintext message since switching to plaintext
// used to decide when to stop sending pt tags when SEND_WHITESPACE_TAG
this.receivedPlaintext = false
}
OTR.prototype._akeInit = function () {
this.ake = new AKE(this)
this.transmittedRS = false
this.ssid = null
}
// smp over webworker
OTR.prototype._SMW = function (otr, reqs) {
this.otr = otr
var opts = {
path: SMWPath
, seed: BigInt.getSeed
}
if (typeof otr.smw === 'object')
Object.keys(otr.smw).forEach(function (k) {
opts[k] = otr.smw[k]
})
// load optional dep. in node
if (typeof module !== 'undefined' && module.exports)
Worker = require('webworker-threads').Worker
this.worker = new Worker(opts.path)
var self = this
this.worker.onmessage = function (e) {
var d = e.data
if (!d) return
self.trigger(d.method, d.args)
}
this.worker.postMessage({
type: 'seed'
, seed: opts.seed()
, imports: opts.imports
})
this.worker.postMessage({
type: 'init'
, reqs: reqs
})
}
// inherit from EE
HLP.extend(OTR.prototype._SMW, EventEmitter)
// shim sm methods
;['handleSM', 'rcvSecret', 'abort'].forEach(function (m) {
OTR.prototype._SMW.prototype[m] = function () {
this.worker.postMessage({
type: 'method'
, method: m
, args: Array.prototype.slice.call(arguments, 0)
})
}
})
OTR.prototype._smInit = function () {
var reqs = {
ssid: this.ssid
, our_fp: this.priv.fingerprint()
, their_fp: this.their_priv_pk.fingerprint()
, debug: this.debug
}
if (this.smw) {
if (this.sm) this.sm.worker.terminate() // destroy prev webworker
this.sm = new this._SMW(this, reqs)
} else {
this.sm = new SM(reqs)
}
var self = this
;['trust', 'abort', 'question'].forEach(function (e) {
self.sm.on(e, function () {
self.trigger('smp', [e].concat(Array.prototype.slice.call(arguments)))
})
})
this.sm.on('send', function (ssid, send) {
if (self.ssid === ssid) {
send = self.prepareMsg(send)
self.io(send)
}
})
}
OTR.prototype.io = function (msg, meta) {
// buffer
msg = ([].concat(msg)).map(function(m){
return { msg: m, meta: meta }
})
this.outgoing = this.outgoing.concat(msg)
var self = this
;(function send(first) {
if (!first) {
if (!self.outgoing.length) return
var elem = self.outgoing.shift()
self.trigger('io', [elem.msg, elem.meta])
}
setTimeout(send, first ? 0 : self.send_interval)
}(true))
}
OTR.prototype.dh = function dh() {
var keys = { privateKey: BigInt.randBigInt(320) }
keys.publicKey = BigInt.powMod(G, keys.privateKey, N)
return keys
}
// session constructor
OTR.prototype.DHSession = function DHSession(our_dh, their_y) {
if (!(this instanceof DHSession)) return new DHSession(our_dh, their_y)
// shared secret
var s = BigInt.powMod(their_y, our_dh.privateKey, N)
var secbytes = HLP.packMPI(s)
// session id
this.id = HLP.mask(HLP.h2('\x00', secbytes), 0, 64) // first 64-bits
// are we the high or low end of the connection?
var sq = BigInt.greater(our_dh.publicKey, their_y)
var sendbyte = sq ? '\x01' : '\x02'
var rcvbyte = sq ? '\x02' : '\x01'
// sending and receiving keys
this.sendenc = HLP.mask(HLP.h1(sendbyte, secbytes), 0, 128) // f16 bytes
this.sendmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.sendenc))
this.sendmac = this.sendmac.toString(CryptoJS.enc.Latin1)
this.rcvenc = HLP.mask(HLP.h1(rcvbyte, secbytes), 0, 128)
this.rcvmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.rcvenc))
this.rcvmac = this.rcvmac.toString(CryptoJS.enc.Latin1)
this.rcvmacused = false
// extra symmetric key
this.extra_symkey = HLP.h2('\xff', secbytes)
// counters
this.send_counter = 0
this.rcv_counter = 0
}
OTR.prototype.rotateOurKeys = function () {
// reveal old mac keys
var self = this
this.sessKeys[1].forEach(function (sk) {
if (sk && sk.rcvmacused) self.oldMacKeys.push(sk.rcvmac)
})
// rotate our keys
this.our_old_dh = this.our_dh
this.our_dh = this.dh()
this.our_keyid += 1
this.sessKeys[1][0] = this.sessKeys[0][0]
this.sessKeys[1][1] = this.sessKeys[0][1]
this.sessKeys[0] = [
this.their_y ?
new this.DHSession(this.our_dh, this.their_y) : null
, this.their_old_y ?
new this.DHSession(this.our_dh, this.their_old_y) : null
]
}
OTR.prototype.rotateTheirKeys = function (their_y) {
// increment their keyid
this.their_keyid += 1
// reveal old mac keys
var self = this
this.sessKeys.forEach(function (sk) {
if (sk[1] && sk[1].rcvmacused) self.oldMacKeys.push(sk[1].rcvmac)
})
// rotate their keys / session
this.their_old_y = this.their_y
this.sessKeys[0][1] = this.sessKeys[0][0]
this.sessKeys[1][1] = this.sessKeys[1][0]
// new keys / sessions
this.their_y = their_y
this.sessKeys[0][0] = new this.DHSession(this.our_dh, this.their_y)
this.sessKeys[1][0] = new this.DHSession(this.our_old_dh, this.their_y)
}
OTR.prototype.prepareMsg = function (msg, esk) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED || this.their_keyid === 0)
return this.error('Not ready to encrypt.')
var sessKeys = this.sessKeys[1][0]
if (sessKeys.send_counter >= MAX_INT)
return this.error('Should have rekeyed by now.')
sessKeys.send_counter += 1
var ctr = HLP.packCtr(sessKeys.send_counter)
var send = this.ake.otr_version + '\x03' // version and type
var v3 = (this.ake.otr_version === CONST.OTR_VERSION_3)
if (v3) {
send += this.our_instance_tag
send += this.their_instance_tag
}
send += '\x00' // flag
send += HLP.packINT(this.our_keyid - 1)
send += HLP.packINT(this.their_keyid)
send += HLP.packMPI(this.our_dh.publicKey)
send += ctr.substring(0, 8)
if (Math.ceil(msg.length / 8) >= MAX_UINT) // * 16 / 128
return this.error('Message is too long.')
var aes = HLP.encryptAes(
CryptoJS.enc.Latin1.parse(msg)
, sessKeys.sendenc
, ctr
)
send += HLP.packData(aes)
send += HLP.make1Mac(send, sessKeys.sendmac)
send += HLP.packData(this.oldMacKeys.splice(0).join(''))
send = HLP.wrapMsg(
send
, this.fragment_size
, v3
, this.our_instance_tag
, this.their_instance_tag
)
if (send[0]) return this.error(send[0])
// emit extra symmetric key
if (esk) this.trigger('file', ['send', sessKeys.extra_symkey, esk])
return send[1]
}
OTR.prototype.handleDataMsg = function (msg) {
var vt = msg.version + msg.type
if (this.ake.otr_version === CONST.OTR_VERSION_3)
vt += msg.instance_tags
var types = ['BYTE', 'INT', 'INT', 'MPI', 'CTR', 'DATA', 'MAC', 'DATA']
msg = HLP.splitype(types, msg.msg)
// ignore flag
var ign = (msg[0] === '\x01')
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED || msg.length !== 8) {
if (!ign) this.error('Received an unreadable encrypted message.', true)
return
}
var our_keyid = this.our_keyid - HLP.readLen(msg[2])
var their_keyid = this.their_keyid - HLP.readLen(msg[1])
if (our_keyid < 0 || our_keyid > 1) {
if (!ign) this.error('Not of our latest keys.', true)
return
}
if (their_keyid < 0 || their_keyid > 1) {
if (!ign) this.error('Not of your latest keys.', true)
return
}
var their_y = their_keyid ? this.their_old_y : this.their_y
if (their_keyid === 1 && !their_y) {
if (!ign) this.error('Do not have that key.')
return
}
var sessKeys = this.sessKeys[our_keyid][their_keyid]
var ctr = HLP.unpackCtr(msg[4])
if (ctr <= sessKeys.rcv_counter) {
if (!ign) this.error('Counter in message is not larger.')
return
}
sessKeys.rcv_counter = ctr
// verify mac
vt += msg.slice(0, 6).join('')
var vmac = HLP.make1Mac(vt, sessKeys.rcvmac)
if (!HLP.compare(msg[6], vmac)) {
if (!ign) this.error('MACs do not match.')
return
}
sessKeys.rcvmacused = true
var out = HLP.decryptAes(
msg[5].substring(4)
, sessKeys.rcvenc
, HLP.padCtr(msg[4])
)
out = out.toString(CryptoJS.enc.Latin1)
if (!our_keyid) this.rotateOurKeys()
if (!their_keyid) this.rotateTheirKeys(HLP.readMPI(msg[3]))
// parse TLVs
var ind = out.indexOf('\x00')
if (~ind) {
this.handleTLVs(out.substring(ind + 1), sessKeys)
out = out.substring(0, ind)
}
out = CryptoJS.enc.Latin1.parse(out)
return out.toString(CryptoJS.enc.Utf8)
}
OTR.prototype.handleTLVs = function (tlvs, sessKeys) {
var type, len, msg
for (; tlvs.length; ) {
type = HLP.unpackSHORT(tlvs.substr(0, 2))
len = HLP.unpackSHORT(tlvs.substr(2, 2))
msg = tlvs.substr(4, len)
// TODO: handle pathological cases better
if (msg.length < len) break
switch (type) {
case 1:
// Disconnected
this.msgstate = CONST.MSGSTATE_FINISHED
this.trigger('status', [CONST.STATUS_END_OTR])
break
case 2: case 3: case 4:
case 5: case 6: case 7:
// SMP
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED) {
if (this.sm) this.sm.abort()
return
}
if (!this.sm) this._smInit()
this.sm.handleSM({ msg: msg, type: type })
break
case 8:
// utf8 filenames
msg = msg.substring(4) // remove 4-byte indication
msg = CryptoJS.enc.Latin1.parse(msg)
msg = msg.toString(CryptoJS.enc.Utf8)
// Extra Symkey
this.trigger('file', ['receive', sessKeys.extra_symkey, msg])
break
}
tlvs = tlvs.substring(4 + len)
}
}
OTR.prototype.smpSecret = function (secret, question) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED)
return this.error('Must be encrypted for SMP.')
if (typeof secret !== 'string' || secret.length < 1)
return this.error('Secret is required.')
if (!this.sm) this._smInit()
// utf8 inputs
secret = CryptoJS.enc.Utf8.parse(secret).toString(CryptoJS.enc.Latin1)
question = CryptoJS.enc.Utf8.parse(question).toString(CryptoJS.enc.Latin1)
this.sm.rcvSecret(secret, question)
}
OTR.prototype.sendQueryMsg = function () {
var versions = {}
, msg = CONST.OTR_TAG
if (this.ALLOW_V2) versions['2'] = true
if (this.ALLOW_V3) versions['3'] = true
// but we don't allow v1
// if (versions['1']) msg += '?'
var vs = Object.keys(versions)
if (vs.length) {
msg += 'v'
vs.forEach(function (v) {
if (v !== '1') msg += v
})
msg += '?'
}
this.io(msg)
this.trigger('status', [CONST.STATUS_SEND_QUERY])
}
OTR.prototype.sendMsg = function (msg, meta) {
if ( this.REQUIRE_ENCRYPTION ||
this.msgstate !== CONST.MSGSTATE_PLAINTEXT
) {
msg = CryptoJS.enc.Utf8.parse(msg)
msg = msg.toString(CryptoJS.enc.Latin1)
}
switch (this.msgstate) {
case CONST.MSGSTATE_PLAINTEXT:
if (this.REQUIRE_ENCRYPTION) {
this.storedMgs.push({msg: msg, meta: meta})
this.sendQueryMsg()
return
}
if (this.SEND_WHITESPACE_TAG && !this.receivedPlaintext) {
msg += CONST.WHITESPACE_TAG // 16 byte tag
if (this.ALLOW_V3) msg += CONST.WHITESPACE_TAG_V3
if (this.ALLOW_V2) msg += CONST.WHITESPACE_TAG_V2
}
break
case CONST.MSGSTATE_FINISHED:
this.storedMgs.push({msg: msg, meta: meta})
this.error('Message cannot be sent at this time.')
return
case CONST.MSGSTATE_ENCRYPTED:
msg = this.prepareMsg(msg)
break
default:
throw new Error('Unknown message state.')
}
if (msg) this.io(msg, meta)
}
OTR.prototype.receiveMsg = function (msg) {
// parse type
msg = Parse.parseMsg(this, msg)
if (!msg) return
switch (msg.cls) {
case 'error':
this.error(msg.msg)
return
case 'ake':
if ( msg.version === CONST.OTR_VERSION_3 &&
this.checkInstanceTags(msg.instance_tags)
) return // ignore
this.ake.handleAKE(msg)
return
case 'data':
if ( msg.version === CONST.OTR_VERSION_3 &&
this.checkInstanceTags(msg.instance_tags)
) return // ignore
msg.msg = this.handleDataMsg(msg)
msg.encrypted = true
break
case 'query':
if (this.msgstate === CONST.MSGSTATE_ENCRYPTED) this._akeInit()
this.doAKE(msg)
break
default:
// check for encrypted
if ( this.REQUIRE_ENCRYPTION ||
this.msgstate !== CONST.MSGSTATE_PLAINTEXT
) this.error('Received an unencrypted message.')
// received a plaintext message
// stop sending the whitespace tag
this.receivedPlaintext = true
// received a whitespace tag
if (this.WHITESPACE_START_AKE && msg.ver.length > 0)
this.doAKE(msg)
}
if (msg.msg) this.trigger('ui', [msg.msg, !!msg.encrypted])
}
OTR.prototype.checkInstanceTags = function (it) {
var their_it = HLP.readLen(it.substr(0, 4))
var our_it = HLP.readLen(it.substr(4, 4))
if (our_it && our_it !== HLP.readLen(this.our_instance_tag))
return true
if (HLP.readLen(this.their_instance_tag)) {
if (HLP.readLen(this.their_instance_tag) !== their_it) return true
} else {
if (their_it < 100) return true
this.their_instance_tag = HLP.packINT(their_it)
}
}
OTR.prototype.doAKE = function (msg) {
if (this.ALLOW_V3 && ~msg.ver.indexOf(CONST.OTR_VERSION_3)) {
this.ake.initiateAKE(CONST.OTR_VERSION_3)
} else if (this.ALLOW_V2 && ~msg.ver.indexOf(CONST.OTR_VERSION_2)) {
this.ake.initiateAKE(CONST.OTR_VERSION_2)
} else {
// is this an error?
this.error('OTR conversation requested, ' +
'but no compatible protocol version found.')
}
}
OTR.prototype.error = function (err, send) {
if (send) {
if (!this.debug) err = "An OTR error has occurred."
err = '?OTR Error:' + err
this.io(err)
return
}
this.trigger('error', [err])
}
OTR.prototype.sendStored = function () {
var self = this
;(this.storedMgs.splice(0)).forEach(function (elem) {
var msg = self.prepareMsg(elem.msg)
self.io(msg, elem.meta)
})
}
OTR.prototype.sendFile = function (filename) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED)
return this.error('Not ready to encrypt.')
if (this.ake.otr_version !== CONST.OTR_VERSION_3)
return this.error('Protocol v3 required.')
if (!filename) return this.error('Please specify a filename.')
// utf8 filenames
var l1name = CryptoJS.enc.Utf8.parse(filename)
l1name = l1name.toString(CryptoJS.enc.Latin1)
if (l1name.length >= 65532) return this.error('filename is too long.')
var msg = '\x00' // null byte
msg += '\x00\x08' // type 8 tlv
msg += HLP.packSHORT(4 + l1name.length) // length of value
msg += '\x00\x00\x00\x01' // four bytes indicating file
msg += l1name
msg = this.prepareMsg(msg, filename)
this.io(msg)
}
OTR.prototype.endOtr = function () {
if (this.msgstate === CONST.MSGSTATE_ENCRYPTED) {
this.sendMsg('\x00\x00\x01\x00\x00')
if (this.sm) {
if (this.smw) this.sm.worker.terminate() // destroy webworker
this.sm = null
}
}
this.msgstate = CONST.MSGSTATE_PLAINTEXT
this.receivedPlaintext = false
this.trigger('status', [CONST.STATUS_END_OTR])
}
// attach methods
OTR.makeInstanceTag = function () {
var num = BigInt.randBigInt(32)
if (BigInt.greater(BigInt.str2bigInt('100', 16), num))
return OTR.makeInstanceTag()
return HLP.packINT(parseInt(BigInt.bigInt2str(num, 10), 10))
}
}).call(this)
| lib/otr.js | ;(function () {
"use strict";
var root = this
var CryptoJS, BigInt, EventEmitter, Worker, SMWPath
, CONST, HLP, Parse, AKE, SM, DSA
if (typeof module !== 'undefined' && module.exports) {
module.exports = OTR
CryptoJS = require('../vendor/crypto.js')
BigInt = require('../vendor/bigint.js')
EventEmitter = require('../vendor/eventemitter.js')
SMWPath = require('path').join(__dirname, '/sm-webworker.js')
CONST = require('./const.js')
HLP = require('./helpers.js')
Parse = require('./parse.js')
AKE = require('./ake.js')
SM = require('./sm.js')
DSA = require('./dsa.js')
// expose CONST for consistency with docs
OTR.CONST = CONST
} else {
// copy over and expose internals
Object.keys(root.OTR).forEach(function (k) {
OTR[k] = root.OTR[k]
})
root.OTR = OTR
CryptoJS = root.CryptoJS
BigInt = root.BigInt
EventEmitter = root.EventEmitter
Worker = root.Worker
SMWPath = 'sm-webworker.js'
CONST = OTR.CONST
HLP = OTR.HLP
Parse = OTR.Parse
AKE = OTR.AKE
SM = OTR.SM
DSA = root.DSA
}
// diffie-hellman modulus and generator
// see group 5, RFC 3526
var G = BigInt.str2bigInt(CONST.G, 10)
var N = BigInt.str2bigInt(CONST.N, 16)
// JavaScript integers
var MAX_INT = Math.pow(2, 53) - 1 // doubles
var MAX_UINT = Math.pow(2, 31) - 1 // bitwise operators
// OTR contructor
function OTR(options) {
if (!(this instanceof OTR)) return new OTR(options)
// options
options = options || {}
// private keys
if (options.priv && !(options.priv instanceof DSA))
throw new Error('Requires long-lived DSA key.')
this.priv = options.priv ? options.priv : new DSA()
this.fragment_size = options.fragment_size || 0
if (this.fragment_size < 0)
throw new Error('Fragment size must be a positive integer.')
this.send_interval = options.send_interval || 0
if (this.send_interval < 0)
throw new Error('Send interval must be a positive integer.')
this.outgoing = []
// instance tag
this.our_instance_tag = options.instance_tag || OTR.makeInstanceTag()
// debug
this.debug = !!options.debug
// smp in webworker options
// this is still experimental and undocumented
this.smw = options.smw
// init vals
this.init()
// bind methods
var self = this
;['sendMsg', 'receiveMsg'].forEach(function (meth) {
self[meth] = self[meth].bind(self)
})
EventEmitter.call(this)
}
// inherit from EE
HLP.extend(OTR, EventEmitter)
// add to prototype
OTR.prototype.init = function () {
this.msgstate = CONST.MSGSTATE_PLAINTEXT
this.authstate = CONST.AUTHSTATE_NONE
this.ALLOW_V2 = true
this.ALLOW_V3 = true
this.REQUIRE_ENCRYPTION = false
this.SEND_WHITESPACE_TAG = false
this.WHITESPACE_START_AKE = false
this.ERROR_START_AKE = false
Parse.initFragment(this)
// their keys
this.their_y = null
this.their_old_y = null
this.their_keyid = 0
this.their_priv_pk = null
this.their_instance_tag = '\x00\x00\x00\x00'
// our keys
this.our_dh = this.dh()
this.our_old_dh = this.dh()
this.our_keyid = 2
// session keys
this.sessKeys = [ new Array(2), new Array(2) ]
// saved
this.storedMgs = []
this.oldMacKeys = []
// smp
this.sm = null // initialized after AKE
// when ake is complete
// save their keys and the session
this._akeInit()
// receive plaintext message since switching to plaintext
// used to decide when to stop sending pt tags when SEND_WHITESPACE_TAG
this.receivedPlaintext = false
}
OTR.prototype._akeInit = function () {
this.ake = new AKE(this)
this.transmittedRS = false
this.ssid = null
}
// smp over webworker
OTR.prototype._SMW = function (otr, reqs) {
this.otr = otr
var opts = {
path: SMWPath
, seed: BigInt.getSeed
}
if (typeof otr.smw === 'object')
Object.keys(otr.smw).forEach(function (k) {
opts[k] = otr.smw[k]
})
// load optional dep. in node
if (typeof module !== 'undefined' && module.exports)
Worker = require('webworker-threads').Worker
this.worker = new Worker(opts.path)
var self = this
this.worker.onmessage = function (e) {
var d = e.data
if (!d) return
self.trigger(d.method, d.args)
}
this.worker.postMessage({
type: 'seed'
, seed: opts.seed()
, imports: opts.imports
})
this.worker.postMessage({
type: 'init'
, reqs: reqs
})
}
// inherit from EE
HLP.extend(OTR.prototype._SMW, EventEmitter)
// shim sm methods
;['handleSM', 'rcvSecret', 'abort'].forEach(function (m) {
OTR.prototype._SMW.prototype[m] = function () {
this.worker.postMessage({
type: 'method'
, method: m
, args: Array.prototype.slice.call(arguments, 0)
})
}
})
OTR.prototype._smInit = function () {
var reqs = {
ssid: this.ssid
, our_fp: this.priv.fingerprint()
, their_fp: this.their_priv_pk.fingerprint()
, debug: this.debug
}
if (this.smw) {
if (this.sm) this.sm.worker.terminate() // destroy prev webworker
this.sm = new this._SMW(this, reqs)
} else {
this.sm = new SM(reqs)
}
var self = this
;['trust', 'abort', 'question'].forEach(function (e) {
self.sm.on(e, function () {
self.trigger('smp', [e].concat(Array.prototype.slice.call(arguments)))
})
})
this.sm.on('send', function (ssid, send) {
if (self.ssid === ssid) {
send = self.prepareMsg(send)
self.io(send)
}
})
}
OTR.prototype.io = function (msg, meta) {
// buffer
msg = ([].concat(msg)).map(function(m){
return { msg: m, meta: meta }
})
this.outgoing = this.outgoing.concat(msg)
var self = this
;(function send(first) {
if (!first) {
if (!self.outgoing.length) return
var elem = self.outgoing.shift()
self.trigger('io', [elem.msg, elem.meta])
}
setTimeout(send, first ? 0 : self.send_interval)
}(true))
}
OTR.prototype.dh = function dh() {
var keys = { privateKey: BigInt.randBigInt(320) }
keys.publicKey = BigInt.powMod(G, keys.privateKey, N)
return keys
}
// session constructor
OTR.prototype.DHSession = function DHSession(our_dh, their_y) {
if (!(this instanceof DHSession)) return new DHSession(our_dh, their_y)
// shared secret
var s = BigInt.powMod(their_y, our_dh.privateKey, N)
var secbytes = HLP.packMPI(s)
// session id
this.id = HLP.mask(HLP.h2('\x00', secbytes), 0, 64) // first 64-bits
// are we the high or low end of the connection?
var sq = BigInt.greater(our_dh.publicKey, their_y)
var sendbyte = sq ? '\x01' : '\x02'
var rcvbyte = sq ? '\x02' : '\x01'
// sending and receiving keys
this.sendenc = HLP.mask(HLP.h1(sendbyte, secbytes), 0, 128) // f16 bytes
this.sendmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.sendenc))
this.sendmac = this.sendmac.toString(CryptoJS.enc.Latin1)
this.sendmacused = false
this.rcvenc = HLP.mask(HLP.h1(rcvbyte, secbytes), 0, 128)
this.rcvmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.rcvenc))
this.rcvmac = this.rcvmac.toString(CryptoJS.enc.Latin1)
this.rcvmacused = false
// extra symmetric key
this.extra_symkey = HLP.h2('\xff', secbytes)
// counters
this.send_counter = 0
this.rcv_counter = 0
}
OTR.prototype.rotateOurKeys = function () {
// reveal old mac keys
var self = this
this.sessKeys[1].forEach(function (sk) {
if (sk && sk.sendmacused) self.oldMacKeys.push(sk.sendmac)
if (sk && sk.rcvmacused) self.oldMacKeys.push(sk.rcvmac)
})
// rotate our keys
this.our_old_dh = this.our_dh
this.our_dh = this.dh()
this.our_keyid += 1
this.sessKeys[1][0] = this.sessKeys[0][0]
this.sessKeys[1][1] = this.sessKeys[0][1]
this.sessKeys[0] = [
this.their_y ?
new this.DHSession(this.our_dh, this.their_y) : null
, this.their_old_y ?
new this.DHSession(this.our_dh, this.their_old_y) : null
]
}
OTR.prototype.rotateTheirKeys = function (their_y) {
// increment their keyid
this.their_keyid += 1
// reveal old mac keys
var self = this
this.sessKeys.forEach(function (sk) {
if (sk[1] && sk[1].sendmacused) self.oldMacKeys.push(sk[1].sendmac)
if (sk[1] && sk[1].rcvmacused) self.oldMacKeys.push(sk[1].rcvmac)
})
// rotate their keys / session
this.their_old_y = this.their_y
this.sessKeys[0][1] = this.sessKeys[0][0]
this.sessKeys[1][1] = this.sessKeys[1][0]
// new keys / sessions
this.their_y = their_y
this.sessKeys[0][0] = new this.DHSession(this.our_dh, this.their_y)
this.sessKeys[1][0] = new this.DHSession(this.our_old_dh, this.their_y)
}
OTR.prototype.prepareMsg = function (msg, esk) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED || this.their_keyid === 0)
return this.error('Not ready to encrypt.')
var sessKeys = this.sessKeys[1][0]
if (sessKeys.send_counter >= MAX_INT)
return this.error('Should have rekeyed by now.')
sessKeys.send_counter += 1
var ctr = HLP.packCtr(sessKeys.send_counter)
var send = this.ake.otr_version + '\x03' // version and type
var v3 = (this.ake.otr_version === CONST.OTR_VERSION_3)
if (v3) {
send += this.our_instance_tag
send += this.their_instance_tag
}
send += '\x00' // flag
send += HLP.packINT(this.our_keyid - 1)
send += HLP.packINT(this.their_keyid)
send += HLP.packMPI(this.our_dh.publicKey)
send += ctr.substring(0, 8)
if (Math.ceil(msg.length / 8) >= MAX_UINT) // * 16 / 128
return this.error('Message is too long.')
var aes = HLP.encryptAes(
CryptoJS.enc.Latin1.parse(msg)
, sessKeys.sendenc
, ctr
)
send += HLP.packData(aes)
send += HLP.make1Mac(send, sessKeys.sendmac)
send += HLP.packData(this.oldMacKeys.splice(0).join(''))
sessKeys.sendmacused = true
send = HLP.wrapMsg(
send
, this.fragment_size
, v3
, this.our_instance_tag
, this.their_instance_tag
)
if (send[0]) return this.error(send[0])
// emit extra symmetric key
if (esk) this.trigger('file', ['send', sessKeys.extra_symkey, esk])
return send[1]
}
OTR.prototype.handleDataMsg = function (msg) {
var vt = msg.version + msg.type
if (this.ake.otr_version === CONST.OTR_VERSION_3)
vt += msg.instance_tags
var types = ['BYTE', 'INT', 'INT', 'MPI', 'CTR', 'DATA', 'MAC', 'DATA']
msg = HLP.splitype(types, msg.msg)
// ignore flag
var ign = (msg[0] === '\x01')
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED || msg.length !== 8) {
if (!ign) this.error('Received an unreadable encrypted message.', true)
return
}
var our_keyid = this.our_keyid - HLP.readLen(msg[2])
var their_keyid = this.their_keyid - HLP.readLen(msg[1])
if (our_keyid < 0 || our_keyid > 1) {
if (!ign) this.error('Not of our latest keys.', true)
return
}
if (their_keyid < 0 || their_keyid > 1) {
if (!ign) this.error('Not of your latest keys.', true)
return
}
var their_y = their_keyid ? this.their_old_y : this.their_y
if (their_keyid === 1 && !their_y) {
if (!ign) this.error('Do not have that key.')
return
}
var sessKeys = this.sessKeys[our_keyid][their_keyid]
var ctr = HLP.unpackCtr(msg[4])
if (ctr <= sessKeys.rcv_counter) {
if (!ign) this.error('Counter in message is not larger.')
return
}
sessKeys.rcv_counter = ctr
// verify mac
vt += msg.slice(0, 6).join('')
var vmac = HLP.make1Mac(vt, sessKeys.rcvmac)
if (!HLP.compare(msg[6], vmac)) {
if (!ign) this.error('MACs do not match.')
return
}
sessKeys.rcvmacused = true
var out = HLP.decryptAes(
msg[5].substring(4)
, sessKeys.rcvenc
, HLP.padCtr(msg[4])
)
out = out.toString(CryptoJS.enc.Latin1)
if (!our_keyid) this.rotateOurKeys()
if (!their_keyid) this.rotateTheirKeys(HLP.readMPI(msg[3]))
// parse TLVs
var ind = out.indexOf('\x00')
if (~ind) {
this.handleTLVs(out.substring(ind + 1), sessKeys)
out = out.substring(0, ind)
}
out = CryptoJS.enc.Latin1.parse(out)
return out.toString(CryptoJS.enc.Utf8)
}
OTR.prototype.handleTLVs = function (tlvs, sessKeys) {
var type, len, msg
for (; tlvs.length; ) {
type = HLP.unpackSHORT(tlvs.substr(0, 2))
len = HLP.unpackSHORT(tlvs.substr(2, 2))
msg = tlvs.substr(4, len)
// TODO: handle pathological cases better
if (msg.length < len) break
switch (type) {
case 1:
// Disconnected
this.msgstate = CONST.MSGSTATE_FINISHED
this.trigger('status', [CONST.STATUS_END_OTR])
break
case 2: case 3: case 4:
case 5: case 6: case 7:
// SMP
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED) {
if (this.sm) this.sm.abort()
return
}
if (!this.sm) this._smInit()
this.sm.handleSM({ msg: msg, type: type })
break
case 8:
// utf8 filenames
msg = msg.substring(4) // remove 4-byte indication
msg = CryptoJS.enc.Latin1.parse(msg)
msg = msg.toString(CryptoJS.enc.Utf8)
// Extra Symkey
this.trigger('file', ['receive', sessKeys.extra_symkey, msg])
break
}
tlvs = tlvs.substring(4 + len)
}
}
OTR.prototype.smpSecret = function (secret, question) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED)
return this.error('Must be encrypted for SMP.')
if (typeof secret !== 'string' || secret.length < 1)
return this.error('Secret is required.')
if (!this.sm) this._smInit()
// utf8 inputs
secret = CryptoJS.enc.Utf8.parse(secret).toString(CryptoJS.enc.Latin1)
question = CryptoJS.enc.Utf8.parse(question).toString(CryptoJS.enc.Latin1)
this.sm.rcvSecret(secret, question)
}
OTR.prototype.sendQueryMsg = function () {
var versions = {}
, msg = CONST.OTR_TAG
if (this.ALLOW_V2) versions['2'] = true
if (this.ALLOW_V3) versions['3'] = true
// but we don't allow v1
// if (versions['1']) msg += '?'
var vs = Object.keys(versions)
if (vs.length) {
msg += 'v'
vs.forEach(function (v) {
if (v !== '1') msg += v
})
msg += '?'
}
this.io(msg)
this.trigger('status', [CONST.STATUS_SEND_QUERY])
}
OTR.prototype.sendMsg = function (msg, meta) {
if ( this.REQUIRE_ENCRYPTION ||
this.msgstate !== CONST.MSGSTATE_PLAINTEXT
) {
msg = CryptoJS.enc.Utf8.parse(msg)
msg = msg.toString(CryptoJS.enc.Latin1)
}
switch (this.msgstate) {
case CONST.MSGSTATE_PLAINTEXT:
if (this.REQUIRE_ENCRYPTION) {
this.storedMgs.push({msg: msg, meta: meta})
this.sendQueryMsg()
return
}
if (this.SEND_WHITESPACE_TAG && !this.receivedPlaintext) {
msg += CONST.WHITESPACE_TAG // 16 byte tag
if (this.ALLOW_V3) msg += CONST.WHITESPACE_TAG_V3
if (this.ALLOW_V2) msg += CONST.WHITESPACE_TAG_V2
}
break
case CONST.MSGSTATE_FINISHED:
this.storedMgs.push({msg: msg, meta: meta})
this.error('Message cannot be sent at this time.')
return
case CONST.MSGSTATE_ENCRYPTED:
msg = this.prepareMsg(msg)
break
default:
throw new Error('Unknown message state.')
}
if (msg) this.io(msg, meta)
}
OTR.prototype.receiveMsg = function (msg) {
// parse type
msg = Parse.parseMsg(this, msg)
if (!msg) return
switch (msg.cls) {
case 'error':
this.error(msg.msg)
return
case 'ake':
if ( msg.version === CONST.OTR_VERSION_3 &&
this.checkInstanceTags(msg.instance_tags)
) return // ignore
this.ake.handleAKE(msg)
return
case 'data':
if ( msg.version === CONST.OTR_VERSION_3 &&
this.checkInstanceTags(msg.instance_tags)
) return // ignore
msg.msg = this.handleDataMsg(msg)
msg.encrypted = true
break
case 'query':
if (this.msgstate === CONST.MSGSTATE_ENCRYPTED) this._akeInit()
this.doAKE(msg)
break
default:
// check for encrypted
if ( this.REQUIRE_ENCRYPTION ||
this.msgstate !== CONST.MSGSTATE_PLAINTEXT
) this.error('Received an unencrypted message.')
// received a plaintext message
// stop sending the whitespace tag
this.receivedPlaintext = true
// received a whitespace tag
if (this.WHITESPACE_START_AKE && msg.ver.length > 0)
this.doAKE(msg)
}
if (msg.msg) this.trigger('ui', [msg.msg, !!msg.encrypted])
}
OTR.prototype.checkInstanceTags = function (it) {
var their_it = HLP.readLen(it.substr(0, 4))
var our_it = HLP.readLen(it.substr(4, 4))
if (our_it && our_it !== HLP.readLen(this.our_instance_tag))
return true
if (HLP.readLen(this.their_instance_tag)) {
if (HLP.readLen(this.their_instance_tag) !== their_it) return true
} else {
if (their_it < 100) return true
this.their_instance_tag = HLP.packINT(their_it)
}
}
OTR.prototype.doAKE = function (msg) {
if (this.ALLOW_V3 && ~msg.ver.indexOf(CONST.OTR_VERSION_3)) {
this.ake.initiateAKE(CONST.OTR_VERSION_3)
} else if (this.ALLOW_V2 && ~msg.ver.indexOf(CONST.OTR_VERSION_2)) {
this.ake.initiateAKE(CONST.OTR_VERSION_2)
} else {
// is this an error?
this.error('OTR conversation requested, ' +
'but no compatible protocol version found.')
}
}
OTR.prototype.error = function (err, send) {
if (send) {
if (!this.debug) err = "An OTR error has occurred."
err = '?OTR Error:' + err
this.io(err)
return
}
this.trigger('error', [err])
}
OTR.prototype.sendStored = function () {
var self = this
;(this.storedMgs.splice(0)).forEach(function (elem) {
var msg = self.prepareMsg(elem.msg)
self.io(msg, elem.meta)
})
}
OTR.prototype.sendFile = function (filename) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED)
return this.error('Not ready to encrypt.')
if (this.ake.otr_version !== CONST.OTR_VERSION_3)
return this.error('Protocol v3 required.')
if (!filename) return this.error('Please specify a filename.')
// utf8 filenames
var l1name = CryptoJS.enc.Utf8.parse(filename)
l1name = l1name.toString(CryptoJS.enc.Latin1)
if (l1name.length >= 65532) return this.error('filename is too long.')
var msg = '\x00' // null byte
msg += '\x00\x08' // type 8 tlv
msg += HLP.packSHORT(4 + l1name.length) // length of value
msg += '\x00\x00\x00\x01' // four bytes indicating file
msg += l1name
msg = this.prepareMsg(msg, filename)
this.io(msg)
}
OTR.prototype.endOtr = function () {
if (this.msgstate === CONST.MSGSTATE_ENCRYPTED) {
this.sendMsg('\x00\x00\x01\x00\x00')
if (this.sm) {
if (this.smw) this.sm.worker.terminate() // destroy webworker
this.sm = null
}
}
this.msgstate = CONST.MSGSTATE_PLAINTEXT
this.receivedPlaintext = false
this.trigger('status', [CONST.STATUS_END_OTR])
}
// attach methods
OTR.makeInstanceTag = function () {
var num = BigInt.randBigInt(32)
if (BigInt.greater(BigInt.str2bigInt('100', 16), num))
return OTR.makeInstanceTag()
return HLP.packINT(parseInt(BigInt.bigInt2str(num, 10), 10))
}
}).call(this)
| Don't publish sending mac keys
* Closes #42
* The finite-state analysis of the otr v2 spec revealed an attack on
message integrity. As a result, only mac keys used to receive
messages can safely be published to allow forgeability of
transcripts.
* This change to the spec is seen in,
http://sourceforge.net/p/otr/libotr/ci/58fd90cb77c836ff9fa762e91d2b2becc6d5aae8/
| lib/otr.js | Don't publish sending mac keys | <ide><path>ib/otr.js
<ide> this.sendenc = HLP.mask(HLP.h1(sendbyte, secbytes), 0, 128) // f16 bytes
<ide> this.sendmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.sendenc))
<ide> this.sendmac = this.sendmac.toString(CryptoJS.enc.Latin1)
<del> this.sendmacused = false
<add>
<ide> this.rcvenc = HLP.mask(HLP.h1(rcvbyte, secbytes), 0, 128)
<ide> this.rcvmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.rcvenc))
<ide> this.rcvmac = this.rcvmac.toString(CryptoJS.enc.Latin1)
<ide> // reveal old mac keys
<ide> var self = this
<ide> this.sessKeys[1].forEach(function (sk) {
<del> if (sk && sk.sendmacused) self.oldMacKeys.push(sk.sendmac)
<ide> if (sk && sk.rcvmacused) self.oldMacKeys.push(sk.rcvmac)
<ide> })
<ide>
<ide> // reveal old mac keys
<ide> var self = this
<ide> this.sessKeys.forEach(function (sk) {
<del> if (sk[1] && sk[1].sendmacused) self.oldMacKeys.push(sk[1].sendmac)
<ide> if (sk[1] && sk[1].rcvmacused) self.oldMacKeys.push(sk[1].rcvmac)
<ide> })
<ide>
<ide> send += HLP.packData(aes)
<ide> send += HLP.make1Mac(send, sessKeys.sendmac)
<ide> send += HLP.packData(this.oldMacKeys.splice(0).join(''))
<del>
<del> sessKeys.sendmacused = true
<ide>
<ide> send = HLP.wrapMsg(
<ide> send |
|
Java | lgpl-2.1 | 51e113f4d524d7a553a87c641bae20fee28a762b | 0 | sewe/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2004 Dave Brosius <[email protected]>
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.List;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types. This class is far, far from being done.
*/
public class OpcodeStack implements Constants2
{
private List<Item> stack;
public static class Item
{
private String signature;
private Object constValue;
private boolean isNull;
public Item(String s) {
this(s, null);
}
public Item(String s, Object v) {
signature = s;
constValue = v;
isNull = false;
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
isNull = true;
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public String getSignature() {
return signature;
}
public boolean isNull() {
return isNull;
}
public Object getConstant() {
return constValue;
}
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
JavaClass cls;
String signature;
Item it, it2, it3;
Constant cons;
try
{
//It would be nice to also track field values, but this currently isn't done.
//It would also be nice to track array values, but this currently isn't done.
switch (seen) {
case ALOAD:
pushByLocal(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocal(dbc, seen - ALOAD_0);
break;
case DLOAD:
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
push(new Item("D"));
break;
case LLOAD:
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
push(new Item("L"));
break;
case FLOAD:
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
push(new Item("F"));
break;
case GETSTATIC:
pushBySignature(dbc.getSigConstantOperand());
break;
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case ARETURN:
case ASTORE:
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
case DRETURN:
case DSTORE:
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
case FRETURN:
case FSTORE:
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
case IRETURN:
case ISTORE:
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
case LOOKUPSWITCH:
case LRETURN:
case LSTORE:
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
case TABLESWITCH:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
case POP2:
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
it = pop();
push(it);
push(it);
break;
case DUP2:
it = pop();
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
break;
case DUP_X1:
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
break;
case DUP_X2:
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
break;
case ATHROW:
case CHECKCAST:
case GOTO:
case GOTO_W:
case IINC:
case NOP:
case RET:
case RETURN:
break;
case SWAP:
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", new Integer(seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", new Long(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", new Double(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", new Float(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ILOAD:
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
push(new Item("I"));
break;
case GETFIELD:
pop();
push(new Item(dbc.getSigConstantOperand()));
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
case CALOAD:
pop(2);
push(new Item("I"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", new Integer((int)dbc.getIntConstant())));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it, it2);
break;
case INEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer(-((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double(-((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
it = pop();
it2 = pop();
pushByLongMath(seen, it, it2);
break;
case LCMP:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = ((Long)it.getConstant()).longValue();
long l2 = ((Long)it.getConstant()).longValue();
if (l2 < l)
push(new Item("I", new Integer(-1)));
else if (l2 > l)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case FCMPG:
case FCMPL:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = ((Float)it.getConstant()).floatValue();
float f2 = ((Float)it.getConstant()).floatValue();
if (f2 < f)
push(new Item("I", new Integer(-1)));
else if (f2 > f)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case DCMPG:
case DCMPL:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = ((Double)it.getConstant()).doubleValue();
double d2 = ((Double)it.getConstant()).doubleValue();
if (d2 < d)
push(new Item("I", new Integer(-1)));
else if (d2 > d)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((byte)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((char)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case I2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("D"));
}
break;
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("F"));
}
break;
case I2L:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", new Long((long)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("J"));
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((short)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case D2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
break;
case D2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("F"));
}
break;
case D2L:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", new Long((long)((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("J"));
}
break;
case L2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Long)it.getConstant()).longValue())));
} else {
push(new Item("I"));
}
break;
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Long)it.getConstant()).longValue())));
} else {
push(new Item("D"));
}
break;
case L2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Long)it.getConstant()).longValue())));
} else {
push(new Item("F"));
}
break;
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Float)it.getConstant()).floatValue())));
} else {
push(new Item("I"));
}
break;
case F2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Float)it.getConstant()).floatValue())));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature(dbc.getClassConstantOperand());
break;
case NEWARRAY:
pop();
signature = BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
case ANEWARRAY:
pop();
pushBySignature("L"+dbc.getClassConstantOperand()+";");
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims--) > 0) {
pop();
}
push(new Item(dbc.getClassConstantOperand()));
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item("")); //?
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
pushByInvoke(dbc);
break;
default:
throw new UnsupportedOperationException("OpCode not supported yet" );
}
}
catch (Exception e) {
//If an error occurs, we clear the stack. one of two things will occur. Either the client will expect more stack
//items than really exist, and so they're condition check will fail, or the stack will resync with the code.
//But hopefully not false positives
stack.clear();
}
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
int tos = stack.size() - 1;
int pos = tos - stackOffset;
return stack.get(pos);
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count--) > 0)
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantInteger)
push(new Item("I", new Integer(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", new Float(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", new Double(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", new Long(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocal(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = lvt.getLocalVariable(register);
String signature = lv.getSignature();
pushBySignature(signature);
} else {
pushBySignature("");
}
}
private void pushByIntMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == IADD)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() + ((Integer)it.getConstant()).intValue())));
else if (seen == ISUB)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() - ((Integer)it.getConstant()).intValue())));
else if (seen == IMUL)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() * ((Integer)it.getConstant()).intValue())));
else if (seen == IDIV)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() / ((Integer)it.getConstant()).intValue())));
else if (seen == IAND)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() & ((Integer)it.getConstant()).intValue())));
else if (seen == IOR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() | ((Integer)it.getConstant()).intValue())));
else if (seen == IXOR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() ^ ((Integer)it.getConstant()).intValue())));
else if (seen == ISHL)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() << ((Integer)it.getConstant()).intValue())));
else if (seen == ISHR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >> ((Integer)it.getConstant()).intValue())));
else if (seen == IREM)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() % ((Integer)it.getConstant()).intValue())));
else if (seen == IUSHR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >>> ((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
}
private void pushByLongMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == LADD)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() + ((Long)it.getConstant()).longValue())));
else if (seen == LSUB)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() - ((Long)it.getConstant()).longValue())));
else if (seen == LMUL)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() * ((Long)it.getConstant()).longValue())));
else if (seen == LDIV)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() / ((Long)it.getConstant()).longValue())));
else if (seen == LAND)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() & ((Long)it.getConstant()).longValue())));
else if (seen == LOR)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() | ((Long)it.getConstant()).longValue())));
else if (seen == LXOR)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() ^ ((Long)it.getConstant()).longValue())));
else if (seen == LSHL)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() << ((Long)it.getConstant()).longValue())));
else if (seen == LSHR)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() >> ((Long)it.getConstant()).longValue())));
else if (seen == LREM)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() % ((Long)it.getConstant()).longValue())));
} else {
push(new Item("J"));
}
}
private void pushByFloatMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == FADD)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() + ((Float)it.getConstant()).floatValue())));
else if (seen == FSUB)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() - ((Float)it.getConstant()).floatValue())));
else if (seen == FMUL)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() * ((Float)it.getConstant()).floatValue())));
else if (seen == FDIV)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() / ((Float)it.getConstant()).floatValue())));
} else {
push(new Item("F"));
}
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == DADD)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() + ((Double)it.getConstant()).doubleValue())));
else if (seen == DSUB)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() - ((Double)it.getConstant()).doubleValue())));
else if (seen == DMUL)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() * ((Double)it.getConstant()).doubleValue())));
else if (seen == DDIV)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() / ((Double)it.getConstant()).doubleValue())));
else if (seen == DREM)
push(new Item("D")); //?
} else {
push(new Item("D"));
}
}
private void pushByInvoke(DismantleBytecode dbc) {
String signature = dbc.getSigConstantOperand();
Type[] argTypes = Type.getArgumentTypes(signature);
pop(argTypes.length);
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, null));
}
} | findbugs/src/java/edu/umd/cs/findbugs/OpcodeStack.java | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2004 Dave Brosius <[email protected]>
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.List;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types. This class is far, far from being done.
*/
public class OpcodeStack implements Constants2
{
private List<Item> stack;
public static class Item
{
private String signature;
private Object constValue;
private boolean isNull;
public Item(String s) {
this(s, null);
}
public Item(String s, Object v) {
signature = s;
constValue = v;
isNull = false;
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
isNull = true;
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public String getSignature() {
return signature;
}
public boolean isNull() {
return isNull;
}
public Object getConstant() {
return constValue;
}
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
JavaClass cls;
String signature;
Item it, it2, it3;
Constant cons;
try
{
//It would be nice to also track field values, but this currently isn't done.
//It would also be nice to track array values, but this currently isn't done.
switch (seen) {
case ALOAD:
pushByLocal(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocal(dbc, seen - ALOAD_0);
break;
case DLOAD:
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
push(new Item("D"));
break;
case LLOAD:
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
push(new Item("L"));
break;
case FLOAD:
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
push(new Item("F"));
break;
case GETSTATIC:
pushBySignature(dbc.getSigConstantOperand());
break;
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case ARETURN:
case ASTORE:
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
case DRETURN:
case DSTORE:
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
case FRETURN:
case FSTORE:
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
case IRETURN:
case ISTORE:
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
case LOOKUPSWITCH:
case LRETURN:
case LSTORE:
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
case TABLESWITCH:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
case POP2:
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
it = pop();
push(it);
push(it);
break;
case DUP2:
it = pop();
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
break;
case DUP_X1:
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
break;
case DUP_X2:
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
break;
case ATHROW:
case CHECKCAST:
case GOTO:
case GOTO_W:
case IINC:
case NOP:
case RET:
case RETURN:
break;
case SWAP:
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", new Integer(seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", new Long(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", new Double(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", new Float(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ILOAD:
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
push(new Item("I"));
break;
case GETFIELD:
pop();
push(new Item(dbc.getSigConstantOperand()));
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
case CALOAD:
pop(2);
push(new Item("I"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", new Integer((int)dbc.getIntConstant())));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it, it2);
break;
case INEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer(-((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double(-((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
it = pop();
it2 = pop();
pushByLongMath(seen, it, it2);
break;
case LCMP:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = ((Long)it.getConstant()).longValue();
long l2 = ((Long)it.getConstant()).longValue();
if (l2 < l)
push(new Item("I", new Integer(-1)));
else if (l2 > l)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case FCMPG:
case FCMPL:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = ((Float)it.getConstant()).floatValue();
float f2 = ((Float)it.getConstant()).floatValue();
if (f2 < f)
push(new Item("I", new Integer(-1)));
else if (f2 > f)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case DCMPG:
case DCMPL:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = ((Double)it.getConstant()).doubleValue();
double d2 = ((Double)it.getConstant()).doubleValue();
if (d2 < d)
push(new Item("I", new Integer(-1)));
else if (d2 > d)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((byte)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((char)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case I2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("D"));
}
break;
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("F"));
}
break;
case I2L:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", new Long((long)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("J"));
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((short)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case D2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
break;
case D2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("F"));
}
break;
case L2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Long)it.getConstant()).longValue())));
} else {
push(new Item("I"));
}
break;
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Long)it.getConstant()).longValue())));
} else {
push(new Item("D"));
}
break;
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Float)it.getConstant()).floatValue())));
} else {
push(new Item("I"));
}
break;
case F2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Float)it.getConstant()).floatValue())));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature(dbc.getClassConstantOperand());
break;
case NEWARRAY:
pop();
signature = BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
case ANEWARRAY:
pop();
pushBySignature("L"+dbc.getClassConstantOperand()+";");
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item("")); //?
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
pushByInvoke(dbc);
break;
default:
throw new UnsupportedOperationException("OpCode not supported yet" );
}
}
catch (Exception e) {
//If an error occurs, we clear the stack. one of two things will occur. Either the client will expect more stack
//items than really exist, and so they're condition check will fail, or the stack will resync with the code.
//But hopefully not false positives
stack.clear();
}
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
int tos = stack.size() - 1;
int pos = tos - stackOffset;
return stack.get(pos);
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count--) > 0)
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantInteger)
push(new Item("I", new Integer(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", new Float(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", new Double(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", new Long(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocal(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = lvt.getLocalVariable(register);
String signature = lv.getSignature();
pushBySignature(signature);
} else {
pushBySignature("");
}
}
private void pushByIntMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == IADD)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() + ((Integer)it.getConstant()).intValue())));
else if (seen == ISUB)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() - ((Integer)it.getConstant()).intValue())));
else if (seen == IMUL)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() * ((Integer)it.getConstant()).intValue())));
else if (seen == IDIV)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() / ((Integer)it.getConstant()).intValue())));
else if (seen == IAND)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() & ((Integer)it.getConstant()).intValue())));
else if (seen == IOR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() | ((Integer)it.getConstant()).intValue())));
else if (seen == IXOR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() ^ ((Integer)it.getConstant()).intValue())));
else if (seen == ISHL)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() << ((Integer)it.getConstant()).intValue())));
else if (seen == ISHR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >> ((Integer)it.getConstant()).intValue())));
else if (seen == IREM)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() % ((Integer)it.getConstant()).intValue())));
else if (seen == IUSHR)
push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >>> ((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
}
private void pushByLongMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == LADD)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() + ((Long)it.getConstant()).longValue())));
else if (seen == LSUB)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() - ((Long)it.getConstant()).longValue())));
else if (seen == LMUL)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() * ((Long)it.getConstant()).longValue())));
else if (seen == LDIV)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() / ((Long)it.getConstant()).longValue())));
else if (seen == LAND)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() & ((Long)it.getConstant()).longValue())));
else if (seen == LOR)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() | ((Long)it.getConstant()).longValue())));
else if (seen == LXOR)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() ^ ((Long)it.getConstant()).longValue())));
else if (seen == LSHL)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() << ((Long)it.getConstant()).longValue())));
else if (seen == LSHR)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() >> ((Long)it.getConstant()).longValue())));
else if (seen == LREM)
push(new Item("J", new Long(((Long)it2.getConstant()).longValue() % ((Long)it.getConstant()).longValue())));
} else {
push(new Item("J"));
}
}
private void pushByFloatMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == FADD)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() + ((Float)it.getConstant()).floatValue())));
else if (seen == FSUB)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() - ((Float)it.getConstant()).floatValue())));
else if (seen == FMUL)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() * ((Float)it.getConstant()).floatValue())));
else if (seen == FDIV)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() / ((Float)it.getConstant()).floatValue())));
} else {
push(new Item("F"));
}
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == DADD)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() + ((Double)it.getConstant()).doubleValue())));
else if (seen == DSUB)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() - ((Double)it.getConstant()).doubleValue())));
else if (seen == DMUL)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() * ((Double)it.getConstant()).doubleValue())));
else if (seen == DDIV)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() / ((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("D"));
}
}
private void pushByInvoke(DismantleBytecode dbc) {
String signature = dbc.getSigConstantOperand();
Type[] argTypes = Type.getArgumentTypes(signature);
pop(argTypes.length);
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, null));
}
} | garsh, there's a lot of opcodes, here's more.
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@3112 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugs/src/java/edu/umd/cs/findbugs/OpcodeStack.java | garsh, there's a lot of opcodes, here's more. | <ide><path>indbugs/src/java/edu/umd/cs/findbugs/OpcodeStack.java
<ide> case DSUB:
<ide> case DMUL:
<ide> case DDIV:
<add> case DREM:
<ide> it = pop();
<ide> it2 = pop();
<ide> pushByDoubleMath(seen, it, it2);
<ide> }
<ide> break;
<ide>
<add> case D2L:
<add> it = pop();
<add> if (it.getConstant() != null) {
<add> push(new Item("J", new Long((long)((Double)it.getConstant()).doubleValue())));
<add> } else {
<add> push(new Item("J"));
<add> }
<add> break;
<add>
<ide> case L2I:
<ide> it = pop();
<ide> if (it.getConstant() != null) {
<ide> }
<ide> break;
<ide>
<add> case L2F:
<add> it = pop();
<add> if (it.getConstant() != null) {
<add> push(new Item("F", new Float((float)((Long)it.getConstant()).longValue())));
<add> } else {
<add> push(new Item("F"));
<add> }
<add> break;
<add>
<ide> case F2I:
<ide> it = pop();
<ide> if (it.getConstant() != null) {
<ide> case ANEWARRAY:
<ide> pop();
<ide> pushBySignature("L"+dbc.getClassConstantOperand()+";");
<add> break;
<add>
<add> case MULTIANEWARRAY:
<add> int dims = dbc.getIntConstant();
<add> while ((dims--) > 0) {
<add> pop();
<add> }
<add> push(new Item(dbc.getClassConstantOperand()));
<ide> break;
<ide>
<ide> case AALOAD:
<ide> push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() * ((Double)it.getConstant()).doubleValue())));
<ide> else if (seen == DDIV)
<ide> push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() / ((Double)it.getConstant()).doubleValue())));
<del> } else {
<add> else if (seen == DREM)
<add> push(new Item("D")); //?
<add> } else {
<ide> push(new Item("D"));
<ide> }
<ide> } |
|
JavaScript | mit | 9f1f5bdbe2edb0518abad9678f93f7e102d061f6 | 0 | IPS-LMU/EMU-webApp,IPS-LMU/EMU-webApp,IPS-LMU/EMU-webApp,IPS-LMU/EMU-webApp,IPS-LMU/EMU-webApp,IPS-LMU/EMU-webApp | 'use strict';
angular.module('emulvcApp')
.service('ConfigProviderService', function ConfigProviderService($rootScope, $http) {
// shared service object
var sServObj = {};
sServObj.vals = {};
/**
*
*/
sServObj.httpGetConfig = function () { // SIC SIC SIC...
$http.get('configFiles/defaultConfig.json').success(function (data) {
sServObj.setVals(data);
$rootScope.$broadcast('configLoaded', data);
}).error(function (data, status, header, config) {
console.log('################ERR');
console.log(status);
console.log(header);
console.log(config);
});
};
/**
* depth of 2 = max
*/
sServObj.setVals = function (data) {
if ($.isEmptyObject(sServObj.vals)) {
sServObj.vals = data;
} else {
Object.keys(data).forEach(function (key1) {
// console.log(key1 + ' : ' + data[key1]);
// sServObj.vals[key1] = data[key1];
Object.keys(data[key1]).forEach(function (key2) {
if (sServObj.vals[key1][key2] !== undefined) {
// console.log('\t' + key2);
// console.log(data[key1][key2]);
sServObj.vals[key1][key2] = data[key1][key2];
} else {
console.error('BAD ENTRY IN CONFIG');
}
});
});
}
};
return sServObj;
}); | app/scripts/services/configProviderService.js | 'use strict';
angular.module('emulvcApp')
.service('ConfigProviderService', function ConfigProviderService($rootScope, $http) {
// shared service object
var sServObj = {};
sServObj.vals = {};
/**
*
*/
sServObj.httpGetConfig = function () { // SIC SIC SIC...
$http.get('configFiles/defaultConfig.json').success(function (data) {
sServObj.setVals(data);
$rootScope.$broadcast('configLoaded', data);
});
};
/**
* depth of 2 = max
*/
sServObj.setVals = function (data) {
if ($.isEmptyObject(sServObj.vals)) {
sServObj.vals = data;
} else {
Object.keys(data).forEach(function (key1) {
// console.log(key1 + ' : ' + data[key1]);
// sServObj.vals[key1] = data[key1];
Object.keys(data[key1]).forEach(function (key2) {
if (sServObj.vals[key1][key2] !== undefined) {
// console.log('\t' + key2);
// console.log(data[key1][key2]);
sServObj.vals[key1][key2] = data[key1][key2];
} else {
console.error('BAD ENTRY IN CONFIG');
}
});
});
}
};
return sServObj;
}); | modals back up and running
| app/scripts/services/configProviderService.js | modals back up and running | <ide><path>pp/scripts/services/configProviderService.js
<ide> $http.get('configFiles/defaultConfig.json').success(function (data) {
<ide> sServObj.setVals(data);
<ide> $rootScope.$broadcast('configLoaded', data);
<add> }).error(function (data, status, header, config) {
<add> console.log('################ERR');
<add> console.log(status);
<add> console.log(header);
<add> console.log(config);
<ide> });
<ide> };
<ide> |
|
Java | apache-2.0 | f8d538e6904b660bb9a13cc269d2e2582f703856 | 0 | Distrotech/intellij-community,xfournet/intellij-community,fitermay/intellij-community,robovm/robovm-studio,fnouama/intellij-community,signed/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,blademainer/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,semonte/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,FHannes/intellij-community,kool79/intellij-community,hurricup/intellij-community,asedunov/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,semonte/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,samthor/intellij-community,jagguli/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,samthor/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,izonder/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,consulo/consulo,hurricup/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,allotria/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,kool79/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,semonte/intellij-community,FHannes/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,xfournet/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,allotria/intellij-community,robovm/robovm-studio,diorcety/intellij-community,supersven/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,robovm/robovm-studio,hurricup/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,consulo/consulo,vladmm/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,da1z/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,diorcety/intellij-community,semonte/intellij-community,kool79/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,caot/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,vladmm/intellij-community,kool79/intellij-community,ernestp/consulo,nicolargo/intellij-community,samthor/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,da1z/intellij-community,caot/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,clumsy/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,izonder/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,adedayo/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,da1z/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,ibinti/intellij-community,allotria/intellij-community,adedayo/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,caot/intellij-community,adedayo/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,petteyg/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,blademainer/intellij-community,dslomov/intellij-community,amith01994/intellij-community,xfournet/intellij-community,ryano144/intellij-community,signed/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,holmes/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,kdwink/intellij-community,amith01994/intellij-community,ryano144/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,consulo/consulo,akosyakov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,allotria/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,hurricup/intellij-community,amith01994/intellij-community,blademainer/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,gnuhub/intellij-community,slisson/intellij-community,da1z/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,consulo/consulo,diorcety/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,da1z/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,izonder/intellij-community,allotria/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,signed/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,semonte/intellij-community,petteyg/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,signed/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,hurricup/intellij-community,slisson/intellij-community,blademainer/intellij-community,supersven/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,izonder/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,consulo/consulo,holmes/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,samthor/intellij-community,caot/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,slisson/intellij-community,da1z/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,caot/intellij-community,izonder/intellij-community,dslomov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,samthor/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,xfournet/intellij-community,kdwink/intellij-community,slisson/intellij-community,izonder/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,da1z/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,da1z/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,ernestp/consulo,slisson/intellij-community,signed/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,fitermay/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,dslomov/intellij-community,allotria/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ernestp/consulo,jagguli/intellij-community,fnouama/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,kool79/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,dslomov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,blademainer/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ernestp/consulo,holmes/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,dslomov/intellij-community,signed/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,caot/intellij-community,fitermay/intellij-community,ibinti/intellij-community,FHannes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ernestp/consulo,retomerz/intellij-community,fitermay/intellij-community,retomerz/intellij-community,samthor/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,caot/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,slisson/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,diorcety/intellij-community,fnouama/intellij-community,supersven/intellij-community,apixandru/intellij-community,supersven/intellij-community,signed/intellij-community,semonte/intellij-community,xfournet/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,supersven/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,robovm/robovm-studio,semonte/intellij-community,dslomov/intellij-community,fitermay/intellij-community,izonder/intellij-community,wreckJ/intellij-community,supersven/intellij-community,fnouama/intellij-community,semonte/intellij-community,vladmm/intellij-community,kdwink/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,FHannes/intellij-community,clumsy/intellij-community,izonder/intellij-community,Distrotech/intellij-community,holmes/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,kool79/intellij-community,retomerz/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,caot/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,kdwink/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,slisson/intellij-community,clumsy/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,signed/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,adedayo/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,samthor/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.uiDesigner.propertyInspector.editors.string;
import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SpeedSearchBase;
import com.intellij.ui.table.JBTable;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.uiDesigner.designSurface.GuiEditor;
import com.intellij.uiDesigner.lw.StringDescriptor;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class KeyChooserDialog extends DialogWrapper{
private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.propertyInspector.editors.string.KeyChooserDialog");
private final PropertiesFile myBundle;
private final String myBundleName;
/** List of bundle's pairs*/
private ArrayList<Pair<String, String>> myPairs;
private final JComponent myCenterPanel;
/** Table with key/value pairs */
private final JTable myTable;
@NonNls private static final String NULL = "null";
private final MyTableModel myModel;
private final GuiEditor myEditor;
private static final String OK_ACTION = "OkAction";
/**
* @param bundle resource bundle to be shown.
* @param bundleName name of the resource bundle to be shown. We need this
* name to create StringDescriptor in {@link #getDescriptor()} method.
* @param keyToPreselect describes row that should be selected in the
* @param parent the parent component for the dialog.
*/
public KeyChooserDialog(
final Component parent,
@NotNull final PropertiesFile bundle,
@NotNull final String bundleName,
final String keyToPreselect,
final GuiEditor editor
) {
super(parent, true);
myEditor = editor;
myBundle = bundle;
myBundleName = bundleName;
setTitle(UIDesignerBundle.message("title.chooser.value"));
// Read key/value pairs from resource bundle
fillPropertyList();
// Create UI
myModel = new MyTableModel();
myTable = new JBTable(myModel);
myTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
new MySpeedSearch(myTable);
myCenterPanel = ScrollPaneFactory.createScrollPane(myTable);
myTable.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), OK_ACTION);
myTable.getActionMap().put(OK_ACTION, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
getOKAction().actionPerformed(e);
}
});
// Calculate width for "Key" columns
final FontMetrics metrics = myTable.getFontMetrics(myTable.getFont());
int width = 0;
for(int i = myPairs.size() - 1; i >= 0; i--){
final Pair<String, String> pair = myPairs.get(i);
width = Math.max(width, metrics.stringWidth(pair.getFirst()));
}
width += 30;
width = Math.max(width, metrics.stringWidth(myModel.getColumnName(0)));
final TableColumn keyColumn = myTable.getColumnModel().getColumn(0);
keyColumn.setMaxWidth(width);
keyColumn.setMinWidth(width);
final TableCellRenderer defaultRenderer = myTable.getDefaultRenderer(String.class);
if (defaultRenderer instanceof JComponent) {
final JComponent component = (JComponent)defaultRenderer;
component.putClientProperty("html.disable", Boolean.TRUE);
}
selectKey(keyToPreselect);
init();
myTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (!e.isPopupTrigger() && e.getClickCount() == 2) {
doOKAction();
}
}
});
}
private void fillPropertyList() {
myPairs = new ArrayList<Pair<String, String>>();
final List<IProperty> properties = myBundle.getProperties();
for (IProperty property : properties) {
final String key = property.getUnescapedKey();
final String value = property.getValue();
if (key != null) {
myPairs.add(new Pair<String, String>(key, value != null? value : NULL));
}
}
Collections.sort(myPairs, new MyPairComparator());
}
private void selectKey(final String keyToPreselect) {
// Preselect proper row
int indexToPreselect = -1;
for(int i = myPairs.size() - 1; i >= 0; i--){
final Pair<String, String> pair = myPairs.get(i);
if(pair.getFirst().equals(keyToPreselect)){
indexToPreselect = i;
break;
}
}
if(indexToPreselect != -1){
selectElementAt(indexToPreselect);
}
}
@Override protected Action[] createLeftSideActions() {
return new Action[] { new NewKeyValueAction() };
}
private void selectElementAt(final int index) {
myTable.getSelectionModel().setSelectionInterval(index, index);
myTable.scrollRectToVisible(myTable.getCellRect(index, 0, true));
}
protected String getDimensionServiceKey() {
return getClass().getName();
}
public JComponent getPreferredFocusedComponent() {
return myTable;
}
/**
* @return resolved string descriptor. If user chose nothing then the
* method returns <code>null</code>.
*/
@Nullable StringDescriptor getDescriptor() {
final int selectedRow = myTable.getSelectedRow();
if(selectedRow < 0 || selectedRow >= myTable.getRowCount()){
return null;
}
else{
final Pair<String, String> pair = myPairs.get(selectedRow);
final StringDescriptor descriptor = new StringDescriptor(myBundleName, pair.getFirst());
descriptor.setResolvedValue(pair.getSecond());
return descriptor;
}
}
protected JComponent createCenterPanel() {
return myCenterPanel;
}
private static final class MyPairComparator implements Comparator<Pair<String, String>>{
public int compare(final Pair<String, String> p1, final Pair<String, String> p2) {
return p1.getFirst().compareToIgnoreCase(p2.getFirst());
}
}
private final class MyTableModel extends AbstractTableModel{
public int getColumnCount() {
return 2;
}
public String getColumnName(final int column) {
if(column == 0){
return UIDesignerBundle.message("column.key");
}
else if(column == 1){
return UIDesignerBundle.message("column.value");
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public Class getColumnClass(final int column) {
if(column == 0){
return String.class;
}
else if(column == 1){
return String.class;
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public Object getValueAt(final int row, final int column) {
if(column == 0){
return myPairs.get(row).getFirst();
}
else if(column == 1){
return myPairs.get(row).getSecond();
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public int getRowCount() {
return myPairs.size();
}
public void update() {
fireTableDataChanged();
}
}
private class MySpeedSearch extends SpeedSearchBase<JTable> {
private TObjectIntHashMap<Object> myElements;
private Object[] myElementsArray;
public MySpeedSearch(final JTable component) {
super(component);
}
@Override
protected int convertIndexToModel(int viewIndex) {
return getComponent().convertRowIndexToModel(viewIndex);
}
public int getSelectedIndex() {
return myComponent.getSelectedRow();
}
public Object[] getAllElements() {
if (myElements == null) {
myElements = new TObjectIntHashMap<Object>();
myElementsArray = myPairs.toArray();
for (int idx = 0; idx < myElementsArray.length; idx++) {
Object element = myElementsArray[idx];
myElements.put(element, idx);
}
}
return myElementsArray;
}
public String getElementText(final Object element) {
//noinspection unchecked
return ((Pair<String, String>)element).getFirst();
}
public void selectElement(final Object element, final String selectedText) {
final int index = myElements.get(element);
selectElementAt(getComponent().convertRowIndexToView(index));
}
}
private class NewKeyValueAction extends AbstractAction {
public NewKeyValueAction() {
putValue(Action.NAME, UIDesignerBundle.message("key.chooser.new.property"));
}
public void actionPerformed(ActionEvent e) {
NewKeyDialog dlg = new NewKeyDialog(getWindow());
dlg.show();
if (dlg.isOK()) {
if (!StringEditorDialog.saveCreatedProperty(myBundle, dlg.getName(), dlg.getValue(), myEditor.getPsiFile())) return;
fillPropertyList();
myModel.update();
selectKey(dlg.getName());
}
}
}
}
| plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/KeyChooserDialog.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.uiDesigner.propertyInspector.editors.string;
import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SpeedSearchBase;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.uiDesigner.designSurface.GuiEditor;
import com.intellij.uiDesigner.lw.StringDescriptor;
import com.intellij.util.ui.Table;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class KeyChooserDialog extends DialogWrapper{
private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.propertyInspector.editors.string.KeyChooserDialog");
private final PropertiesFile myBundle;
private final String myBundleName;
/** List of bundle's pairs*/
private ArrayList<Pair<String, String>> myPairs;
private final JComponent myCenterPanel;
/** Table with key/value pairs */
private final Table myTable;
@NonNls private static final String NULL = "null";
private final MyTableModel myModel;
private final GuiEditor myEditor;
private static final String OK_ACTION = "OkAction";
/**
* @param bundle resource bundle to be shown.
*@param bundleName name of the resource bundle to be shown. We need this
* name to create StringDescriptor in {@link #getDescriptor()} method.
*@param keyToPreselect describes row that should be selected in the
* @param parent the parent component for the dialog.
*/
public KeyChooserDialog(
final Component parent,
@NotNull final PropertiesFile bundle,
@NotNull final String bundleName,
final String keyToPreselect,
final GuiEditor editor
) {
super(parent, true);
myEditor = editor;
myBundle = bundle;
myBundleName = bundleName;
setTitle(UIDesignerBundle.message("title.chooser.value"));
// Read key/value pairs from resource bundle
fillPropertyList();
// Create UI
myModel = new MyTableModel();
myTable = new Table(myModel);
myTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
new MySpeedSearch(myTable);
myCenterPanel = ScrollPaneFactory.createScrollPane(myTable);
myTable.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), OK_ACTION);
myTable.getActionMap().put(OK_ACTION, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
getOKAction().actionPerformed(e);
}
});
// Calculate width for "Key" columns
final FontMetrics metrics = myTable.getFontMetrics(myTable.getFont());
int width = 0;
for(int i = myPairs.size() - 1; i >= 0; i--){
final Pair<String, String> pair = myPairs.get(i);
width = Math.max(width, metrics.stringWidth(pair.getFirst()));
}
width += 30;
width = Math.max(width, metrics.stringWidth(myModel.getColumnName(0)));
final TableColumn keyColumn = myTable.getColumnModel().getColumn(0);
keyColumn.setMaxWidth(width);
keyColumn.setMinWidth(width);
selectKey(keyToPreselect);
init();
myTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (!e.isPopupTrigger() && e.getClickCount() == 2) {
doOKAction();
}
}
});
}
private void fillPropertyList() {
myPairs = new ArrayList<Pair<String, String>>();
final List<IProperty> properties = myBundle.getProperties();
for (IProperty property : properties) {
final String key = property.getUnescapedKey();
final String value = property.getValue();
if (key != null) {
myPairs.add(new Pair<String, String>(key, value != null? value : NULL));
}
}
Collections.sort(myPairs, new MyPairComparator());
}
private void selectKey(final String keyToPreselect) {
// Preselect proper row
int indexToPreselect = -1;
for(int i = myPairs.size() - 1; i >= 0; i--){
final Pair<String, String> pair = myPairs.get(i);
if(pair.getFirst().equals(keyToPreselect)){
indexToPreselect = i;
break;
}
}
if(indexToPreselect != -1){
selectElementAt(indexToPreselect);
}
}
@Override protected Action[] createLeftSideActions() {
return new Action[] { new NewKeyValueAction() };
}
private void selectElementAt(final int index) {
myTable.getSelectionModel().setSelectionInterval(index, index);
myTable.scrollRectToVisible(myTable.getCellRect(index, 0, true));
}
protected String getDimensionServiceKey() {
return getClass().getName();
}
public JComponent getPreferredFocusedComponent() {
return myTable;
}
/**
* @return resolved string descriptor. If user chose nothing then the
* method returns <code>null</code>.
*/
@Nullable StringDescriptor getDescriptor() {
final int selectedRow = myTable.getSelectedRow();
if(selectedRow < 0 || selectedRow >= myTable.getRowCount()){
return null;
}
else{
final Pair<String, String> pair = myPairs.get(selectedRow);
final StringDescriptor descriptor = new StringDescriptor(myBundleName, pair.getFirst());
descriptor.setResolvedValue(pair.getSecond());
return descriptor;
}
}
protected JComponent createCenterPanel() {
return myCenterPanel;
}
private static final class MyPairComparator implements Comparator<Pair<String, String>>{
public int compare(final Pair<String, String> p1, final Pair<String, String> p2) {
return p1.getFirst().compareToIgnoreCase(p2.getFirst());
}
}
private final class MyTableModel extends AbstractTableModel{
public int getColumnCount() {
return 2;
}
public String getColumnName(final int column) {
if(column == 0){
return UIDesignerBundle.message("column.key");
}
else if(column == 1){
return UIDesignerBundle.message("column.value");
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public Class getColumnClass(final int column) {
if(column == 0){
return String.class;
}
else if(column == 1){
return String.class;
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public Object getValueAt(final int row, final int column) {
if(column == 0){
return myPairs.get(row).getFirst();
}
else if(column == 1){
return myPairs.get(row).getSecond();
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public int getRowCount() {
return myPairs.size();
}
public void update() {
fireTableDataChanged();
}
}
private class MySpeedSearch extends SpeedSearchBase<Table> {
private TObjectIntHashMap<Object> myElements;
private Object[] myElementsArray;
public MySpeedSearch(final Table component) {
super(component);
}
@Override
protected int convertIndexToModel(int viewIndex) {
return getComponent().convertRowIndexToModel(viewIndex);
}
public int getSelectedIndex() {
return myComponent.getSelectedRow();
}
public Object[] getAllElements() {
if (myElements == null) {
myElements = new TObjectIntHashMap<Object>();
myElementsArray = myPairs.toArray();
for (int idx = 0; idx < myElementsArray.length; idx++) {
Object element = myElementsArray[idx];
myElements.put(element, idx);
}
}
return myElementsArray;
}
public String getElementText(final Object element) {
//noinspection unchecked
return ((Pair<String, String>)element).getFirst();
}
public void selectElement(final Object element, final String selectedText) {
final int index = myElements.get(element);
selectElementAt(getComponent().convertRowIndexToView(index));
}
}
private class NewKeyValueAction extends AbstractAction {
public NewKeyValueAction() {
putValue(Action.NAME, UIDesignerBundle.message("key.chooser.new.property"));
}
public void actionPerformed(ActionEvent e) {
NewKeyDialog dlg = new NewKeyDialog(getWindow());
dlg.show();
if (dlg.isOK()) {
if (!StringEditorDialog.saveCreatedProperty(myBundle, dlg.getName(), dlg.getValue(), myEditor.getPsiFile())) return;
fillPropertyList();
myModel.update();
selectKey(dlg.getName());
}
}
}
}
| display source of html properties instead of messing up table layout (e.g. in CvsBundle)
| plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/KeyChooserDialog.java | display source of html properties instead of messing up table layout (e.g. in CvsBundle) | <ide><path>lugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/KeyChooserDialog.java
<ide> /*
<del> * Copyright 2000-2009 JetBrains s.r.o.
<add> * Copyright 2000-2011 JetBrains s.r.o.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import com.intellij.openapi.util.Pair;
<ide> import com.intellij.ui.ScrollPaneFactory;
<ide> import com.intellij.ui.SpeedSearchBase;
<add>import com.intellij.ui.table.JBTable;
<ide> import com.intellij.uiDesigner.UIDesignerBundle;
<ide> import com.intellij.uiDesigner.designSurface.GuiEditor;
<ide> import com.intellij.uiDesigner.lw.StringDescriptor;
<del>import com.intellij.util.ui.Table;
<ide> import gnu.trove.TObjectIntHashMap;
<ide> import org.jetbrains.annotations.NonNls;
<ide> import org.jetbrains.annotations.NotNull;
<ide>
<ide> import javax.swing.*;
<ide> import javax.swing.table.AbstractTableModel;
<add>import javax.swing.table.TableCellRenderer;
<ide> import javax.swing.table.TableColumn;
<ide> import java.awt.*;
<ide> import java.awt.event.ActionEvent;
<add>import java.awt.event.KeyEvent;
<ide> import java.awt.event.MouseAdapter;
<ide> import java.awt.event.MouseEvent;
<del>import java.awt.event.KeyEvent;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.Comparator;
<ide> private ArrayList<Pair<String, String>> myPairs;
<ide> private final JComponent myCenterPanel;
<ide> /** Table with key/value pairs */
<del> private final Table myTable;
<add> private final JTable myTable;
<ide> @NonNls private static final String NULL = "null";
<ide> private final MyTableModel myModel;
<ide> private final GuiEditor myEditor;
<ide>
<ide> /**
<ide> * @param bundle resource bundle to be shown.
<del> *@param bundleName name of the resource bundle to be shown. We need this
<add> * @param bundleName name of the resource bundle to be shown. We need this
<ide> * name to create StringDescriptor in {@link #getDescriptor()} method.
<del> *@param keyToPreselect describes row that should be selected in the
<add> * @param keyToPreselect describes row that should be selected in the
<ide> * @param parent the parent component for the dialog.
<ide> */
<ide> public KeyChooserDialog(
<ide>
<ide> // Create UI
<ide> myModel = new MyTableModel();
<del> myTable = new Table(myModel);
<add> myTable = new JBTable(myModel);
<ide> myTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
<ide> new MySpeedSearch(myTable);
<ide> myCenterPanel = ScrollPaneFactory.createScrollPane(myTable);
<ide> final TableColumn keyColumn = myTable.getColumnModel().getColumn(0);
<ide> keyColumn.setMaxWidth(width);
<ide> keyColumn.setMinWidth(width);
<del>
<add> final TableCellRenderer defaultRenderer = myTable.getDefaultRenderer(String.class);
<add> if (defaultRenderer instanceof JComponent) {
<add> final JComponent component = (JComponent)defaultRenderer;
<add> component.putClientProperty("html.disable", Boolean.TRUE);
<add> }
<ide> selectKey(keyToPreselect);
<ide>
<ide> init();
<ide> }
<ide> }
<ide>
<del> private class MySpeedSearch extends SpeedSearchBase<Table> {
<add> private class MySpeedSearch extends SpeedSearchBase<JTable> {
<ide> private TObjectIntHashMap<Object> myElements;
<ide> private Object[] myElementsArray;
<ide>
<del> public MySpeedSearch(final Table component) {
<add> public MySpeedSearch(final JTable component) {
<ide> super(component);
<ide> }
<ide> |
|
Java | mit | error: pathspec 'src/com/freetymekiyan/algorithms/level/easy/TwoSum3DataStructureDesign.java' did not match any file(s) known to git
| 7952b5eaa1819b463958a6dd647ba432e5679033 | 1 | FreeTymeKiyan/LeetCode-Sol-Res,FreeTymeKiyan/LeetCode-Sol-Res | package com.freetymekiyan.algorithms.level.easy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Design and implement a TwoSum class. It should support the following operations: add and find.
* <p>
* add - Add the number to an internal data structure.
* find - Find if there exists any pair of numbers which sum is equal to the value.
* <p>
* For example,
* add(1); add(3); add(5);
* find(4) -> true
* find(7) -> false
* <p>
* Company Tags: LinkedIn
* Tags: Hash Table, Design
* Similar Problems: (E) Two Sum, (E) Unique Word Abbreviation
*/
public class TwoSum3DataStructureDesign {
public class TwoSum {
List<Integer> nums = new ArrayList<>();
Map<Integer, Integer> count = new HashMap<>(); // Map iterator is slow.
// Add the number to an internal data structure.
public void add(int number) {
if (!count.containsKey(number)) {
count.put(number, 0);
nums.add(number);
}
count.put(number, count.get(number) + 1);
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
for (int num1 : nums) {
int num2 = value - num1;
if (!count.containsKey(num2)) {
continue;
}
if (num1 != num2 && count.get(num2) > 0) {
return true;
}
if (num1 == num2 && count.get(num2) >= 2) {
return true;
}
}
return false;
}
}
// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum = new TwoSum();
// twoSum.add(number);
// twoSum.find(value);
}
| src/com/freetymekiyan/algorithms/level/easy/TwoSum3DataStructureDesign.java | add two sum 3
| src/com/freetymekiyan/algorithms/level/easy/TwoSum3DataStructureDesign.java | add two sum 3 | <ide><path>rc/com/freetymekiyan/algorithms/level/easy/TwoSum3DataStructureDesign.java
<add>package com.freetymekiyan.algorithms.level.easy;
<add>
<add>import java.util.ArrayList;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>
<add>/**
<add> * Design and implement a TwoSum class. It should support the following operations: add and find.
<add> * <p>
<add> * add - Add the number to an internal data structure.
<add> * find - Find if there exists any pair of numbers which sum is equal to the value.
<add> * <p>
<add> * For example,
<add> * add(1); add(3); add(5);
<add> * find(4) -> true
<add> * find(7) -> false
<add> * <p>
<add> * Company Tags: LinkedIn
<add> * Tags: Hash Table, Design
<add> * Similar Problems: (E) Two Sum, (E) Unique Word Abbreviation
<add> */
<add>public class TwoSum3DataStructureDesign {
<add>
<add> public class TwoSum {
<add>
<add> List<Integer> nums = new ArrayList<>();
<add> Map<Integer, Integer> count = new HashMap<>(); // Map iterator is slow.
<add>
<add> // Add the number to an internal data structure.
<add> public void add(int number) {
<add> if (!count.containsKey(number)) {
<add> count.put(number, 0);
<add> nums.add(number);
<add> }
<add> count.put(number, count.get(number) + 1);
<add> }
<add>
<add> // Find if there exists any pair of numbers which sum is equal to the value.
<add> public boolean find(int value) {
<add> for (int num1 : nums) {
<add> int num2 = value - num1;
<add> if (!count.containsKey(num2)) {
<add> continue;
<add> }
<add> if (num1 != num2 && count.get(num2) > 0) {
<add> return true;
<add> }
<add> if (num1 == num2 && count.get(num2) >= 2) {
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add> }
<add>
<add>// Your TwoSum object will be instantiated and called as such:
<add>// TwoSum twoSum = new TwoSum();
<add>// twoSum.add(number);
<add>// twoSum.find(value);
<add>} |
|
Java | apache-2.0 | d541c8e25783187417a243d2c1485af3664131c3 | 0 | SanjayUser/SpringSecurityPro,adairtaosy/spring-security,djechelon/spring-security,adairtaosy/spring-security,pwheel/spring-security,hippostar/spring-security,ajdinhedzic/spring-security,pkdevbox/spring-security,fhanik/spring-security,djechelon/spring-security,ollie314/spring-security,MatthiasWinzeler/spring-security,olezhuravlev/spring-security,jmnarloch/spring-security,diegofernandes/spring-security,pkdevbox/spring-security,likaiwalkman/spring-security,forestqqqq/spring-security,rwinch/spring-security,vitorgv/spring-security,kazuki43zoo/spring-security,kazuki43zoo/spring-security,thomasdarimont/spring-security,ollie314/spring-security,spring-projects/spring-security,jmnarloch/spring-security,jmnarloch/spring-security,zgscwjm/spring-security,izeye/spring-security,zshift/spring-security,zhaoqin102/spring-security,ractive/spring-security,jgrandja/spring-security,eddumelendez/spring-security,follow99/spring-security,hippostar/spring-security,spring-projects/spring-security,cyratech/spring-security,dsyer/spring-security,forestqqqq/spring-security,driftman/spring-security,spring-projects/spring-security,mdeinum/spring-security,wilkinsona/spring-security,jgrandja/spring-security,thomasdarimont/spring-security,chinazhaoht/spring-security,SanjayUser/SpringSecurityPro,tekul/spring-security,thomasdarimont/spring-security,izeye/spring-security,mdeinum/spring-security,Krasnyanskiy/spring-security,justinedelson/spring-security,xingguang2013/spring-security,rwinch/spring-security,vitorgv/spring-security,ajdinhedzic/spring-security,tekul/spring-security,fhanik/spring-security,dsyer/spring-security,diegofernandes/spring-security,ajdinhedzic/spring-security,forestqqqq/spring-security,fhanik/spring-security,dsyer/spring-security,pwheel/spring-security,chinazhaoht/spring-security,mounb/spring-security,eddumelendez/spring-security,caiwenshu/spring-security,mparaz/spring-security,spring-projects/spring-security,eddumelendez/spring-security,thomasdarimont/spring-security,SanjayUser/SpringSecurityPro,raindev/spring-security,yinhe402/spring-security,panchenko/spring-security,tekul/spring-security,wilkinsona/spring-security,mrkingybc/spring-security,yinhe402/spring-security,mparaz/spring-security,MatthiasWinzeler/spring-security,follow99/spring-security,kazuki43zoo/spring-security,mdeinum/spring-security,zshift/spring-security,Peter32/spring-security,forestqqqq/spring-security,Xcorpio/spring-security,fhanik/spring-security,xingguang2013/spring-security,mrkingybc/spring-security,olezhuravlev/spring-security,Krasnyanskiy/spring-security,spring-projects/spring-security,thomasdarimont/spring-security,liuguohua/spring-security,mdeinum/spring-security,justinedelson/spring-security,yinhe402/spring-security,zhaoqin102/spring-security,caiwenshu/spring-security,adairtaosy/spring-security,fhanik/spring-security,xingguang2013/spring-security,wilkinsona/spring-security,Xcorpio/spring-security,mounb/spring-security,SanjayUser/SpringSecurityPro,pwheel/spring-security,ractive/spring-security,wkorando/spring-security,adairtaosy/spring-security,rwinch/spring-security,wkorando/spring-security,panchenko/spring-security,djechelon/spring-security,panchenko/spring-security,caiwenshu/spring-security,fhanik/spring-security,pwheel/spring-security,rwinch/spring-security,caiwenshu/spring-security,ajdinhedzic/spring-security,wilkinsona/spring-security,likaiwalkman/spring-security,olezhuravlev/spring-security,raindev/spring-security,follow99/spring-security,zshift/spring-security,likaiwalkman/spring-security,ollie314/spring-security,liuguohua/spring-security,pwheel/spring-security,kazuki43zoo/spring-security,follow99/spring-security,MatthiasWinzeler/spring-security,eddumelendez/spring-security,mrkingybc/spring-security,wkorando/spring-security,MatthiasWinzeler/spring-security,tekul/spring-security,liuguohua/spring-security,kazuki43zoo/spring-security,driftman/spring-security,mounb/spring-security,vitorgv/spring-security,rwinch/spring-security,jgrandja/spring-security,ollie314/spring-security,Peter32/spring-security,justinedelson/spring-security,hippostar/spring-security,panchenko/spring-security,yinhe402/spring-security,jgrandja/spring-security,zgscwjm/spring-security,jgrandja/spring-security,justinedelson/spring-security,cyratech/spring-security,chinazhaoht/spring-security,zshift/spring-security,Xcorpio/spring-security,olezhuravlev/spring-security,chinazhaoht/spring-security,mparaz/spring-security,zgscwjm/spring-security,djechelon/spring-security,mparaz/spring-security,ractive/spring-security,driftman/spring-security,liuguohua/spring-security,pkdevbox/spring-security,wkorando/spring-security,diegofernandes/spring-security,izeye/spring-security,Peter32/spring-security,mrkingybc/spring-security,diegofernandes/spring-security,dsyer/spring-security,hippostar/spring-security,SanjayUser/SpringSecurityPro,driftman/spring-security,zgscwjm/spring-security,cyratech/spring-security,jgrandja/spring-security,djechelon/spring-security,xingguang2013/spring-security,Peter32/spring-security,spring-projects/spring-security,Krasnyanskiy/spring-security,jmnarloch/spring-security,Xcorpio/spring-security,dsyer/spring-security,cyratech/spring-security,vitorgv/spring-security,raindev/spring-security,ractive/spring-security,pkdevbox/spring-security,mounb/spring-security,zhaoqin102/spring-security,spring-projects/spring-security,Krasnyanskiy/spring-security,likaiwalkman/spring-security,raindev/spring-security,zhaoqin102/spring-security,olezhuravlev/spring-security,eddumelendez/spring-security,rwinch/spring-security,izeye/spring-security | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.ui;
import org.acegisecurity.AcegiMessageSource;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent;
import org.acegisecurity.ui.rememberme.NullRememberMeServices;
import org.acegisecurity.ui.rememberme.RememberMeServices;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Abstract processor of browser-based HTTP-based authentication requests.
*
* <p>
* This filter is responsible for processing authentication requests. If
* authentication is successful, the resulting {@link Authentication} object
* will be placed into the <code>SecurityContext</code>, which is guaranteed
* to have already been created by an earlier filter.
* </p>
*
* <p>
* If authentication fails, the <code>AuthenticationException</code> will be
* placed into the <code>HttpSession</code> with the attribute defined by
* {@link #ACEGI_SECURITY_LAST_EXCEPTION_KEY}.
* </p>
*
* <p>
* To use this filter, it is necessary to specify the following properties:
* </p>
*
* <ul>
* <li>
* <code>defaultTargetUrl</code> indicates the URL that should be used for
* redirection if the <code>HttpSession</code> attribute named {@link
* #ACEGI_SECURITY_TARGET_URL_KEY} does not indicate the target URL once
* authentication is completed successfully. eg: <code>/</code>. This will be
* treated as relative to the web-app's context path, and should include the
* leading <code>/</code>.
* </li>
* <li>
* <code>authenticationFailureUrl</code> indicates the URL that should be used
* for redirection if the authentication request fails. eg:
* <code>/login.jsp?login_error=1</code>.
* </li>
* <li>
* <code>filterProcessesUrl</code> indicates the URL that this filter will
* respond to. This parameter varies by subclass.
* </li>
* <li>
* <code>alwaysUseDefaultTargetUrl</code> causes successful authentication to
* always redirect to the <code>defaultTargetUrl</code>, even if the
* <code>HttpSession</code> attribute named {@link
* #ACEGI_SECURITY_TARGET_URL_KEY} defines the intended target URL.
* </li>
* </ul>
*
* <p>
* To configure this filter to redirect to specific pages as the result of
* specific {@link AuthenticationException}s you can do the following.
* Configure the <code>exceptionMappings</code> property in your application
* xml. This property is a java.util.Properties object that maps a
* fully-qualified exception class name to a redirection url target.<br>
* For example:<br>
* <code> <property name="exceptionMappings"><br>
* * <props><br>
* * <prop> key="org.acegisecurity.BadCredentialsException">/bad_credentials.jsp</prop><br>
* * </props><br>
* * </property><br>
* * </code><br>
* The example above would redirect all {@link
* org.acegisecurity.BadCredentialsException}s thrown, to a page in the
* web-application called /bad_credentials.jsp.
* </p>
*
* <p>
* Any {@link AuthenticationException} thrown that cannot be matched in the
* <code>exceptionMappings</code> will be redirected to the
* <code>authenticationFailureUrl</code>
* </p>
*
* <p>
* If authentication is successful, an {@link
* org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent}
* will be published to the application context. No events will be published
* if authentication was unsuccessful, because this would generally be
* recorded via an <code>AuthenticationManager</code>-specific application
* event.
* </p>
*/
public abstract class AbstractProcessingFilter implements Filter,
InitializingBean, ApplicationEventPublisherAware, MessageSourceAware {
//~ Static fields/initializers =============================================
public static final String ACEGI_SECURITY_TARGET_URL_KEY = "ACEGI_SECURITY_TARGET_URL";
public static final String ACEGI_SECURITY_LAST_EXCEPTION_KEY = "ACEGI_SECURITY_LAST_EXCEPTION";
protected static final Log logger = LogFactory.getLog(AbstractProcessingFilter.class);
//~ Instance fields ========================================================
protected ApplicationEventPublisher eventPublisher;
private AuthenticationManager authenticationManager;
protected MessageSourceAccessor messages = AcegiMessageSource.getAccessor();
private Properties exceptionMappings = new Properties();
private RememberMeServices rememberMeServices = new NullRememberMeServices();
/** Where to redirect the browser to if authentication fails */
private String authenticationFailureUrl;
/**
* Where to redirect the browser to if authentication is successful but
* ACEGI_SECURITY_TARGET_URL_KEY is <code>null</code>
*/
private String defaultTargetUrl;
/**
* The URL destination that this filter intercepts and processes (usually
* something like <code>/j_acegi_security_check</code>)
*/
private String filterProcessesUrl = getDefaultFilterProcessesUrl();
/**
* If <code>true</code>, will always redirect to {@link #defaultTargetUrl}
* upon successful authentication, irrespective of the page that caused
* the authentication request (defaults to <code>false</code>).
*/
private boolean alwaysUseDefaultTargetUrl = false;
/**
* Indicates if the filter chain should be continued prior to delegation to
* {@link #successfulAuthentication(HttpServletRequest,
* HttpServletResponse, Authentication)}, which may be useful in certain
* environment (eg Tapestry). Defaults to <code>false</code>.
*/
private boolean continueChainBeforeSuccessfulAuthentication = false;
//~ Methods ================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasLength(filterProcessesUrl,
"filterProcessesUrl must be specified");
Assert.hasLength(defaultTargetUrl, "defaultTargetUrl must be specified");
Assert.hasLength(authenticationFailureUrl,
"authenticationFailureUrl must be specified");
Assert.notNull(authenticationManager,
"authenticationManager must be specified");
Assert.notNull(this.rememberMeServices);
}
/**
* Performs actual authentication.
*
* @param request from which to extract parameters and perform the
* authentication
*
* @return the authenticated user
*
* @throws AuthenticationException if authentication fails
*/
public abstract Authentication attemptAuthentication(
HttpServletRequest request) throws AuthenticationException;
/**
* Does nothing. We use IoC container lifecycle services instead.
*/
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(response instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (requiresAuthentication(httpRequest, httpResponse)) {
if (logger.isDebugEnabled()) {
logger.debug("Request is to process authentication");
}
Authentication authResult;
try {
onPreAuthentication(httpRequest, httpResponse);
authResult = attemptAuthentication(httpRequest);
} catch (AuthenticationException failed) {
// Authentication failed
unsuccessfulAuthentication(httpRequest, httpResponse, failed);
return;
}
// Authentication success
if (continueChainBeforeSuccessfulAuthentication) {
chain.doFilter(request, response);
}
successfulAuthentication(httpRequest, httpResponse, authResult);
return;
}
chain.doFilter(request, response);
}
public String getAuthenticationFailureUrl() {
return authenticationFailureUrl;
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
/**
* Specifies the default <code>filterProcessesUrl</code> for the
* implementation.
*
* @return the default <code>filterProcessesUrl</code>
*/
public abstract String getDefaultFilterProcessesUrl();
public String getDefaultTargetUrl() {
return defaultTargetUrl;
}
public Properties getExceptionMappings() {
return new Properties(exceptionMappings);
}
public String getFilterProcessesUrl() {
return filterProcessesUrl;
}
public RememberMeServices getRememberMeServices() {
return rememberMeServices;
}
/**
* Does nothing. We use IoC container lifecycle services instead.
*
* @param arg0 ignored
*
* @throws ServletException ignored
*/
public void init(FilterConfig arg0) throws ServletException {}
public boolean isAlwaysUseDefaultTargetUrl() {
return alwaysUseDefaultTargetUrl;
}
public boolean isContinueChainBeforeSuccessfulAuthentication() {
return continueChainBeforeSuccessfulAuthentication;
}
protected void onPreAuthentication(HttpServletRequest request,
HttpServletResponse response)
throws AuthenticationException, IOException {}
protected void onSuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, Authentication authResult)
throws IOException {}
protected void onUnsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException {}
/**
* <p>
* Indicates whether this filter should attempt to process a login request
* for the current invocation.
* </p>
*
* <p>
* It strips any parameters from the "path" section of the request URL
* (such as the jsessionid parameter in
* <em>http://host/myapp/index.html;jsessionid=blah</em>) before matching
* against the <code>filterProcessesUrl</code> property.
* </p>
*
* <p>
* Subclasses may override for special requirements, such as Tapestry
* integration.
* </p>
*
* @param request as received from the filter chain
* @param response as received from the filter chain
*
* @return <code>true</code> if the filter should attempt authentication,
* <code>false</code> otherwise
*/
protected boolean requiresAuthentication(HttpServletRequest request,
HttpServletResponse response) {
String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';');
if (pathParamIndex > 0) {
// strip everything after the first semi-colon
uri = uri.substring(0, pathParamIndex);
}
return uri.endsWith(request.getContextPath() + filterProcessesUrl);
}
protected void sendRedirect(HttpServletRequest request,
HttpServletResponse response, String failureUrl)
throws IOException {
if (!failureUrl.startsWith("http://")
&& !failureUrl.startsWith("https://")) {
failureUrl = request.getContextPath() + failureUrl;
}
response.sendRedirect(response.encodeRedirectURL(failureUrl));
}
public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl) {
this.alwaysUseDefaultTargetUrl = alwaysUseDefaultTargetUrl;
}
public void setApplicationEventPublisher(
ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void setAuthenticationFailureUrl(String authenticationFailureUrl) {
this.authenticationFailureUrl = authenticationFailureUrl;
}
public void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public void setContinueChainBeforeSuccessfulAuthentication(
boolean continueChainBeforeSuccessfulAuthentication) {
this.continueChainBeforeSuccessfulAuthentication = continueChainBeforeSuccessfulAuthentication;
}
public void setDefaultTargetUrl(String defaultTargetUrl) {
this.defaultTargetUrl = defaultTargetUrl;
}
public void setExceptionMappings(Properties exceptionMappings) {
this.exceptionMappings = exceptionMappings;
}
public void setFilterProcessesUrl(String filterProcessesUrl) {
this.filterProcessesUrl = filterProcessesUrl;
}
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setRememberMeServices(RememberMeServices rememberMeServices) {
this.rememberMeServices = rememberMeServices;
}
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response, Authentication authResult)
throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authResult.toString());
}
SecurityContextHolder.getContext().setAuthentication(authResult);
if (logger.isDebugEnabled()) {
logger.debug(
"Updated SecurityContextHolder to contain the following Authentication: '"
+ authResult + "'");
}
String targetUrl = (String) request.getSession()
.getAttribute(ACEGI_SECURITY_TARGET_URL_KEY);
request.getSession().removeAttribute(ACEGI_SECURITY_TARGET_URL_KEY);
if (alwaysUseDefaultTargetUrl == true) {
targetUrl = null;
}
if (targetUrl == null) {
targetUrl = request.getContextPath() + defaultTargetUrl;
}
if (logger.isDebugEnabled()) {
logger.debug(
"Redirecting to target URL from HTTP Session (or default): "
+ targetUrl);
}
onSuccessfulAuthentication(request, response, authResult);
rememberMeServices.loginSuccess(request, response, authResult);
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
authResult, this.getClass()));
}
response.sendRedirect(response.encodeRedirectURL(targetUrl));
}
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException {
SecurityContextHolder.getContext().setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug(
"Updated SecurityContextHolder to contain null Authentication");
}
String failureUrl = exceptionMappings.getProperty(failed.getClass()
.getName(),
authenticationFailureUrl);
if (logger.isDebugEnabled()) {
logger.debug("Authentication request failed: " + failed.toString());
}
try {
request.getSession()
.setAttribute(ACEGI_SECURITY_LAST_EXCEPTION_KEY, failed);
} catch (Exception ignored) {}
onUnsuccessfulAuthentication(request, response, failed);
rememberMeServices.loginFail(request, response);
sendRedirect(request, response, failureUrl);
}
}
| core/src/main/java/org/acegisecurity/ui/AbstractProcessingFilter.java | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.ui;
import org.acegisecurity.AcegiMessageSource;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent;
import org.acegisecurity.ui.rememberme.NullRememberMeServices;
import org.acegisecurity.ui.rememberme.RememberMeServices;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Abstract processor of browser-based HTTP-based authentication requests.
*
* <p>
* This filter is responsible for processing authentication requests. If
* authentication is successful, the resulting {@link Authentication} object
* will be placed into the <code>SecurityContext</code>, which is guaranteed
* to have already been created by an earlier filter.
* </p>
*
* <p>
* If authentication fails, the <code>AuthenticationException</code> will be
* placed into the <code>HttpSession</code> with the attribute defined by
* {@link #ACEGI_SECURITY_LAST_EXCEPTION_KEY}.
* </p>
*
* <p>
* To use this filter, it is necessary to specify the following properties:
* </p>
*
* <ul>
* <li>
* <code>defaultTargetUrl</code> indicates the URL that should be used for
* redirection if the <code>HttpSession</code> attribute named {@link
* #ACEGI_SECURITY_TARGET_URL_KEY} does not indicate the target URL once
* authentication is completed successfully. eg: <code>/</code>. This will be
* treated as relative to the web-app's context path, and should include the
* leading <code>/</code>.
* </li>
* <li>
* <code>authenticationFailureUrl</code> indicates the URL that should be used
* for redirection if the authentication request fails. eg:
* <code>/login.jsp?login_error=1</code>.
* </li>
* <li>
* <code>filterProcessesUrl</code> indicates the URL that this filter will
* respond to. This parameter varies by subclass.
* </li>
* <li>
* <code>alwaysUseDefaultTargetUrl</code> causes successful authentication to
* always redirect to the <code>defaultTargetUrl</code>, even if the
* <code>HttpSession</code> attribute named {@link
* #ACEGI_SECURITY_TARGET_URL_KEY} defines the intended target URL.
* </li>
* </ul>
*
* <p>
* To configure this filter to redirect to specific pages as the result of
* specific {@link AuthenticationException}s you can do the following.
* Configure the <code>exceptionMappings</code> property in your application
* xml. This property is a java.util.Properties object that maps a
* fully-qualified exception class name to a redirection url target.<br>
* For example:<br>
* <code> <property name="exceptionMappings"><br>
* * <props><br>
* * <prop> key="org.acegisecurity.BadCredentialsException">/bad_credentials.jsp</prop><br>
* * </props><br>
* * </property><br>
* * </code><br>
* The example above would redirect all {@link
* org.acegisecurity.BadCredentialsException}s thrown, to a page in the
* web-application called /bad_credentials.jsp.
* </p>
*
* <p>
* Any {@link AuthenticationException} thrown that cannot be matched in the
* <code>exceptionMappings</code> will be redirected to the
* <code>authenticationFailureUrl</code>
* </p>
*
* <p>
* If authentication is successful, an {@link
* org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent}
* will be published to the application context. No events will be published
* if authentication was unsuccessful, because this would generally be
* recorded via an <code>AuthenticationManager</code>-specific application
* event.
* </p>
*/
public abstract class AbstractProcessingFilter implements Filter,
InitializingBean, ApplicationEventPublisherAware, MessageSourceAware {
//~ Static fields/initializers =============================================
public static final String ACEGI_SECURITY_TARGET_URL_KEY = "ACEGI_SECURITY_TARGET_URL";
public static final String ACEGI_SECURITY_LAST_EXCEPTION_KEY = "ACEGI_SECURITY_LAST_EXCEPTION";
protected static final Log logger = LogFactory.getLog(AbstractProcessingFilter.class);
//~ Instance fields ========================================================
protected ApplicationEventPublisher eventPublisher;
private AuthenticationManager authenticationManager;
protected MessageSourceAccessor messages = AcegiMessageSource.getAccessor();
private Properties exceptionMappings = new Properties();
private RememberMeServices rememberMeServices = new NullRememberMeServices();
/** Where to redirect the browser to if authentication fails */
private String authenticationFailureUrl;
/**
* Where to redirect the browser to if authentication is successful but
* ACEGI_SECURITY_TARGET_URL_KEY is <code>null</code>
*/
private String defaultTargetUrl;
/**
* The URL destination that this filter intercepts and processes (usually
* something like <code>/j_acegi_security_check</code>)
*/
private String filterProcessesUrl = getDefaultFilterProcessesUrl();
/**
* If <code>true</code>, will always redirect to {@link #defaultTargetUrl}
* upon successful authentication, irrespective of the page that caused
* the authentication request (defaults to <code>false</code>).
*/
private boolean alwaysUseDefaultTargetUrl = false;
/**
* Indicates if the filter chain should be continued prior to delegation to
* {@link #successfulAuthentication(HttpServletRequest,
* HttpServletResponse, Authentication)}, which may be useful in certain
* environment (eg Tapestry). Defaults to <code>false</code>.
*/
private boolean continueChainBeforeSuccessfulAuthentication = false;
//~ Methods ================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasLength(filterProcessesUrl,
"filterProcessesUrl must be specified");
Assert.hasLength(defaultTargetUrl, "defaultTargetUrl must be specified");
Assert.hasLength(authenticationFailureUrl,
"authenticationFailureUrl must be specified");
Assert.notNull(authenticationManager,
"authenticationManager must be specified");
Assert.notNull(this.rememberMeServices);
}
/**
* Performs actual authentication.
*
* @param request from which to extract parameters and perform the
* authentication
*
* @return the authenticated user
*
* @throws AuthenticationException if authentication fails
*/
public abstract Authentication attemptAuthentication(
HttpServletRequest request) throws AuthenticationException;
/**
* Does nothing. We use IoC container lifecycle services instead.
*/
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(response instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (requiresAuthentication(httpRequest, httpResponse)) {
if (logger.isDebugEnabled()) {
logger.debug("Request is to process authentication");
}
Authentication authResult;
try {
onPreAuthentication(httpRequest, httpResponse);
authResult = attemptAuthentication(httpRequest);
} catch (AuthenticationException failed) {
// Authentication failed
unsuccessfulAuthentication(httpRequest, httpResponse, failed);
return;
}
// Authentication success
if (continueChainBeforeSuccessfulAuthentication) {
chain.doFilter(request, response);
}
successfulAuthentication(httpRequest, httpResponse, authResult);
return;
}
chain.doFilter(request, response);
}
public String getAuthenticationFailureUrl() {
return authenticationFailureUrl;
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
/**
* Specifies the default <code>filterProcessesUrl</code> for the
* implementation.
*
* @return the default <code>filterProcessesUrl</code>
*/
public abstract String getDefaultFilterProcessesUrl();
public String getDefaultTargetUrl() {
return defaultTargetUrl;
}
public Properties getExceptionMappings() {
return new Properties(exceptionMappings);
}
public String getFilterProcessesUrl() {
return filterProcessesUrl;
}
public RememberMeServices getRememberMeServices() {
return rememberMeServices;
}
/**
* Does nothing. We use IoC container lifecycle services instead.
*
* @param arg0 ignored
*
* @throws ServletException ignored
*/
public void init(FilterConfig arg0) throws ServletException {}
public boolean isAlwaysUseDefaultTargetUrl() {
return alwaysUseDefaultTargetUrl;
}
public boolean isContinueChainBeforeSuccessfulAuthentication() {
return continueChainBeforeSuccessfulAuthentication;
}
protected void onPreAuthentication(HttpServletRequest request,
HttpServletResponse response)
throws AuthenticationException, IOException {}
protected void onSuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, Authentication authResult)
throws IOException {}
protected void onUnsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response) throws IOException {}
/**
* <p>
* Indicates whether this filter should attempt to process a login request
* for the current invocation.
* </p>
*
* <p>
* It strips any parameters from the "path" section of the request URL
* (such as the jsessionid parameter in
* <em>http://host/myapp/index.html;jsessionid=blah</em>) before matching
* against the <code>filterProcessesUrl</code> property.
* </p>
*
* <p>
* Subclasses may override for special requirements, such as Tapestry
* integration.
* </p>
*
* @param request as received from the filter chain
* @param response as received from the filter chain
*
* @return <code>true</code> if the filter should attempt authentication,
* <code>false</code> otherwise
*/
protected boolean requiresAuthentication(HttpServletRequest request,
HttpServletResponse response) {
String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';');
if (pathParamIndex > 0) {
// strip everything after the first semi-colon
uri = uri.substring(0, pathParamIndex);
}
return uri.endsWith(request.getContextPath() + filterProcessesUrl);
}
protected void sendRedirect(HttpServletRequest request,
HttpServletResponse response, String failureUrl)
throws IOException {
if (!failureUrl.startsWith("http://")
&& !failureUrl.startsWith("https://")) {
failureUrl = request.getContextPath() + failureUrl;
}
response.sendRedirect(response.encodeRedirectURL(failureUrl));
}
public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl) {
this.alwaysUseDefaultTargetUrl = alwaysUseDefaultTargetUrl;
}
public void setApplicationEventPublisher(
ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void setAuthenticationFailureUrl(String authenticationFailureUrl) {
this.authenticationFailureUrl = authenticationFailureUrl;
}
public void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public void setContinueChainBeforeSuccessfulAuthentication(
boolean continueChainBeforeSuccessfulAuthentication) {
this.continueChainBeforeSuccessfulAuthentication = continueChainBeforeSuccessfulAuthentication;
}
public void setDefaultTargetUrl(String defaultTargetUrl) {
this.defaultTargetUrl = defaultTargetUrl;
}
public void setExceptionMappings(Properties exceptionMappings) {
this.exceptionMappings = exceptionMappings;
}
public void setFilterProcessesUrl(String filterProcessesUrl) {
this.filterProcessesUrl = filterProcessesUrl;
}
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setRememberMeServices(RememberMeServices rememberMeServices) {
this.rememberMeServices = rememberMeServices;
}
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response, Authentication authResult)
throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authResult.toString());
}
SecurityContextHolder.getContext().setAuthentication(authResult);
if (logger.isDebugEnabled()) {
logger.debug(
"Updated SecurityContextHolder to contain the following Authentication: '"
+ authResult + "'");
}
String targetUrl = (String) request.getSession()
.getAttribute(ACEGI_SECURITY_TARGET_URL_KEY);
request.getSession().removeAttribute(ACEGI_SECURITY_TARGET_URL_KEY);
if (alwaysUseDefaultTargetUrl == true) {
targetUrl = null;
}
if (targetUrl == null) {
targetUrl = request.getContextPath() + defaultTargetUrl;
}
if (logger.isDebugEnabled()) {
logger.debug(
"Redirecting to target URL from HTTP Session (or default): "
+ targetUrl);
}
onSuccessfulAuthentication(request, response, authResult);
rememberMeServices.loginSuccess(request, response, authResult);
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
authResult, this.getClass()));
}
response.sendRedirect(response.encodeRedirectURL(targetUrl));
}
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException {
SecurityContextHolder.getContext().setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug(
"Updated SecurityContextHolder to contain null Authentication");
}
String failureUrl = exceptionMappings.getProperty(failed.getClass()
.getName(),
authenticationFailureUrl);
if (logger.isDebugEnabled()) {
logger.debug("Authentication request failed: " + failed.toString());
}
try {
request.getSession()
.setAttribute(ACEGI_SECURITY_LAST_EXCEPTION_KEY, failed);
} catch (Exception ignored) {}
onUnsuccessfulAuthentication(request, response);
rememberMeServices.loginFail(request, response);
sendRedirect(request, response, failureUrl);
}
}
| SEC-238: Add AuthenticationException to onUnsuccessfulAuthentication method signature.
| core/src/main/java/org/acegisecurity/ui/AbstractProcessingFilter.java | SEC-238: Add AuthenticationException to onUnsuccessfulAuthentication method signature. | <ide><path>ore/src/main/java/org/acegisecurity/ui/AbstractProcessingFilter.java
<ide> throws IOException {}
<ide>
<ide> protected void onUnsuccessfulAuthentication(HttpServletRequest request,
<del> HttpServletResponse response) throws IOException {}
<add> HttpServletResponse response, AuthenticationException failed)
<add> throws IOException {}
<ide>
<ide> /**
<ide> * <p>
<ide> .setAttribute(ACEGI_SECURITY_LAST_EXCEPTION_KEY, failed);
<ide> } catch (Exception ignored) {}
<ide>
<del> onUnsuccessfulAuthentication(request, response);
<add> onUnsuccessfulAuthentication(request, response, failed);
<ide>
<ide> rememberMeServices.loginFail(request, response);
<ide> |
|
Java | bsd-3-clause | 71346b4432a70269e264fa15d090eb90fb30302c | 0 | CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers | package gov.nih.nci.cabig.caaers.web.ae;
import static gov.nih.nci.cabig.caaers.CaaersUseCase.*;
import gov.nih.nci.cabig.caaers.CaaersUseCases;
import static gov.nih.nci.cabig.caaers.domain.Fixtures.*;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition;
import gov.nih.nci.cabig.caaers.service.EvaluationService;
import gov.nih.nci.cabig.caaers.service.ReportService;
import static org.easymock.classextension.EasyMock.expect;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
@CaaersUseCases({ CREATE_EXPEDITED_REPORT })
public class CheckpointTabTest extends AeTabTestCase {
private ReportDefinition r1, r2, r3;
private EvaluationService evaluationService;
private ReportService reportService;
@Override
protected void setUp() throws Exception {
evaluationService = registerMockFor(EvaluationService.class);
reportService = registerMockFor(ReportService.class);
super.setUp();
r1 = setId(1, createReportDefinition("R1"));
r2 = setId(2, createReportDefinition("R2"));
r3 = setId(3, createReportDefinition("R3"));
}
@Override
protected AeTab createTab() {
CheckpointTab tab = new CheckpointTab();
tab.setEvaluationService(evaluationService);
tab.setReportService(reportService);
return tab;
}
//TODO: fix the commented testcase URGENT
// public void testPostProcessAddsOptionalReports() throws Exception {
// assertEquals(0, command.getAeReport().getReports().size());
// List<ReportDefinition> reportDefs = new ArrayList<ReportDefinition>();
// reportDefs.add(r1);
// reportDefs.add(r2);
// reportDefs.add(r3);
//
// command.getOptionalReportDefinitionsMap().put(r1, Boolean.TRUE);
// command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
// command.getOptionalReportDefinitionsMap().put(r3, Boolean.TRUE);
// evaluationService.addOptionalReports(command.getAeReport(), reportDefs);
// expect(reportService.createReport(r1, command.getAeReport())).andReturn(null); // DC
// expect(reportService.createReport(r3, command.getAeReport())).andReturn(null); // DC
//
// replayMocks();
//
// getTab().postProcess(request, command, errors);
// verifyMocks();
// }
public void testPostProcessDoesNotInterfereWithExistingRequiredReports() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r1));
command.getOptionalReportDefinitionsMap().put(r2, Boolean.TRUE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
expect(reportService.createReport(r2, command.getAeReport())).andReturn(null); // DC
getTab().postProcess(request, command, errors);
List<Report> actualReports = command.getAeReport().getReports();
// note that IRL, this would be 2, but we mocked out the add of the optional
// and are only testing that the required report wasn't touched
assertEquals(1, actualReports.size());
assertEquals(r1, actualReports.get(0).getReportDefinition());
assertTrue(actualReports.get(0).isRequired());
}
public void testPostProcessRemovesDeselectedOptionalReports() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r1));
command.getAeReport().getReports().add(r2.createReport());
command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
// TODO: there will probably be a call to a service in here somewhere
getTab().postProcess(request, command, errors);
List<Report> actualReports = command.getAeReport().getReports();
assertEquals(1, actualReports.size());
assertEquals(r1, actualReports.get(0).getReportDefinition());
assertTrue(actualReports.get(0).isRequired());
}
public void testPostProcessDoesNotRemoveRequiredReportsEver() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r1));
// other code should prevent this situation from occurring, but just in case:
command.getOptionalReportDefinitionsMap().put(r1, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
// TODO: there will probably be a call to a service in here somewhere
getTab().postProcess(request, command, errors);
List<Report> actualReports = command.getAeReport().getReports();
assertEquals(1, actualReports.size());
assertEquals(r1, actualReports.get(0).getReportDefinition());
assertTrue(actualReports.get(0).isRequired());
}
private Report createRequiredReport(ReportDefinition def) {
Report reqd = def.createReport();
reqd.setRequired(true);
return reqd;
}
public void testPostProcessSavesWhenThereAreAnyReports() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r2));
reportDao.save(command.getAeReport());
replayMocks();
getTab().postProcess(request, command, errors);
verifyMocks();
}
public void testPostProcessDoesNotSaveWhenThereAreNoReports() throws Exception {
command.getAeReport().getReports().clear();
replayMocks();
getTab().postProcess(request, command, errors);
verifyMocks();
}
public void testPreProcessEvaluates() throws Exception {
evaluationService.addRequiredReports(command.getAeReport());
expect(evaluationService.applicableReportDefinitions(command.getAssignment()))
.andReturn(Collections.<ReportDefinition>emptyList());
replayMocks();
getTab().onDisplay(request, command);
verifyMocks();
}
public void testPreProcessSetsUpOptionalDefList() throws Exception {
command.getAeReport().getReports().clear();
command.getAeReport().addReport(r1.createReport());
command.getAeReport().addReport(createRequiredReport(r2));
evaluationService.addRequiredReports(command.getAeReport());
expect(evaluationService.applicableReportDefinitions(command.getAssignment()))
.andReturn(new ArrayList<ReportDefinition>(Arrays.asList(r1, r2, r3)));
replayMocks();
getTab().onDisplay(request, command);
verifyMocks();
Map<ReportDefinition,Boolean> map = command.getOptionalReportDefinitionsMap();
assertEquals("Wrong number of optional defs", 2, map.size());
assertTrue("Optional defs does not include r1", map.containsKey(r1));
assertTrue("Optional defs does not include r3", map.containsKey(r3));
}
public void testFieldsPresentForOptionalReports() throws Exception {
command.getAeReport().addReport(r2.createReport());
command.setOptionalReportDefinitions(Arrays.asList(r1, r2, r3));
assertFieldProperties("optionalReports",
"optionalReportDefinitionsMap[1]",
"optionalReportDefinitionsMap[2]",
"optionalReportDefinitionsMap[3]"
);
}
public void testNoReportsIsError() throws Exception {
command.getAeReport().getReports().clear();
replayMocks();
getTab().validate(command, errors);
verifyMocks();
assertEquals(1, errors.getErrorCount());
assertEquals(1, errors.getGlobalErrorCount());
assertEquals("At least one expedited report must be selected to proceed",
errors.getGlobalError().getDefaultMessage());
}
public void testAtLeastOneSelectedOptionalReportIsNotError() throws Exception {
command.getAeReport().getReports().clear();
command.getOptionalReportDefinitionsMap().put(r1, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r2, Boolean.TRUE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
replayMocks();
getTab().validate(command, errors);
verifyMocks();
assertEquals(0, errors.getErrorCount());
}
}
| projects/web/src/test/java/gov/nih/nci/cabig/caaers/web/ae/CheckpointTabTest.java | package gov.nih.nci.cabig.caaers.web.ae;
import static gov.nih.nci.cabig.caaers.CaaersUseCase.*;
import gov.nih.nci.cabig.caaers.CaaersUseCases;
import static gov.nih.nci.cabig.caaers.domain.Fixtures.*;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition;
import gov.nih.nci.cabig.caaers.service.EvaluationService;
import gov.nih.nci.cabig.caaers.service.ReportService;
import static org.easymock.classextension.EasyMock.expect;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
@CaaersUseCases({ CREATE_EXPEDITED_REPORT })
public class CheckpointTabTest extends AeTabTestCase {
private ReportDefinition r1, r2, r3;
private EvaluationService evaluationService;
private ReportService reportService;
@Override
protected void setUp() throws Exception {
evaluationService = registerMockFor(EvaluationService.class);
reportService = registerMockFor(ReportService.class);
super.setUp();
r1 = setId(1, createReportDefinition("R1"));
r2 = setId(2, createReportDefinition("R2"));
r3 = setId(3, createReportDefinition("R3"));
}
@Override
protected AeTab createTab() {
CheckpointTab tab = new CheckpointTab();
tab.setEvaluationService(evaluationService);
tab.setReportService(reportService);
return tab;
}
public void testPostProcessAddsOptionalReports() throws Exception {
assertEquals(0, command.getAeReport().getReports().size());
command.getOptionalReportDefinitionsMap().put(r1, Boolean.TRUE);
command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.TRUE);
expect(reportService.createReport(r1, command.getAeReport())).andReturn(null); // DC
expect(reportService.createReport(r3, command.getAeReport())).andReturn(null); // DC
replayMocks();
getTab().postProcess(request, command, errors);
verifyMocks();
}
public void testPostProcessDoesNotInterfereWithExistingRequiredReports() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r1));
command.getOptionalReportDefinitionsMap().put(r2, Boolean.TRUE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
expect(reportService.createReport(r2, command.getAeReport())).andReturn(null); // DC
getTab().postProcess(request, command, errors);
List<Report> actualReports = command.getAeReport().getReports();
// note that IRL, this would be 2, but we mocked out the add of the optional
// and are only testing that the required report wasn't touched
assertEquals(1, actualReports.size());
assertEquals(r1, actualReports.get(0).getReportDefinition());
assertTrue(actualReports.get(0).isRequired());
}
public void testPostProcessRemovesDeselectedOptionalReports() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r1));
command.getAeReport().getReports().add(r2.createReport());
command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
// TODO: there will probably be a call to a service in here somewhere
getTab().postProcess(request, command, errors);
List<Report> actualReports = command.getAeReport().getReports();
assertEquals(1, actualReports.size());
assertEquals(r1, actualReports.get(0).getReportDefinition());
assertTrue(actualReports.get(0).isRequired());
}
public void testPostProcessDoesNotRemoveRequiredReportsEver() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r1));
// other code should prevent this situation from occurring, but just in case:
command.getOptionalReportDefinitionsMap().put(r1, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
// TODO: there will probably be a call to a service in here somewhere
getTab().postProcess(request, command, errors);
List<Report> actualReports = command.getAeReport().getReports();
assertEquals(1, actualReports.size());
assertEquals(r1, actualReports.get(0).getReportDefinition());
assertTrue(actualReports.get(0).isRequired());
}
private Report createRequiredReport(ReportDefinition def) {
Report reqd = def.createReport();
reqd.setRequired(true);
return reqd;
}
public void testPostProcessSavesWhenThereAreAnyReports() throws Exception {
command.getAeReport().getReports().add(createRequiredReport(r2));
reportDao.save(command.getAeReport());
replayMocks();
getTab().postProcess(request, command, errors);
verifyMocks();
}
public void testPostProcessDoesNotSaveWhenThereAreNoReports() throws Exception {
command.getAeReport().getReports().clear();
replayMocks();
getTab().postProcess(request, command, errors);
verifyMocks();
}
public void testPreProcessEvaluates() throws Exception {
evaluationService.addRequiredReports(command.getAeReport());
expect(evaluationService.applicableReportDefinitions(command.getAssignment()))
.andReturn(Collections.<ReportDefinition>emptyList());
replayMocks();
getTab().onDisplay(request, command);
verifyMocks();
}
public void testPreProcessSetsUpOptionalDefList() throws Exception {
command.getAeReport().getReports().clear();
command.getAeReport().addReport(r1.createReport());
command.getAeReport().addReport(createRequiredReport(r2));
evaluationService.addRequiredReports(command.getAeReport());
expect(evaluationService.applicableReportDefinitions(command.getAssignment()))
.andReturn(new ArrayList<ReportDefinition>(Arrays.asList(r1, r2, r3)));
replayMocks();
getTab().onDisplay(request, command);
verifyMocks();
Map<ReportDefinition,Boolean> map = command.getOptionalReportDefinitionsMap();
assertEquals("Wrong number of optional defs", 2, map.size());
assertTrue("Optional defs does not include r1", map.containsKey(r1));
assertTrue("Optional defs does not include r3", map.containsKey(r3));
}
public void testFieldsPresentForOptionalReports() throws Exception {
command.getAeReport().addReport(r2.createReport());
command.setOptionalReportDefinitions(Arrays.asList(r1, r2, r3));
assertFieldProperties("optionalReports",
"optionalReportDefinitionsMap[1]",
"optionalReportDefinitionsMap[2]",
"optionalReportDefinitionsMap[3]"
);
}
public void testNoReportsIsError() throws Exception {
command.getAeReport().getReports().clear();
replayMocks();
getTab().validate(command, errors);
verifyMocks();
assertEquals(1, errors.getErrorCount());
assertEquals(1, errors.getGlobalErrorCount());
assertEquals("At least one expedited report must be selected to proceed",
errors.getGlobalError().getDefaultMessage());
}
public void testAtLeastOneSelectedOptionalReportIsNotError() throws Exception {
command.getAeReport().getReports().clear();
command.getOptionalReportDefinitionsMap().put(r1, Boolean.FALSE);
command.getOptionalReportDefinitionsMap().put(r2, Boolean.TRUE);
command.getOptionalReportDefinitionsMap().put(r3, Boolean.FALSE);
replayMocks();
getTab().validate(command, errors);
verifyMocks();
assertEquals(0, errors.getErrorCount());
}
}
| commented the postprocess testcase. (to be uncommented after fixing the error in testmethod)
SVN-Revision: 2783
| projects/web/src/test/java/gov/nih/nci/cabig/caaers/web/ae/CheckpointTabTest.java | commented the postprocess testcase. (to be uncommented after fixing the error in testmethod) | <ide><path>rojects/web/src/test/java/gov/nih/nci/cabig/caaers/web/ae/CheckpointTabTest.java
<ide> return tab;
<ide> }
<ide>
<del> public void testPostProcessAddsOptionalReports() throws Exception {
<del> assertEquals(0, command.getAeReport().getReports().size());
<del>
<del> command.getOptionalReportDefinitionsMap().put(r1, Boolean.TRUE);
<del> command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
<del> command.getOptionalReportDefinitionsMap().put(r3, Boolean.TRUE);
<del>
<del> expect(reportService.createReport(r1, command.getAeReport())).andReturn(null); // DC
<del> expect(reportService.createReport(r3, command.getAeReport())).andReturn(null); // DC
<del> replayMocks();
<del>
<del> getTab().postProcess(request, command, errors);
<del> verifyMocks();
<del> }
<add>//TODO: fix the commented testcase URGENT
<add>// public void testPostProcessAddsOptionalReports() throws Exception {
<add>// assertEquals(0, command.getAeReport().getReports().size());
<add>// List<ReportDefinition> reportDefs = new ArrayList<ReportDefinition>();
<add>// reportDefs.add(r1);
<add>// reportDefs.add(r2);
<add>// reportDefs.add(r3);
<add>//
<add>// command.getOptionalReportDefinitionsMap().put(r1, Boolean.TRUE);
<add>// command.getOptionalReportDefinitionsMap().put(r2, Boolean.FALSE);
<add>// command.getOptionalReportDefinitionsMap().put(r3, Boolean.TRUE);
<add>// evaluationService.addOptionalReports(command.getAeReport(), reportDefs);
<add>// expect(reportService.createReport(r1, command.getAeReport())).andReturn(null); // DC
<add>// expect(reportService.createReport(r3, command.getAeReport())).andReturn(null); // DC
<add>//
<add>// replayMocks();
<add>//
<add>// getTab().postProcess(request, command, errors);
<add>// verifyMocks();
<add>// }
<ide>
<ide> public void testPostProcessDoesNotInterfereWithExistingRequiredReports() throws Exception {
<ide> command.getAeReport().getReports().add(createRequiredReport(r1));
<ide> getTab().postProcess(request, command, errors);
<ide>
<ide> List<Report> actualReports = command.getAeReport().getReports();
<del> // note that IRL, this would be 2, but we mocked out the add of the optional
<add> // note that IRL, this would be 2, but we mocked out the add of the optional
<ide> // and are only testing that the required report wasn't touched
<ide> assertEquals(1, actualReports.size());
<ide> assertEquals(r1, actualReports.get(0).getReportDefinition());
<ide> getTab().postProcess(request, command, errors);
<ide> verifyMocks();
<ide> }
<del>
<add>
<ide> public void testPreProcessEvaluates() throws Exception {
<ide> evaluationService.addRequiredReports(command.getAeReport());
<ide> expect(evaluationService.applicableReportDefinitions(command.getAssignment()))
<ide> verifyMocks();
<ide>
<ide> Map<ReportDefinition,Boolean> map = command.getOptionalReportDefinitionsMap();
<del>
<add>
<ide> assertEquals("Wrong number of optional defs", 2, map.size());
<ide> assertTrue("Optional defs does not include r1", map.containsKey(r1));
<ide> assertTrue("Optional defs does not include r3", map.containsKey(r3)); |
|
Java | apache-2.0 | 9b83625c349eeeb3127a2f771b75e325128896c3 | 0 | apache/geronimo-specs,salyh/geronimo-specs,salyh/geronimo-specs,apache/geronimo-specs,apache/geronimo-specs,salyh/javamailspec,salyh/geronimo-specs | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.json.spi;
import javax.json.JsonArrayBuilder;
import javax.json.JsonBuilderFactory;
import javax.json.JsonException;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonReaderFactory;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParserFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
public abstract class JsonProvider {
private static final String DEFAULT_PROVIDER = "org.apache.johnzon.core.JsonProviderImpl";
protected JsonProvider() {
// no-op
}
public static JsonProvider provider() {
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<JsonProvider>() {
public JsonProvider run() {
return doLoadProvider();
}
});
}
return doLoadProvider();
}
private static JsonProvider doLoadProvider() throws JsonException {
final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
final Class<?> clazz = Class.forName("org.apache.geronimo.osgi.locator.ProviderLocator");
final Method getServices = clazz.getDeclaredMethod("getServices", String.class, Class.class, ClassLoader.class);
final List<JsonProvider> osgiProviders = (List<JsonProvider>) getServices.invoke(null, JsonProvider.class.getName(), JsonProvider.class, tccl);
if (osgiProviders != null && !osgiProviders.isEmpty()) {
return osgiProviders.iterator().next();
}
} catch (final Throwable e) {
// locator not available, try normal mode
}
// don't use Class.forName() to avoid to bind class to tccl if thats a classloader facade
// so implementing a simple SPI when ProviderLocator is not here
final String name = "META-INF/services/" + JsonProvider.class.getName();
try {
Enumeration<URL> configs;
if (tccl == null) {
configs = ClassLoader.getSystemResources(name);
} else {
configs = tccl.getResources(name);
}
if (configs.hasMoreElements()) {
InputStream in = null;
BufferedReader r = null;
final List<String> names = new ArrayList<String>();
try {
in = configs.nextElement().openStream();
r = new BufferedReader(new InputStreamReader(in, "utf-8"));
String l;
while ((l = r.readLine()) != null) {
if (l.startsWith("#")) {
continue;
}
return JsonProvider.class.cast(tccl.loadClass(l).newInstance());
}
} catch (final IOException x) {
// no-op
} finally {
try {
if (r != null) {
r.close();
}
} catch (final IOException y) {
// no-op
}
try {
if (in != null) {
in.close();
}
} catch (final IOException y) {
// no-op
}
}
}
} catch (final Exception ex) {
// no-op
}
try {
final Class<?> clazz = tccl.loadClass(DEFAULT_PROVIDER);
return JsonProvider.class.cast(clazz.newInstance());
} catch (final Throwable cnfe) {
throw new JsonException(DEFAULT_PROVIDER + " not found", cnfe);
}
}
public abstract JsonParser createParser(Reader reader);
public abstract JsonParser createParser(InputStream in);
public abstract JsonParserFactory createParserFactory(Map<String, ?> config);
public abstract JsonGenerator createGenerator(Writer writer);
public abstract JsonGenerator createGenerator(OutputStream out);
public abstract JsonGeneratorFactory createGeneratorFactory(Map<String, ?> config);
public abstract JsonReader createReader(Reader reader);
public abstract JsonReader createReader(InputStream in);
public abstract JsonWriter createWriter(Writer writer);
public abstract JsonWriter createWriter(OutputStream out);
public abstract JsonWriterFactory createWriterFactory(Map<String, ?> config);
public abstract JsonReaderFactory createReaderFactory(Map<String, ?> config);
public abstract JsonObjectBuilder createObjectBuilder();
public abstract JsonArrayBuilder createArrayBuilder();
public abstract JsonBuilderFactory createBuilderFactory(Map<String, ?> config);
}
| geronimo-json_1.0_spec/src/main/java/javax/json/spi/JsonProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.json.spi;
import javax.json.JsonArrayBuilder;
import javax.json.JsonBuilderFactory;
import javax.json.JsonException;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonReaderFactory;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParserFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
public abstract class JsonProvider {
private static final String DEFAULT_PROVIDER = "org.apache.fleece.core.JsonProviderImpl";
protected JsonProvider() {
// no-op
}
public static JsonProvider provider() {
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<JsonProvider>() {
public JsonProvider run() {
return doLoadProvider();
}
});
}
return doLoadProvider();
}
private static JsonProvider doLoadProvider() throws JsonException {
final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
final Class<?> clazz = Class.forName("org.apache.geronimo.osgi.locator.ProviderLocator");
final Method getServices = clazz.getDeclaredMethod("getServices", String.class, Class.class, ClassLoader.class);
final List<JsonProvider> osgiProviders = (List<JsonProvider>) getServices.invoke(null, JsonProvider.class.getName(), JsonProvider.class, tccl);
if (osgiProviders != null && !osgiProviders.isEmpty()) {
return osgiProviders.iterator().next();
}
} catch (final Throwable e) {
// locator not available, try normal mode
}
// don't use Class.forName() to avoid to bind class to tccl if thats a classloader facade
// so implementing a simple SPI when ProviderLocator is not here
final String name = "META-INF/services/" + JsonProvider.class.getName();
try {
Enumeration<URL> configs;
if (tccl == null) {
configs = ClassLoader.getSystemResources(name);
} else {
configs = tccl.getResources(name);
}
if (configs.hasMoreElements()) {
InputStream in = null;
BufferedReader r = null;
final List<String> names = new ArrayList<String>();
try {
in = configs.nextElement().openStream();
r = new BufferedReader(new InputStreamReader(in, "utf-8"));
String l;
while ((l = r.readLine()) != null) {
if (l.startsWith("#")) {
continue;
}
return JsonProvider.class.cast(tccl.loadClass(l).newInstance());
}
} catch (final IOException x) {
// no-op
} finally {
try {
if (r != null) {
r.close();
}
} catch (final IOException y) {
// no-op
}
try {
if (in != null) {
in.close();
}
} catch (final IOException y) {
// no-op
}
}
}
} catch (final Exception ex) {
// no-op
}
try {
final Class<?> clazz = tccl.loadClass(DEFAULT_PROVIDER);
return JsonProvider.class.cast(clazz.newInstance());
} catch (final Throwable cnfe) {
throw new JsonException(DEFAULT_PROVIDER + " not found", cnfe);
}
}
public abstract JsonParser createParser(Reader reader);
public abstract JsonParser createParser(InputStream in);
public abstract JsonParserFactory createParserFactory(Map<String, ?> config);
public abstract JsonGenerator createGenerator(Writer writer);
public abstract JsonGenerator createGenerator(OutputStream out);
public abstract JsonGeneratorFactory createGeneratorFactory(Map<String, ?> config);
public abstract JsonReader createReader(Reader reader);
public abstract JsonReader createReader(InputStream in);
public abstract JsonWriter createWriter(Writer writer);
public abstract JsonWriter createWriter(OutputStream out);
public abstract JsonWriterFactory createWriterFactory(Map<String, ?> config);
public abstract JsonReaderFactory createReaderFactory(Map<String, ?> config);
public abstract JsonObjectBuilder createObjectBuilder();
public abstract JsonArrayBuilder createArrayBuilder();
public abstract JsonBuilderFactory createBuilderFactory(Map<String, ?> config);
}
| s/fleece/johnzon/
git-svn-id: 60e751271f50ec028ae56d425821c1c711e0b018@1621859 13f79535-47bb-0310-9956-ffa450edef68
| geronimo-json_1.0_spec/src/main/java/javax/json/spi/JsonProvider.java | s/fleece/johnzon/ | <ide><path>eronimo-json_1.0_spec/src/main/java/javax/json/spi/JsonProvider.java
<ide> import java.util.ServiceLoader;
<ide>
<ide> public abstract class JsonProvider {
<del> private static final String DEFAULT_PROVIDER = "org.apache.fleece.core.JsonProviderImpl";
<add> private static final String DEFAULT_PROVIDER = "org.apache.johnzon.core.JsonProviderImpl";
<ide>
<ide> protected JsonProvider() {
<ide> // no-op |
|
Java | apache-2.0 | e0420d8d24fde07f3fa1784712f907c142f54e2f | 0 | dfoerderreuther/acs-aem-commons,bstopp/acs-aem-commons,dfoerderreuther/acs-aem-commons,SachinMali/acs-aem-commons,dfoerderreuther/acs-aem-commons,SachinMali/acs-aem-commons,dfoerderreuther/acs-aem-commons,SachinMali/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,bstopp/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,bstopp/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,SachinMali/acs-aem-commons,bstopp/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2013 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.redirectmaps.impl;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adobe.acs.commons.redirectmaps.models.MapEntry;
import com.adobe.acs.commons.redirectmaps.models.RedirectMapModel;
import com.day.cq.commons.jcr.JcrConstants;
import com.google.common.net.MediaType;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
/**
* Utilities for interacting with the redirect entries
*/
public class RedirectEntriesUtils {
private RedirectEntriesUtils() {
}
private static final Gson gson = new Gson();
private static final Logger log = LoggerFactory.getLogger(RedirectEntriesUtils.class);
protected static final List<String> readEntries(SlingHttpServletRequest request) throws IOException {
List<String> lines = null;
InputStream is = null;
try {
is = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE).adaptTo(InputStream.class);
lines = IOUtils.readLines(is);
log.debug("Loaded {} lines", lines.size());
} finally {
IOUtils.closeQuietly(is);
}
return lines;
}
protected static final void updateRedirectMap(SlingHttpServletRequest request, List<String> entries)
throws PersistenceException {
ModifiableValueMap mvm = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE)
.getChild(JcrConstants.JCR_CONTENT).adaptTo(ModifiableValueMap.class);
mvm.put(JcrConstants.JCR_DATA, StringUtils.join(entries, "\n"));
request.getResourceResolver().commit();
request.getResourceResolver().refresh();
log.debug("Changes saved...");
}
protected static final void writeEntriesToResponse(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException, IOException {
log.trace("writeEntriesToResponse");
log.debug("Requesting redirect maps from {}", request.getResource());
RedirectMapModel redirectMap = request.getResource().adaptTo(RedirectMapModel.class);
response.setContentType(MediaType.JSON_UTF_8.toString());
JsonElement entries = gson.toJsonTree(redirectMap.getEntries(), new TypeToken<List<MapEntry>>() {
}.getType());
Iterator<JsonElement> it = entries.getAsJsonArray().iterator();
for (int i = 0; it.hasNext(); i++) {
it.next().getAsJsonObject().addProperty("id", i);
}
IOUtils.write(entries.toString(), response.getOutputStream(), StandardCharsets.UTF_8);
}
}
| bundle/src/main/java/com/adobe/acs/commons/redirectmaps/impl/RedirectEntriesUtils.java | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2013 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.redirectmaps.impl;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adobe.acs.commons.redirectmaps.models.MapEntry;
import com.adobe.acs.commons.redirectmaps.models.RedirectMapModel;
import com.day.cq.commons.jcr.JcrConstants;
import com.google.common.net.MediaType;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
/**
* Utilities for interacting with the redirect entries
*/
public class RedirectEntriesUtils {
private RedirectEntriesUtils() {
};
private static final Gson gson = new Gson();
private static final Logger log = LoggerFactory.getLogger(RedirectEntriesUtils.class);
protected static final List<String> readEntries(SlingHttpServletRequest request) throws IOException {
List<String> lines = null;
InputStream is = null;
try {
is = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE).adaptTo(InputStream.class);
lines = IOUtils.readLines(is);
log.debug("Loaded {} lines", lines.size());
} finally {
IOUtils.closeQuietly(is);
}
return lines;
}
protected static final void updateRedirectMap(SlingHttpServletRequest request, List<String> entries)
throws PersistenceException {
ModifiableValueMap mvm = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE)
.getChild(JcrConstants.JCR_CONTENT).adaptTo(ModifiableValueMap.class);
mvm.put(JcrConstants.JCR_DATA, StringUtils.join(entries, "\n"));
request.getResourceResolver().commit();
request.getResourceResolver().refresh();
log.debug("Changes saved...");
}
protected static final void writeEntriesToResponse(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException, IOException {
log.trace("writeEntriesToResponse");
log.debug("Requesting redirect maps from {}", request.getResource());
RedirectMapModel redirectMap = request.getResource().adaptTo(RedirectMapModel.class);
response.setContentType(MediaType.JSON_UTF_8.toString());
JsonElement entries = gson.toJsonTree(redirectMap.getEntries(), new TypeToken<List<MapEntry>>() {
}.getType());
Iterator<JsonElement> it = entries.getAsJsonArray().iterator();
for (int i = 0; it.hasNext(); i++) {
it.next().getAsJsonObject().addProperty("id", i);
}
IOUtils.write(entries.toString(), response.getOutputStream(), StandardCharsets.UTF_8);
}
}
| Removing semi-colon | bundle/src/main/java/com/adobe/acs/commons/redirectmaps/impl/RedirectEntriesUtils.java | Removing semi-colon | <ide><path>undle/src/main/java/com/adobe/acs/commons/redirectmaps/impl/RedirectEntriesUtils.java
<ide> public class RedirectEntriesUtils {
<ide>
<ide> private RedirectEntriesUtils() {
<del> };
<add> }
<ide>
<ide> private static final Gson gson = new Gson();
<ide> |
|
Java | mit | 1bd0cb94501c1ac6d9b6c3f966476de2bb986784 | 0 | tlaplus/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus | package org.lamport.tla.toolbox.util.pref;
/**
*
* @author zambrovski
*/
public interface IPreferenceConstants
{
// TODO COMMENTS
public static final String P_PROJECT_ROOT_FILE = "ProjectRootFile";
public static final String P_PROJECT_OPENED_MODULES = "ProjectOpenedModules";
public static final String DEFAULT_NOT_SET = "not set";
public static final String P_PARSER_POPUP_ERRORS = "parserPopupErrors";
/**
* restore the same state of the specification after a restart
*
*/
public static final String I_RESTORE_LAST_SPEC = "restoreLastSpec";
public static final String I_PARSE_FILES_ON_MODIFY = "autoParseTopModules";
public static final String I_PARSE_MODULE_ON_MODIFY = "autoParseModule";
public static final String I_PARSE_SPEC_ON_MODIFY = "autoParseSpec";
public static final String I_SPEC_LOADED = "specLoadedName";
/** Resource persistent property for sticking info about the pcal algorithm */
public static final String CONTAINS_PCAL_ALGORITHM = "containsPCalAlgorithm";
}
| org.lamport.tla.toolbox/src/org/lamport/tla/toolbox/util/pref/IPreferenceConstants.java | package org.lamport.tla.toolbox.util.pref;
/**
*
* @author zambrovski
*/
public interface IPreferenceConstants
{
// TODO COMMENTS
public static final String P_PROJECT_ROOT_FILE = "ProjectRootFile";
public static final String P_PROJECT_OPENED_MODULES = "ProjectOpenedModules";
public static final String DEFAULT_NOT_SET = "not set";
public static final String P_PARSER_POPUP_ERRORS = "parserPopupErrors";
public static final String I_PARSE_FILES_ON_MODIFY = "autoParseTopModules";
public static final String I_PARSE_MODULE_ON_MODIFY = "autoParseModule";
public static final String I_PARSE_SPEC_ON_MODIFY = "autoParseSpec";
public static final String I_RESTORE_LAST_SPEC = "restoreLastSpec";
public static final String I_SPEC_LOADED = "specLoadedName";
/** Resource persistent property for sticking info about the pcal algorithm */
public static final String CONTAINS_PCAL_ALGORITHM = "containsPCalAlgorithm";
}
| comments
git-svn-id: 7acc490bd371dbc82047a939b87dc892fdc31f59@12832 76a6fc44-f60b-0410-a9a8-e67b0e8fc65c
| org.lamport.tla.toolbox/src/org/lamport/tla/toolbox/util/pref/IPreferenceConstants.java | comments | <ide><path>rg.lamport.tla.toolbox/src/org/lamport/tla/toolbox/util/pref/IPreferenceConstants.java
<ide>
<ide> public static final String P_PARSER_POPUP_ERRORS = "parserPopupErrors";
<ide>
<add> /**
<add> * restore the same state of the specification after a restart
<add> *
<add> */
<add> public static final String I_RESTORE_LAST_SPEC = "restoreLastSpec";
<add>
<ide> public static final String I_PARSE_FILES_ON_MODIFY = "autoParseTopModules";
<ide> public static final String I_PARSE_MODULE_ON_MODIFY = "autoParseModule";
<ide> public static final String I_PARSE_SPEC_ON_MODIFY = "autoParseSpec";
<del> public static final String I_RESTORE_LAST_SPEC = "restoreLastSpec";
<add>
<ide> public static final String I_SPEC_LOADED = "specLoadedName";
<ide>
<ide> /** Resource persistent property for sticking info about the pcal algorithm */ |
|
JavaScript | mit | 689f799e6d07a879ebd40e61aab9107ba85a5c97 | 0 | vedi/restifizer | /**
* Created by vedi on 10/09/16.
*/
'use strict';
const handlers = {};
let subscribed = false;
class SocketIoTransport {
constructor(options) {
this.transportName = 'socket.io';
this.sio = options.sio;
this.prefix = options.prefix || 'restifizer';
if (!subscribed) {
this.sio.on('connection', (socket) => {
socket.on(this.prefix, (payload) => {
try {
this.handle(socket, payload);
} catch (err) {
socket.emit('error', err);
}
});
});
subscribed = true;
}
}
addRoute(controller, method, paths, action, handlerFn) {
handlers[`${method}:${paths[0]}${action.path.length > 0 ? '/' : ''}${action.path}`] = (socket, payload) => {
const scope = action.createScope(controller, this);
payload.params = payload.params || {};
scope.transportData.socket = socket;
scope.transportData.payload = payload;
scope.transportData.result = {};
handlerFn(scope)
.then(() => {
socket.emit(this.prefix, {method, path: paths[0], result: scope.transportData.result});
});
};
}
pre(scope) {
}
post(scope) {
}
getQ(scope) {
return scope.transportData.payload.q;
}
getBody(scope) {
return scope.transportData.payload.body;
}
getParams(scope) {
return scope.transportData.payload.params;
}
getFields(scope) {
return scope.transportData.payload.fields;
}
getFilter(scope) {
return scope.transportData.payload.filter;
}
getOrderBy(scope) {
return scope.transportData.payload.orderBy;
}
getPagination(scope) {
return scope.transportData.payload.pagination;
}
setResData(data, scope, statusCode) {
if (typeof data != 'undefined') {
scope.restfulResult = data;
}
scope.statusCode = statusCode;
}
sendResult(result, scope) {
result = result || scope.restfulResult;
scope.transportData.result.body = result;
scope.transportData.result.statusCode = scope.statusCode;
}
handle(socket, payload) {
const handler = handlers[payload.route];
if (!handler) {
throw new Error(`Unhandled route: ${payload.route}`);
}
handler(socket, payload);
}
}
module.exports = SocketIoTransport; | lib/transports/socket-io.transport.js | /**
* Created by vedi on 10/09/16.
*/
'use strict';
const handlers = {};
let subscribed = false;
class SocketIoTransport {
constructor(options) {
this.transportName = 'socket.io';
this.sio = options.sio;
this.prefix = options.prefix || 'restifizer';
if (!subscribed) {
this.sio.on('connection', (socket) => {
socket.on(this.prefix, (payload) => {
this.handle(socket, payload);
});
});
subscribed = true;
}
}
addRoute(controller, method, paths, action, handlerFn) {
handlers[`${method}:${paths[0]}${action.path.length > 0 ? '/' : ''}${action.path}`] = (socket, payload) => {
const scope = action.createScope(controller, this);
payload.params = payload.params || {};
scope.transportData.socket = socket;
scope.transportData.payload = payload;
scope.transportData.result = {};
handlerFn(scope)
.then(() => {
socket.emit(this.prefix, {method, path: paths[0], result: scope.transportData.result});
});
};
}
pre(scope) {
}
post(scope) {
}
getQ(scope) {
return scope.transportData.payload.q;
}
getBody(scope) {
return scope.transportData.payload.body;
}
getParams(scope) {
return scope.transportData.payload.params;
}
getFields(scope) {
return scope.transportData.payload.fields;
}
getFilter(scope) {
return scope.transportData.payload.filter;
}
getOrderBy(scope) {
return scope.transportData.payload.orderBy;
}
getPagination(scope) {
return scope.transportData.payload.pagination;
}
setResData(data, scope, statusCode) {
if (typeof data != 'undefined') {
scope.restfulResult = data;
}
scope.statusCode = statusCode;
}
sendResult(result, scope) {
result = result || scope.restfulResult;
scope.transportData.result.body = result;
scope.transportData.result.statusCode = scope.statusCode;
}
handle(socket, payload) {
const handler = handlers[payload.route];
if (!handler) {
throw new Error(`Unhandled route: ${payload.route}`);
}
handler(socket, payload);
}
}
module.exports = SocketIoTransport; | improve error handling in socket.io
| lib/transports/socket-io.transport.js | improve error handling in socket.io | <ide><path>ib/transports/socket-io.transport.js
<ide> if (!subscribed) {
<ide> this.sio.on('connection', (socket) => {
<ide> socket.on(this.prefix, (payload) => {
<del> this.handle(socket, payload);
<add> try {
<add> this.handle(socket, payload);
<add> } catch (err) {
<add> socket.emit('error', err);
<add> }
<ide> });
<ide> });
<ide> subscribed = true; |
|
Java | mit | 4b661fe4a0410e58768084d181ca780919380b34 | 0 | hxhgit/java-jwt,Rebzie/java-jwt,FriedEgg/java-jwt,jccheok/java-jwt,xiaoligit/java-jwt | package com.auth0.jwt;
import static org.junit.Assert.*;
import com.auth0.jwt.impl.BasicPayloadHandler;
import com.auth0.jwt.impl.JwtProxyImpl;
import org.junit.Test;
/**
* Test harness for JwtProxy
*/
public class TestHarness {
@Test
public void testHarness() throws Exception {
final String secret = "This is a secret";
final Algorithm algorithm = Algorithm.HS256;
User user = new User();
user.setUsername("jwt");
user.setPassword("mypassword");
JwtProxy proxy = new JwtProxyImpl();
proxy.setPayloadHandler(new BasicPayloadHandler());
ClaimSet claimSet = new ClaimSet();
claimSet.setExp(24 * 60 * 60); // expire in 24 hours
String token = proxy.encode(algorithm, user, secret, claimSet);
Object payload = proxy.decode(algorithm, token, secret);
assertEquals("{\"username\":\"jwt\",\"password\":\"mypassword\"}",payload);
}
}
| src/test/java/com/auth0/jwt/TestHarness.java | package com.auth0.jwt;
import static org.junit.Assert.*;
import com.auth0.jwt.impl.BasicPayloadHandler;
import com.auth0.jwt.impl.JwtProxyImpl;
import org.junit.Test;
/**
* Test harness for JwtProxy
*/
public class TestHarness {
@Test
public void testHarness() throws Exception {
final String secret = "This is a secret";
final Algorithm algorithm = Algorithm.HS256;
User user = new User();
user.setUsername("jwt");
user.setPassword("mypassword");
JwtProxy proxy = new JwtProxyImpl();
proxy.setPayloadHandler(new BasicPayloadHandler());
ClaimSet claimSet = new ClaimSet();
claimSet.setExp(24 * 60 * 60); // expire in 24 hours
String token = proxy.encode(algorithm, user, secret, claimSet);
Object payload = proxy.decode(algorithm, token, secret);
assertEquals("{\"username\":\"jwt\",\"password\":\"mypassword\"}",payload);
}
}
| Changing tabs to spaces. | src/test/java/com/auth0/jwt/TestHarness.java | Changing tabs to spaces. | <ide><path>rc/test/java/com/auth0/jwt/TestHarness.java
<ide> */
<ide> public class TestHarness {
<ide>
<del> @Test
<del> public void testHarness() throws Exception {
<del>
<del> final String secret = "This is a secret";
<del> final Algorithm algorithm = Algorithm.HS256;
<del>
<del> User user = new User();
<del> user.setUsername("jwt");
<del> user.setPassword("mypassword");
<del>
<del> JwtProxy proxy = new JwtProxyImpl();
<del> proxy.setPayloadHandler(new BasicPayloadHandler());
<del>
<del> ClaimSet claimSet = new ClaimSet();
<del> claimSet.setExp(24 * 60 * 60); // expire in 24 hours
<del> String token = proxy.encode(algorithm, user, secret, claimSet);
<del>
<del> Object payload = proxy.decode(algorithm, token, secret);
<del> assertEquals("{\"username\":\"jwt\",\"password\":\"mypassword\"}",payload);
<del> }
<add> @Test
<add> public void testHarness() throws Exception {
<add>
<add> final String secret = "This is a secret";
<add> final Algorithm algorithm = Algorithm.HS256;
<add>
<add> User user = new User();
<add> user.setUsername("jwt");
<add> user.setPassword("mypassword");
<add>
<add> JwtProxy proxy = new JwtProxyImpl();
<add> proxy.setPayloadHandler(new BasicPayloadHandler());
<add>
<add> ClaimSet claimSet = new ClaimSet();
<add> claimSet.setExp(24 * 60 * 60); // expire in 24 hours
<add> String token = proxy.encode(algorithm, user, secret, claimSet);
<add>
<add> Object payload = proxy.decode(algorithm, token, secret);
<add> assertEquals("{\"username\":\"jwt\",\"password\":\"mypassword\"}",payload);
<add> }
<ide> } |
|
Java | epl-1.0 | 0d001d79ffbf853437dbf264824980624b893588 | 0 | spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4 | /*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.manifest.yaml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import java.io.IOException;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.DiagnosticSeverity;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFServiceInstance;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientRequests;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFCredentials;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.ClientParamsProvider;
import org.springframework.ide.vscode.languageserver.testharness.Editor;
import org.springframework.ide.vscode.languageserver.testharness.LanguageServerHarness;
import com.google.common.collect.ImmutableList;
public class ManifestYamlEditorTest {
LanguageServerHarness harness;
MockCloudfoundry cloudfoundry = new MockCloudfoundry();
@Before public void setup() throws Exception {
harness = new LanguageServerHarness(()-> new ManifestYamlLanguageServer(cloudfoundry.factory, cloudfoundry.paramsProvider));
harness.intialize(null);
}
@Test public void testReconcileCatchesParseError() throws Exception {
Editor editor = harness.newEditor(
"somemap: val\n"+
"- sequence"
);
editor.assertProblems(
"-|expected <block end>"
);
}
@Test public void reconcileRunsOnDocumentOpenAndChange() throws Exception {
LanguageServerHarness harness = new LanguageServerHarness(ManifestYamlLanguageServer::new);
harness.intialize(null);
Editor editor = harness.newEditor(
"somemap: val\n"+
"- sequence"
);
editor.assertProblems(
"-|expected <block end>"
);
editor.setText(
"- sequence\n" +
"zomemap: val"
);
editor.assertProblems(
"z|expected <block end>"
);
}
@Test
public void reconcileMisSpelledPropertyNames() throws Exception {
Editor editor;
editor = harness.newEditor(
"memory: 1G\n" +
"aplications:\n" +
" - buildpack: zbuildpack\n" +
" domain: zdomain\n" +
" name: foo"
);
editor.assertProblems("aplications|Unknown property");
//mispelled or not allowed at toplevel
editor = harness.newEditor(
"name: foo\n" +
"buildpeck: yahah\n" +
"memory: 1G\n" +
"memori: 1G\n"
);
editor.assertProblems(
"name|Unknown property",
"buildpeck|Unknown property",
"memori|Unknown property"
);
//mispelled or not allowed as nested
editor = harness.newEditor(
"applications:\n" +
"- name: fine\n" +
" buildpeck: yahah\n" +
" memory: 1G\n" +
" memori: 1G\n" +
" applications: bad\n"
);
editor.assertProblems(
"buildpeck|Unknown property",
"memori|Unknown property",
"applications|Unknown property"
);
}
@Test
public void reconcileStructuralProblems() throws Exception {
Editor editor;
//forgot the 'applications:' heading
editor = harness.newEditor(
"- name: foo"
);
editor.assertProblems(
"- name: foo|Expecting a 'Map' but found a 'Sequence'"
);
//forgot to make the '-' after applications
editor = harness.newEditor(
"applications:\n" +
" name: foo"
);
editor.assertProblems(
"name: foo|Expecting a 'Sequence' but found a 'Map'"
);
//Using a 'composite' element where a scalar type is expected
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
"memory:\n"+
"- bad sequence\n" +
"buildpack:\n" +
" bad: map\n"
);
editor.assertProblems(
"- bad sequence|Expecting a 'Memory' but found a 'Sequence'",
"bad: map|Expecting a 'Buildpack' but found a 'Map'"
);
}
@Test
public void reconcileSimpleTypes() throws Exception {
Editor editor;
//check for 'format' errors:
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: not a number\n" +
" no-route: notBool\n"+
" memory: 1024\n" +
" disk_quota: 2048\n" +
" health-check-type: unhealthy"
);
editor.assertProblems(
"not a number|NumberFormatException",
"notBool|boolean",
"1024|doesn't end with a valid unit of memory",
"2048|doesn't end with a valid unit of memory",
"unhealthy|Health Check Type"
);
//check for 'range' errors:
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: -3\n" +
" memory: -1024M\n" +
" disk_quota: -2048M\n"
);
editor.assertProblems(
"-3|Value must be at least 1",
"-1024M|Negative value is not allowed",
"-2048M|Negative value is not allowed"
);
//check that correct values are indeed accepted
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: 2\n" +
" no-route: true\n"+
" memory: 1024M\n" +
" disk_quota: 2048MB\n"
);
editor.assertProblems(/*none*/);
//check that correct values are indeed accepted
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: 2\n" +
" no-route: false\n" +
" memory: 1024m\n" +
" disk_quota: 2048mb\n"
);
editor.assertProblems(/*none*/);
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: 2\n" +
" memory: 1G\n" +
" disk_quota: 2g\n"
);
editor.assertProblems(/*none*/);
}
@Test
public void noListIndent() throws Exception {
Editor editor;
editor = harness.newEditor("appl<*>");
editor.assertCompletions(
"applications:\n"+
"- <*>"
);
}
@Test
public void toplevelCompletions() throws Exception {
Editor editor;
editor = harness.newEditor("<*>");
editor.assertCompletions(
"applications:\n"+
"- <*>",
// ---------------
"buildpack: <*>",
// ---------------
"command: <*>",
// ---------------
"disk_quota: <*>",
// ---------------
"domain: <*>",
// ---------------
"domains:\n"+
"- <*>",
// ---------------
"env:\n"+
" <*>",
// ---------------
"health-check-type: <*>",
// ---------------
// "host: <*>",
// ---------------
// "hosts: \n"+
// " - <*>",
// ---------------
"inherit: <*>",
// ---------------
"instances: <*>",
// ---------------
"memory: <*>",
// ---------------
// "name: <*>",
// ---------------
"no-hostname: <*>",
// ---------------
"no-route: <*>",
// ---------------
"path: <*>",
// ---------------
"random-route: <*>",
// ---------------
"services:\n"+
"- <*>",
// ---------------
"stack: <*>",
// ---------------
"timeout: <*>"
);
editor = harness.newEditor("ranro<*>");
editor.assertCompletions(
"random-route: <*>"
);
}
@Test
public void nestedCompletions() throws Exception {
Editor editor;
editor = harness.newEditor(
"applications:\n" +
"- <*>"
);
editor.assertCompletions(
// ---------------
"applications:\n" +
"- buildpack: <*>",
// ---------------
"applications:\n" +
"- command: <*>",
// ---------------
"applications:\n" +
"- disk_quota: <*>",
// ---------------
"applications:\n" +
"- domain: <*>",
// ---------------
"applications:\n" +
"- domains:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- env:\n"+
" <*>",
// ---------------
"applications:\n" +
"- health-check-type: <*>",
// ---------------
"applications:\n" +
"- host: <*>",
// ---------------
"applications:\n" +
"- hosts:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- instances: <*>",
// ---------------
"applications:\n" +
"- memory: <*>",
// ---------------
"applications:\n" +
"- name: <*>",
// ---------------
"applications:\n" +
"- no-hostname: <*>",
// ---------------
"applications:\n" +
"- no-route: <*>",
// ---------------
"applications:\n" +
"- path: <*>",
// ---------------
"applications:\n" +
"- random-route: <*>",
// ---------------
"applications:\n" +
"- services:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- stack: <*>",
// ---------------
"applications:\n" +
"- timeout: <*>"
);
}
@Test
public void completionDetailsAndDocs() throws Exception {
Editor editor = harness.newEditor(
"applications:\n" +
"- build<*>"
);
editor.assertCompletionDetails("buildpack", "Buildpack", "If your application requires a custom buildpack");
}
@Test
public void valueCompletions() throws Exception {
assertCompletions("disk_quota: <*>",
"disk_quota: 1024M<*>",
"disk_quota: 256M<*>",
"disk_quota: 512M<*>"
);
assertCompletions("memory: <*>",
"memory: 1024M<*>",
"memory: 256M<*>",
"memory: 512M<*>"
);
assertCompletions("no-hostname: <*>",
"no-hostname: false<*>",
"no-hostname: true<*>"
);
assertCompletions("no-route: <*>",
"no-route: false<*>",
"no-route: true<*>"
);
assertCompletions("random-route: <*>",
"random-route: false<*>",
"random-route: true<*>"
);
assertCompletions("health-check-type: <*>",
"health-check-type: none<*>",
"health-check-type: port<*>"
);
}
@Test
public void hoverInfos() throws Exception {
Editor editor = harness.newEditor(
"memory: 1G\n" +
"#comment\n" +
"inherit: base-manifest.yml\n"+
"applications:\n" +
"- buildpack: zbuildpack\n" +
" domain: zdomain\n" +
" name: foo\n" +
" command: java main.java\n" +
" disk_quota: 1024M\n" +
" domains:\n" +
" - pivotal.io\n" +
" - otherdomain.org\n" +
" env:\n" +
" RAILS_ENV: production\n" +
" RACK_ENV: production\n" +
" host: apppage\n" +
" hosts:\n" +
" - apppage2\n" +
" - appage3\n" +
" instances: 2\n" +
" no-hostname: true\n" +
" no-route: true\n" +
" path: somepath/app.jar\n" +
" random-route: true\n" +
" services:\n" +
" - instance_ABC\n" +
" - instance_XYZ\n" +
" stack: cflinuxfs2\n" +
" timeout: 80\n" +
" health-check-type: none\n"
);
editor.assertIsHoverRegion("memory");
editor.assertIsHoverRegion("inherit");
editor.assertIsHoverRegion("applications");
editor.assertIsHoverRegion("buildpack");
editor.assertIsHoverRegion("domain");
editor.assertIsHoverRegion("name");
editor.assertIsHoverRegion("command");
editor.assertIsHoverRegion("disk_quota");
editor.assertIsHoverRegion("domains");
editor.assertIsHoverRegion("env");
editor.assertIsHoverRegion("host");
editor.assertIsHoverRegion("hosts");
editor.assertIsHoverRegion("instances");
editor.assertIsHoverRegion("no-hostname");
editor.assertIsHoverRegion("no-route");
editor.assertIsHoverRegion("path");
editor.assertIsHoverRegion("random-route");
editor.assertIsHoverRegion("services");
editor.assertIsHoverRegion("stack");
editor.assertIsHoverRegion("timeout");
editor.assertIsHoverRegion("health-check-type");
editor.assertHoverContains("memory", "Use the `memory` attribute to specify the memory limit");
editor.assertHoverContains("1G", "Use the `memory` attribute to specify the memory limit");
editor.assertHoverContains("inherit", "For example, every child of a parent manifest called `base-manifest.yml` begins like this");
editor.assertHoverContains("buildpack", "use the `buildpack` attribute to specify its URL or name");
editor.assertHoverContains("name", "The `name` attribute is the only required attribute for an application in a manifest file");
editor.assertHoverContains("command", "On the command line, use the `-c` option to specify the custom start command as the following example shows");
editor.assertHoverContains("disk_quota", "Use the `disk_quota` attribute to allocate the disk space for your app instance");
editor.assertHoverContains("domain", "You can use the `domain` attribute when you want your application to be served");
editor.assertHoverContains("domains", "Use the `domains` attribute to provide multiple domains");
editor.assertHoverContains("env", "The `env` block consists of a heading, then one or more environment variable/value pairs");
editor.assertHoverContains("host", "Use the `host` attribute to provide a hostname, or subdomain, in the form of a string");
editor.assertHoverContains("hosts", "Use the `hosts` attribute to provide multiple hostnames, or subdomains");
editor.assertHoverContains("instances", "Use the `instances` attribute to specify the number of app instances that you want to start upon push");
editor.assertHoverContains("no-hostname", "By default, if you do not provide a hostname, the URL for the app takes the form of `APP-NAME.DOMAIN`");
editor.assertHoverContains("no-route", "You can use the `no-route` attribute with a value of `true` to prevent a route from being created for your application");
editor.assertHoverContains("path", "You can use the `path` attribute to tell Cloud Foundry where to find your application");
editor.assertHoverContains("random-route", "Use the `random-route` attribute to create a URL that includes the app name and random words");
editor.assertHoverContains("services", "The `services` block consists of a heading, then one or more service instance names");
editor.assertHoverContains("stack", "Use the `stack` attribute to specify which stack to deploy your application to.");
editor.assertHoverContains("timeout", "The `timeout` attribute defines the number of seconds Cloud Foundry allocates for starting your application");
editor.assertHoverContains("health-check-type", "Use the `health-check-type` attribute to");
}
@Test
public void noHoverInfos() throws Exception {
Editor editor = harness.newEditor(
"#comment\n" +
"applications:\n" +
"- buildpack: zbuildpack\n" +
" name: foo\n" +
" domains:\n" +
" - pivotal.io\n" +
" - otherdomain.org\n"
);
editor.assertNoHover("comment");
// May fail in the future if hover support is added, but if hover support is added in the future,
// it is expected that these should start to fail, as right now they have no hover
editor.assertNoHover("pivotal.io");
editor.assertNoHover("otherdomain.org");
}
@Test
public void reconcileDuplicateKeys() throws Exception {
Editor editor = harness.newEditor(
"#comment\n" +
"applications:\n" +
"- buildpack: zbuildpack\n" +
" name: foo\n" +
" domains:\n" +
" - pivotal.io\n" +
" domains:\n" +
" - otherdomain.org\n"
);
editor.assertProblems(
"domains|Duplicate key",
"domains|Duplicate key"
);
}
@Test public void PT_137299017_extra_space_with_completion() throws Exception {
assertCompletions(
"applications:\n" +
"- name: foo\n" +
" random-route:<*>"
, // ==>
"applications:\n" +
"- name: foo\n" +
" random-route: false<*>"
, // --
"applications:\n" +
"- name: foo\n" +
" random-route: true<*>"
);
}
@Test public void PT_137722057_extra_space_with_completion() throws Exception {
assertCompletions(
"applications:\n" +
"-<*>",
// ===>
"applications:\n" +
"- buildpack: <*>",
// ---------------
"applications:\n" +
"- command: <*>",
// ---------------
"applications:\n" +
"- disk_quota: <*>",
// ---------------
"applications:\n" +
"- domain: <*>",
// ---------------
"applications:\n" +
"- domains:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- env:\n"+
" <*>",
// ---------------
"applications:\n" +
"- health-check-type: <*>",
// ---------------
"applications:\n" +
"- host: <*>",
// ---------------
"applications:\n" +
"- hosts:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- instances: <*>",
// ---------------
"applications:\n" +
"- memory: <*>",
// ---------------
"applications:\n" +
"- name: <*>",
// ---------------
"applications:\n" +
"- no-hostname: <*>",
// ---------------
"applications:\n" +
"- no-route: <*>",
// ---------------
"applications:\n" +
"- path: <*>",
// ---------------
"applications:\n" +
"- random-route: <*>",
// ---------------
"applications:\n" +
"- services:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- stack: <*>",
// ---------------
"applications:\n" +
"- timeout: <*>"
);
//Second example
assertCompletions(
"applications:\n" +
"-<*>\n" +
"- name: test"
, // ==>
"applications:\n" +
"- buildpack: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- command: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- disk_quota: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- domain: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- domains:\n" +
" - <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- env:\n" +
" <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- health-check-type: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- host: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- hosts:\n" +
" - <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- instances: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- memory: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- name: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- no-hostname: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- no-route: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- path: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- random-route: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- services:\n" +
" - <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- stack: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- timeout: <*>\n" +
"- name: test"
);
}
@Test public void numberOfYamlDocumentsShouldBeExactlyOne() throws Exception {
Editor editor;
{
//when the file is empty (there is no AST at all)
editor = harness.newEditor("#Emptyfile");
editor.assertProblems("#Emptyfile|'Cloudfoundry Manifest' must have at least some Yaml content");
}
{
//when the file has too many documents... then highlight the '---' marker introducing the first document
//exceeding the range.
editor = harness.newEditor(
"---\n" +
"applications:\n"+
"- name: foo\n" +
" bad-one: xx\n" +
"---\n" +
"applications:\n"+
"- name: foo\n" +
" bad-two: xx"
);
editor.assertProblems(
"bad-one|Unknown property", //should still reconcile the documents even thought there's too many of them!
"---|'Cloudfoundry Manifest' should not have more than 1 Yaml Document",
"bad-two|Unknown property" //should still reconcile the documents even thought there's too many of them!
);
//also check the location of the marker since there are two occurrences of '---' in the editor text.
Diagnostic problem = editor.assertProblem("---");
assertTrue(problem.getRange().getStart().getLine()>1);
}
{
// Also check that looking for the '---' isn't confused by extra whitespace
editor = harness.newEditor(
"---\n" +
"applications:\n"+
"- name: foo\n" +
" \n"+
"---\n" +
" \n"+
"applications:\n"+
"- name: foo\n"
);
editor.assertProblems(
"---|'Cloudfoundry Manifest' should not have more than 1 Yaml Document"
);
//also check the location of the marker since there are two occurrences of '---' in the editor text.
Diagnostic problem = editor.assertProblem("---");
assertTrue(problem.getRange().getStart().getLine()>1);
}
}
@Test public void namePropertyIsRequired() throws Exception {
Editor editor = harness.newEditor(
"applications:\n" +
"- name: this-is-good\n" +
"- memory: 1G\n" +
"- name:\n"
);
editor.assertProblems(
"memory: 1G|Property 'name' is required",
"|should not be empty"
);
}
@Test
public void noReconcileErrorsWhenCFFactoryThrows() throws Exception {
reset(cloudfoundry.factory);
when(cloudfoundry.factory.getClient(any(), any())).thenThrow(new IOException("Can't create a client!"));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" buildpack: bad-buildpack\n" +
" services:\n" +
" - bad-service\n" +
" bogus: bad" //a token error to make sure reconciler is actually running!
);
editor.assertProblems("bogus|Unknown property");
}
@Test
public void noReconcileErrorsWhenClientThrows() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
when(cfClient.getBuildpacks()).thenThrow(new IOException("Can't get buildpacks"));
when(cfClient.getServices()).thenThrow(new IOException("Can't get services"));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" buildpack: bad-buildpack\n" +
" services:\n" +
" - bad-service\n" +
" bogus: bad" //a token error to make sure reconciler is actually running!
);
editor.assertProblems("bogus|Unknown property");
}
@Test
public void reconcileCFService() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
CFServiceInstance service = Mockito.mock(CFServiceInstance.class);
when(service.getName()).thenReturn("myservice");
when(cfClient.getServices()).thenReturn(ImmutableList.of(service));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" services:\n" +
" - myservice\n"
);
// Should have no problems
editor.assertProblems(/*none*/);
}
@Test
public void reconcileShowsWarningOnUnknownService() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
CFServiceInstance service = Mockito.mock(CFServiceInstance.class);
when(service.getName()).thenReturn("myservice");
when(cfClient.getServices()).thenReturn(ImmutableList.of(service));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" services:\n" +
" - bad-service\n"
);
editor.assertProblems("bad-service|There is no service instance called");
Diagnostic problem = editor.assertProblem("bad-service");
assertEquals(DiagnosticSeverity.Warning, problem.getSeverity());
}
@Test
public void reconcileShowsWarningOnNoService() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
when(cfClient.getServices()).thenReturn(ImmutableList.of());
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" services:\n" +
" - bad-service\n");
editor.assertProblems("bad-service|There is no service instance called");
Diagnostic problem = editor.assertProblem("bad-service");
assertEquals(DiagnosticSeverity.Warning, problem.getSeverity());
}
//////////////////////////////////////////////////////////////////////////////
private void assertCompletions(String textBefore, String... textAfter) throws Exception {
Editor editor = harness.newEditor(textBefore);
editor.assertCompletions(textAfter);
}
}
| vscode-extensions/vscode-manifest-yaml/src/test/java/org/springframework/ide/vscode/manifest/yaml/ManifestYamlEditorTest.java | /*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.manifest.yaml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import java.io.IOException;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.DiagnosticSeverity;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFServiceInstance;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientRequests;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFCredentials;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.ClientParamsProvider;
import org.springframework.ide.vscode.languageserver.testharness.Editor;
import org.springframework.ide.vscode.languageserver.testharness.LanguageServerHarness;
import com.google.common.collect.ImmutableList;
public class ManifestYamlEditorTest {
LanguageServerHarness harness;
MockCloudfoundry cloudfoundry = new MockCloudfoundry();
@Before public void setup() throws Exception {
harness = new LanguageServerHarness(()-> new ManifestYamlLanguageServer(cloudfoundry.factory, cloudfoundry.paramsProvider));
harness.intialize(null);
}
@Test public void testReconcileCatchesParseError() throws Exception {
Editor editor = harness.newEditor(
"somemap: val\n"+
"- sequence"
);
editor.assertProblems(
"-|expected <block end>"
);
}
@Test public void reconcileRunsOnDocumentOpenAndChange() throws Exception {
LanguageServerHarness harness = new LanguageServerHarness(ManifestYamlLanguageServer::new);
harness.intialize(null);
Editor editor = harness.newEditor(
"somemap: val\n"+
"- sequence"
);
editor.assertProblems(
"-|expected <block end>"
);
editor.setText(
"- sequence\n" +
"zomemap: val"
);
editor.assertProblems(
"z|expected <block end>"
);
}
@Test
public void reconcileMisSpelledPropertyNames() throws Exception {
Editor editor;
editor = harness.newEditor(
"memory: 1G\n" +
"aplications:\n" +
" - buildpack: zbuildpack\n" +
" domain: zdomain\n" +
" name: foo"
);
editor.assertProblems("aplications|Unknown property");
//mispelled or not allowed at toplevel
editor = harness.newEditor(
"name: foo\n" +
"buildpeck: yahah\n" +
"memory: 1G\n" +
"memori: 1G\n"
);
editor.assertProblems(
"name|Unknown property",
"buildpeck|Unknown property",
"memori|Unknown property"
);
//mispelled or not allowed as nested
editor = harness.newEditor(
"applications:\n" +
"- name: fine\n" +
" buildpeck: yahah\n" +
" memory: 1G\n" +
" memori: 1G\n" +
" applications: bad\n"
);
editor.assertProblems(
"buildpeck|Unknown property",
"memori|Unknown property",
"applications|Unknown property"
);
}
@Test
public void reconcileStructuralProblems() throws Exception {
Editor editor;
//forgot the 'applications:' heading
editor = harness.newEditor(
"- name: foo"
);
editor.assertProblems(
"- name: foo|Expecting a 'Map' but found a 'Sequence'"
);
//forgot to make the '-' after applications
editor = harness.newEditor(
"applications:\n" +
" name: foo"
);
editor.assertProblems(
"name: foo|Expecting a 'Sequence' but found a 'Map'"
);
//Using a 'composite' element where a scalar type is expected
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
"memory:\n"+
"- bad sequence\n" +
"buildpack:\n" +
" bad: map\n"
);
editor.assertProblems(
"- bad sequence|Expecting a 'Memory' but found a 'Sequence'",
"bad: map|Expecting a 'Buildpack' but found a 'Map'"
);
}
@Test
public void reconcileSimpleTypes() throws Exception {
Editor editor;
//check for 'format' errors:
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: not a number\n" +
" no-route: notBool\n"+
" memory: 1024\n" +
" disk_quota: 2048\n" +
" health-check-type: unhealthy"
);
editor.assertProblems(
"not a number|NumberFormatException",
"notBool|boolean",
"1024|doesn't end with a valid unit of memory",
"2048|doesn't end with a valid unit of memory",
"unhealthy|Health Check Type"
);
//check for 'range' errors:
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: -3\n" +
" memory: -1024M\n" +
" disk_quota: -2048M\n"
);
editor.assertProblems(
"-3|Value must be at least 1",
"-1024M|Negative value is not allowed",
"-2048M|Negative value is not allowed"
);
//check that correct values are indeed accepted
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: 2\n" +
" no-route: true\n"+
" memory: 1024M\n" +
" disk_quota: 2048MB\n"
);
editor.assertProblems(/*none*/);
//check that correct values are indeed accepted
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: 2\n" +
" no-route: false\n" +
" memory: 1024m\n" +
" disk_quota: 2048mb\n"
);
editor.assertProblems(/*none*/);
editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" instances: 2\n" +
" memory: 1G\n" +
" disk_quota: 2g\n"
);
editor.assertProblems(/*none*/);
}
@Test
public void noListIndent() throws Exception {
Editor editor;
editor = harness.newEditor("appl<*>");
editor.assertCompletions(
"applications:\n"+
"- <*>"
);
}
@Test
public void toplevelCompletions() throws Exception {
Editor editor;
editor = harness.newEditor("<*>");
editor.assertCompletions(
"applications:\n"+
"- <*>",
// ---------------
"buildpack: <*>",
// ---------------
"command: <*>",
// ---------------
"disk_quota: <*>",
// ---------------
"domain: <*>",
// ---------------
"domains:\n"+
"- <*>",
// ---------------
"env:\n"+
" <*>",
// ---------------
"health-check-type: <*>",
// ---------------
// "host: <*>",
// ---------------
// "hosts: \n"+
// " - <*>",
// ---------------
"inherit: <*>",
// ---------------
"instances: <*>",
// ---------------
"memory: <*>",
// ---------------
// "name: <*>",
// ---------------
"no-hostname: <*>",
// ---------------
"no-route: <*>",
// ---------------
"path: <*>",
// ---------------
"random-route: <*>",
// ---------------
"services:\n"+
"- <*>",
// ---------------
"stack: <*>",
// ---------------
"timeout: <*>"
);
editor = harness.newEditor("ranro<*>");
editor.assertCompletions(
"random-route: <*>"
);
}
@Test
public void nestedCompletions() throws Exception {
Editor editor;
editor = harness.newEditor(
"applications:\n" +
"- <*>"
);
editor.assertCompletions(
// ---------------
"applications:\n" +
"- buildpack: <*>",
// ---------------
"applications:\n" +
"- command: <*>",
// ---------------
"applications:\n" +
"- disk_quota: <*>",
// ---------------
"applications:\n" +
"- domain: <*>",
// ---------------
"applications:\n" +
"- domains:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- env:\n"+
" <*>",
// ---------------
"applications:\n" +
"- health-check-type: <*>",
// ---------------
"applications:\n" +
"- host: <*>",
// ---------------
"applications:\n" +
"- hosts:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- instances: <*>",
// ---------------
"applications:\n" +
"- memory: <*>",
// ---------------
"applications:\n" +
"- name: <*>",
// ---------------
"applications:\n" +
"- no-hostname: <*>",
// ---------------
"applications:\n" +
"- no-route: <*>",
// ---------------
"applications:\n" +
"- path: <*>",
// ---------------
"applications:\n" +
"- random-route: <*>",
// ---------------
"applications:\n" +
"- services:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- stack: <*>",
// ---------------
"applications:\n" +
"- timeout: <*>"
);
}
@Test
public void completionDetailsAndDocs() throws Exception {
Editor editor = harness.newEditor(
"applications:\n" +
"- build<*>"
);
editor.assertCompletionDetails("buildpack", "Buildpack", "If your application requires a custom buildpack");
}
@Test
public void valueCompletions() throws Exception {
assertCompletions("disk_quota: <*>",
"disk_quota: 1024M<*>",
"disk_quota: 256M<*>",
"disk_quota: 512M<*>"
);
assertCompletions("memory: <*>",
"memory: 1024M<*>",
"memory: 256M<*>",
"memory: 512M<*>"
);
assertCompletions("no-hostname: <*>",
"no-hostname: false<*>",
"no-hostname: true<*>"
);
assertCompletions("no-route: <*>",
"no-route: false<*>",
"no-route: true<*>"
);
assertCompletions("random-route: <*>",
"random-route: false<*>",
"random-route: true<*>"
);
assertCompletions("health-check-type: <*>",
"health-check-type: none<*>",
"health-check-type: port<*>"
);
}
@Test
public void hoverInfos() throws Exception {
Editor editor = harness.newEditor(
"memory: 1G\n" +
"#comment\n" +
"inherit: base-manifest.yml\n"+
"applications:\n" +
"- buildpack: zbuildpack\n" +
" domain: zdomain\n" +
" name: foo\n" +
" command: java main.java\n" +
" disk_quota: 1024M\n" +
" domains:\n" +
" - pivotal.io\n" +
" - otherdomain.org\n" +
" env:\n" +
" RAILS_ENV: production\n" +
" RACK_ENV: production\n" +
" host: apppage\n" +
" hosts:\n" +
" - apppage2\n" +
" - appage3\n" +
" instances: 2\n" +
" no-hostname: true\n" +
" no-route: true\n" +
" path: somepath/app.jar\n" +
" random-route: true\n" +
" services:\n" +
" - instance_ABC\n" +
" - instance_XYZ\n" +
" stack: cflinuxfs2\n" +
" timeout: 80\n" +
" health-check-type: none\n"
);
editor.assertIsHoverRegion("memory");
editor.assertIsHoverRegion("inherit");
editor.assertIsHoverRegion("applications");
editor.assertIsHoverRegion("buildpack");
editor.assertIsHoverRegion("domain");
editor.assertIsHoverRegion("name");
editor.assertIsHoverRegion("command");
editor.assertIsHoverRegion("disk_quota");
editor.assertIsHoverRegion("domains");
editor.assertIsHoverRegion("env");
editor.assertIsHoverRegion("host");
editor.assertIsHoverRegion("hosts");
editor.assertIsHoverRegion("instances");
editor.assertIsHoverRegion("no-hostname");
editor.assertIsHoverRegion("no-route");
editor.assertIsHoverRegion("path");
editor.assertIsHoverRegion("random-route");
editor.assertIsHoverRegion("services");
editor.assertIsHoverRegion("stack");
editor.assertIsHoverRegion("timeout");
editor.assertIsHoverRegion("health-check-type");
editor.assertHoverContains("memory", "Use the `memory` attribute to specify the memory limit");
editor.assertHoverContains("1G", "Use the `memory` attribute to specify the memory limit");
editor.assertHoverContains("inherit", "For example, every child of a parent manifest called `base-manifest.yml` begins like this");
editor.assertHoverContains("buildpack", "use the `buildpack` attribute to specify its URL or name");
editor.assertHoverContains("name", "The `name` attribute is the only required attribute for an application in a manifest file");
editor.assertHoverContains("command", "On the command line, use the `-c` option to specify the custom start command as the following example shows");
editor.assertHoverContains("disk_quota", "Use the `disk_quota` attribute to allocate the disk space for your app instance");
editor.assertHoverContains("domain", "You can use the `domain` attribute when you want your application to be served");
editor.assertHoverContains("domains", "Use the `domains` attribute to provide multiple domains");
editor.assertHoverContains("env", "The `env` block consists of a heading, then one or more environment variable/value pairs");
editor.assertHoverContains("host", "Use the `host` attribute to provide a hostname, or subdomain, in the form of a string");
editor.assertHoverContains("hosts", "Use the `hosts` attribute to provide multiple hostnames, or subdomains");
editor.assertHoverContains("instances", "Use the `instances` attribute to specify the number of app instances that you want to start upon push");
editor.assertHoverContains("no-hostname", "By default, if you do not provide a hostname, the URL for the app takes the form of `APP-NAME.DOMAIN`");
editor.assertHoverContains("no-route", "You can use the `no-route` attribute with a value of `true` to prevent a route from being created for your application");
editor.assertHoverContains("path", "You can use the `path` attribute to tell Cloud Foundry where to find your application");
editor.assertHoverContains("random-route", "Use the `random-route` attribute to create a URL that includes the app name and random words");
editor.assertHoverContains("services", "The `services` block consists of a heading, then one or more service instance names");
editor.assertHoverContains("stack", "Use the `stack` attribute to specify which stack to deploy your application to.");
editor.assertHoverContains("timeout", "The `timeout` attribute defines the number of seconds Cloud Foundry allocates for starting your application");
editor.assertHoverContains("health-check-type", "Use the `health-check-type` attribute to");
}
@Test
public void noHoverInfos() throws Exception {
Editor editor = harness.newEditor(
"#comment\n" +
"applications:\n" +
"- buildpack: zbuildpack\n" +
" name: foo\n" +
" domains:\n" +
" - pivotal.io\n" +
" - otherdomain.org\n"
);
editor.assertNoHover("comment");
// May fail in the future if hover support is added, but if hover support is added in the future,
// it is expected that these should start to fail, as right now they have no hover
editor.assertNoHover("pivotal.io");
editor.assertNoHover("otherdomain.org");
}
@Test
public void reconcileDuplicateKeys() throws Exception {
Editor editor = harness.newEditor(
"#comment\n" +
"applications:\n" +
"- buildpack: zbuildpack\n" +
" name: foo\n" +
" domains:\n" +
" - pivotal.io\n" +
" domains:\n" +
" - otherdomain.org\n"
);
editor.assertProblems(
"domains|Duplicate key",
"domains|Duplicate key"
);
}
@Test public void PT_137299017_extra_space_with_completion() throws Exception {
assertCompletions(
"applications:\n" +
"- name: foo\n" +
" random-route:<*>"
, // ==>
"applications:\n" +
"- name: foo\n" +
" random-route: false<*>"
, // --
"applications:\n" +
"- name: foo\n" +
" random-route: true<*>"
);
}
@Test public void PT_137722057_extra_space_with_completion() throws Exception {
assertCompletions(
"applications:\n" +
"-<*>",
// ===>
"applications:\n" +
"- buildpack: <*>",
// ---------------
"applications:\n" +
"- command: <*>",
// ---------------
"applications:\n" +
"- disk_quota: <*>",
// ---------------
"applications:\n" +
"- domain: <*>",
// ---------------
"applications:\n" +
"- domains:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- env:\n"+
" <*>",
// ---------------
"applications:\n" +
"- health-check-type: <*>",
// ---------------
"applications:\n" +
"- host: <*>",
// ---------------
"applications:\n" +
"- hosts:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- instances: <*>",
// ---------------
"applications:\n" +
"- memory: <*>",
// ---------------
"applications:\n" +
"- name: <*>",
// ---------------
"applications:\n" +
"- no-hostname: <*>",
// ---------------
"applications:\n" +
"- no-route: <*>",
// ---------------
"applications:\n" +
"- path: <*>",
// ---------------
"applications:\n" +
"- random-route: <*>",
// ---------------
"applications:\n" +
"- services:\n"+
" - <*>",
// ---------------
"applications:\n" +
"- stack: <*>",
// ---------------
"applications:\n" +
"- timeout: <*>"
);
//Second example
assertCompletions(
"applications:\n" +
"-<*>\n" +
"- name: test"
, // ==>
"applications:\n" +
"- buildpack: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- command: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- disk_quota: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- domain: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- domains:\n" +
" - <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- env:\n" +
" <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- health-check-type: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- host: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- hosts:\n" +
" - <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- instances: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- memory: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- name: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- no-hostname: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- no-route: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- path: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- random-route: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- services:\n" +
" - <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- stack: <*>\n" +
"- name: test"
, // ---------------------
"applications:\n" +
"- timeout: <*>\n" +
"- name: test"
);
}
@Test public void numberOfYamlDocumentsShouldBeExactlyOne() throws Exception {
Editor editor;
{
//when the file is empty (there is no AST at all)
editor = harness.newEditor("#Emptyfile");
editor.assertProblems("#Emptyfile|'Cloudfoundry Manifest' must have at least some Yaml content");
}
{
//when the file has too many documents... then highlight the '---' marker introducing the first document
//exceeding the range.
editor = harness.newEditor(
"---\n" +
"applications:\n"+
"- name: foo\n" +
" bad-one: xx\n" +
"---\n" +
"applications:\n"+
"- name: foo\n" +
" bad-two: xx"
);
editor.assertProblems(
"bad-one|Unknown property", //should still reconcile the documents even thought there's too many of them!
"---|'Cloudfoundry Manifest' should not have more than 1 Yaml Document",
"bad-two|Unknown property" //should still reconcile the documents even thought there's too many of them!
);
//also check the location of the marker since there are two occurrences of '---' in the editor text.
Diagnostic problem = editor.assertProblem("---");
assertTrue(problem.getRange().getStart().getLine()>1);
}
{
// Also check that looking for the '---' isn't confused by extra whitespace
editor = harness.newEditor(
"---\n" +
"applications:\n"+
"- name: foo\n" +
" \n"+
"---\n" +
" \n"+
"applications:\n"+
"- name: foo\n"
);
editor.assertProblems(
"---|'Cloudfoundry Manifest' should not have more than 1 Yaml Document"
);
//also check the location of the marker since there are two occurrences of '---' in the editor text.
Diagnostic problem = editor.assertProblem("---");
assertTrue(problem.getRange().getStart().getLine()>1);
}
}
@Test public void namePropertyIsRequired() throws Exception {
Editor editor = harness.newEditor(
"applications:\n" +
"- name: this-is-good\n" +
"- memory: 1G\n" +
"- name:\n"
);
editor.assertProblems(
"memory: 1G|Property 'name' is required",
"|should not be empty"
);
}
@Test
public void noReconcileErrorsWhenCFFactoryThrows() throws Exception {
reset(cloudfoundry.factory);
when(cloudfoundry.factory.getClient(any(), any())).thenThrow(new IOException("Can't create a client!"));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" buildpack: bad-buildpack\n" +
" services:\n" +
" - bad-service\n" +
" bogus: bad" //a token error to make sure reconciler is actually running!
);
editor.assertProblems("bogus|Unknown property");
}
@Test
public void noReconcileErrorsWhenClientThrows() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
when(cfClient.getBuildpacks()).thenThrow(new IOException("Can't get buildpacks"));
when(cfClient.getServices()).thenThrow(new IOException("Can't get services"));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" buildpack: bad-buildpack\n" +
" services:\n" +
" - bad-service\n" +
" bogus: bad" //a token error to make sure reconciler is actually running!
);
editor.assertProblems("bogus|Unknown property");
}
//////////////////////////////////////////////////////////////////////////////
// These tests are on ignore because they fail in the concourse ci build that uses OpenJDK.
// Possible issue is with mockito does not behave as expected using OpenJDK vs Oracle JVM
// These tests pass when running on an Oracle JVM.
@Test
public void reconcileCFService() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
CFServiceInstance service = Mockito.mock(CFServiceInstance.class);
when(service.getName()).thenReturn("myservice");
when(cfClient.getServices()).thenReturn(ImmutableList.of(service));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" services:\n" +
" - myservice\n"
);
// Should have no problems
editor.assertProblems(/*none*/);
}
@Test
public void reconcileShowsWarningOnUnknownService() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
CFServiceInstance service = Mockito.mock(CFServiceInstance.class);
when(service.getName()).thenReturn("myservice");
when(cfClient.getServices()).thenReturn(ImmutableList.of(service));
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" services:\n" +
" - bad-service\n"
);
editor.assertProblems("bad-service|There is no service instance called");
Diagnostic problem = editor.assertProblem("bad-service");
assertEquals(DiagnosticSeverity.Warning, problem.getSeverity());
}
@Ignore
@Test
public void reconcileShowsWarningOnNoService() throws Exception {
ClientRequests cfClient = cloudfoundry.client;
when(cfClient.getServices()).thenReturn(ImmutableList.of());
Editor editor = harness.newEditor(
"applications:\n" +
"- name: foo\n" +
" services:\n" +
" - bad-service\n");
editor.assertProblems("bad-service|There is no service instance called");
Diagnostic problem = editor.assertProblem("bad-service");
assertEquals(DiagnosticSeverity.Warning, problem.getSeverity());
}
//////////////////////////////////////////////////////////////////////////////
private void assertCompletions(String textBefore, String... textAfter) throws Exception {
Editor editor = harness.newEditor(textBefore);
editor.assertCompletions(textAfter);
}
}
| Cleanup obsolete comments, enable igored test that passes now | vscode-extensions/vscode-manifest-yaml/src/test/java/org/springframework/ide/vscode/manifest/yaml/ManifestYamlEditorTest.java | Cleanup obsolete comments, enable igored test that passes now | <ide><path>scode-extensions/vscode-manifest-yaml/src/test/java/org/springframework/ide/vscode/manifest/yaml/ManifestYamlEditorTest.java
<ide> editor.assertProblems("bogus|Unknown property");
<ide> }
<ide>
<del> //////////////////////////////////////////////////////////////////////////////
<del>
<del> // These tests are on ignore because they fail in the concourse ci build that uses OpenJDK.
<del> // Possible issue is with mockito does not behave as expected using OpenJDK vs Oracle JVM
<del> // These tests pass when running on an Oracle JVM.
<ide> @Test
<ide> public void reconcileCFService() throws Exception {
<ide> ClientRequests cfClient = cloudfoundry.client;
<ide> assertEquals(DiagnosticSeverity.Warning, problem.getSeverity());
<ide> }
<ide>
<del> @Ignore
<ide> @Test
<ide> public void reconcileShowsWarningOnNoService() throws Exception {
<ide> ClientRequests cfClient = cloudfoundry.client; |
|
Java | apache-2.0 | 8e6e70e71106f3277fcc7d0d578620e6647418b9 | 0 | SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.testing.server.entity;
import com.google.common.truth.BooleanSubject;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
import com.google.common.truth.extensions.proto.ProtoSubject;
import com.google.common.truth.extensions.proto.ProtoTruth;
import com.google.protobuf.Message;
import io.spine.server.entity.EntityWithLifecycle;
import io.spine.server.entity.LifecycleFlags;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import static com.google.common.truth.Truth.assertThat;
/**
* Assertions for entities.
*
* @param <T> the type of entity subject for parameter covariance in {@link Subject.Factory}
* @param <S> the type of the entity state message
* @param <E> the type of the entity
*/
public class EntitySubject<T extends EntitySubject<T, S, E>,
S extends Message,
E extends EntityWithLifecycle<?, S>>
extends Subject<T, E> {
protected EntitySubject(FailureMetadata metadata, @NullableDecl E actual) {
super(metadata, actual);
}
/**
* Verifies if the entity exists.
*/
public void exists() {
isNotNull();
}
/**
* Obtains the subject for the {@code archived} flag.
*/
public BooleanSubject archivedFlag() {
exists();
return assertThat(flags().getArchived());
}
/**
* Obtains the subject for the {@code deleted} flag.
*/
public BooleanSubject deletedFlag() {
exists();
return assertThat(flags().getDeleted());
}
private LifecycleFlags flags() {
return actual().getLifecycleFlags();
}
/**
* Obtains the subject for the state of the entity.
*/
public ProtoSubject<?, Message> hasStateThat() {
exists();
return ProtoTruth.assertThat(actual().getState());
}
}
| testutil-server/src/main/java/io/spine/testing/server/entity/EntitySubject.java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.testing.server.entity;
import com.google.common.truth.BooleanSubject;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
import com.google.common.truth.extensions.proto.ProtoSubject;
import com.google.common.truth.extensions.proto.ProtoTruth;
import com.google.protobuf.Message;
import io.spine.server.entity.EntityWithLifecycle;
import io.spine.server.entity.LifecycleFlags;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import static com.google.common.truth.Truth.assertThat;
/**
* Assertions for entities.
*
* @param <T> the type of entity subject for covariance
* @param <S> the type of the entity state message
* @param <E> the type of the entity
*/
public class EntitySubject<T extends EntitySubject<T, S, E>,
S extends Message,
E extends EntityWithLifecycle<?, S>>
extends Subject<T, E> {
protected EntitySubject(FailureMetadata metadata, @NullableDecl E actual) {
super(metadata, actual);
}
/**
* Verifies if the entity exists.
*/
public void exists() {
isNotNull();
}
/**
* Obtains the subject for the {@code archived} flag.
*/
public BooleanSubject archivedFlag() {
exists();
return assertThat(flags().getArchived());
}
/**
* Obtains the subject for the {@code deleted} flag.
*/
public BooleanSubject deletedFlag() {
exists();
return assertThat(flags().getDeleted());
}
private LifecycleFlags flags() {
return actual().getLifecycleFlags();
}
/**
* Obtains the subject for the state of the entity.
*/
public ProtoSubject<?, Message> hasStateThat() {
exists();
return ProtoTruth.assertThat(actual().getState());
}
}
| Improve Javadoc
| testutil-server/src/main/java/io/spine/testing/server/entity/EntitySubject.java | Improve Javadoc | <ide><path>estutil-server/src/main/java/io/spine/testing/server/entity/EntitySubject.java
<ide> /**
<ide> * Assertions for entities.
<ide> *
<del> * @param <T> the type of entity subject for covariance
<add> * @param <T> the type of entity subject for parameter covariance in {@link Subject.Factory}
<ide> * @param <S> the type of the entity state message
<ide> * @param <E> the type of the entity
<ide> */ |
|
Java | apache-2.0 | 82f715cceb95903bc494e92a0ebd9c51f8705daa | 0 | anshumanchatterji/selenium,arunsingh/selenium,quoideneuf/selenium,dibagga/selenium,joshuaduffy/selenium,sag-enorman/selenium,bayandin/selenium,i17c/selenium,jknguyen/josephknguyen-selenium,quoideneuf/selenium,aluedeke/chromedriver,chrsmithdemos/selenium,rovner/selenium,temyers/selenium,chrisblock/selenium,uchida/selenium,amar-sharma/selenium,gorlemik/selenium,orange-tv-blagnac/selenium,alexec/selenium,pulkitsinghal/selenium,TikhomirovSergey/selenium,freynaud/selenium,clavery/selenium,aluedeke/chromedriver,kalyanjvn1/selenium,freynaud/selenium,uchida/selenium,pulkitsinghal/selenium,SeleniumHQ/selenium,lukeis/selenium,dandv/selenium,isaksky/selenium,dbo/selenium,dkentw/selenium,sevaseva/selenium,houchj/selenium,wambat/selenium,xmhubj/selenium,orange-tv-blagnac/selenium,gemini-testing/selenium,amikey/selenium,p0deje/selenium,dandv/selenium,vveliev/selenium,Tom-Trumper/selenium,MCGallaspy/selenium,kalyanjvn1/selenium,mach6/selenium,bayandin/selenium,customcommander/selenium,joshmgrant/selenium,dkentw/selenium,vveliev/selenium,lilredindy/selenium,customcommander/selenium,lrowe/selenium,Tom-Trumper/selenium,freynaud/selenium,davehunt/selenium,gorlemik/selenium,blueyed/selenium,meksh/selenium,dcjohnson1989/selenium,titusfortner/selenium,houchj/selenium,customcommander/selenium,dimacus/selenium,Herst/selenium,telefonicaid/selenium,dibagga/selenium,dimacus/selenium,mestihudson/selenium,customcommander/selenium,yukaReal/selenium,twalpole/selenium,GorK-ChO/selenium,Sravyaksr/selenium,clavery/selenium,alb-i986/selenium,gurayinan/selenium,o-schneider/selenium,Sravyaksr/selenium,denis-vilyuzhanin/selenium-fastview,xsyntrex/selenium,GorK-ChO/selenium,asashour/selenium,jsakamoto/selenium,telefonicaid/selenium,vinay-qa/vinayit-android-server-apk,slongwang/selenium,sag-enorman/selenium,chrisblock/selenium,lukeis/selenium,BlackSmith/selenium,GorK-ChO/selenium,o-schneider/selenium,customcommander/selenium,dbo/selenium,dbo/selenium,sankha93/selenium,minhthuanit/selenium,carsonmcdonald/selenium,doungni/selenium,sri85/selenium,Herst/selenium,compstak/selenium,TikhomirovSergey/selenium,gotcha/selenium,clavery/selenium,DrMarcII/selenium,titusfortner/selenium,markodolancic/selenium,jsarenik/jajomojo-selenium,Appdynamics/selenium,TikhomirovSergey/selenium,isaksky/selenium,xmhubj/selenium,carsonmcdonald/selenium,zenefits/selenium,zenefits/selenium,krosenvold/selenium,gorlemik/selenium,xmhubj/selenium,jknguyen/josephknguyen-selenium,s2oBCN/selenium,rovner/selenium,bartolkaruza/selenium,SeleniumHQ/selenium,krmahadevan/selenium,dbo/selenium,rrussell39/selenium,mach6/selenium,thanhpete/selenium,houchj/selenium,arunsingh/selenium,dcjohnson1989/selenium,quoideneuf/selenium,MCGallaspy/selenium,sag-enorman/selenium,gemini-testing/selenium,markodolancic/selenium,twalpole/selenium,oddui/selenium,manuelpirez/selenium,valfirst/selenium,orange-tv-blagnac/selenium,meksh/selenium,dkentw/selenium,anshumanchatterji/selenium,blackboarddd/selenium,HtmlUnit/selenium,zenefits/selenium,xsyntrex/selenium,houchj/selenium,minhthuanit/selenium,lilredindy/selenium,tarlabs/selenium,Tom-Trumper/selenium,jsarenik/jajomojo-selenium,JosephCastro/selenium,GorK-ChO/selenium,bayandin/selenium,bayandin/selenium,amar-sharma/selenium,gabrielsimas/selenium,titusfortner/selenium,twalpole/selenium,denis-vilyuzhanin/selenium-fastview,jerome-jacob/selenium,Herst/selenium,jerome-jacob/selenium,oddui/selenium,petruc/selenium,Dude-X/selenium,juangj/selenium,amar-sharma/selenium,knorrium/selenium,jsarenik/jajomojo-selenium,amar-sharma/selenium,5hawnknight/selenium,sri85/selenium,jsakamoto/selenium,dandv/selenium,denis-vilyuzhanin/selenium-fastview,Appdynamics/selenium,Ardesco/selenium,stupidnetizen/selenium,jknguyen/josephknguyen-selenium,joshmgrant/selenium,xsyntrex/selenium,davehunt/selenium,i17c/selenium,Dude-X/selenium,temyers/selenium,orange-tv-blagnac/selenium,p0deje/selenium,jsakamoto/selenium,DrMarcII/selenium,markodolancic/selenium,amikey/selenium,Jarob22/selenium,tbeadle/selenium,mojwang/selenium,eric-stanley/selenium,isaksky/selenium,uchida/selenium,arunsingh/selenium,DrMarcII/selenium,eric-stanley/selenium,dandv/selenium,sankha93/selenium,doungni/selenium,carlosroh/selenium,alexec/selenium,krosenvold/selenium,gregerrag/selenium,TheBlackTuxCorp/selenium,uchida/selenium,Sravyaksr/selenium,bmannix/selenium,jerome-jacob/selenium,TheBlackTuxCorp/selenium,JosephCastro/selenium,bartolkaruza/selenium,zenefits/selenium,rplevka/selenium,sevaseva/selenium,carlosroh/selenium,manuelpirez/selenium,tarlabs/selenium,wambat/selenium,anshumanchatterji/selenium,doungni/selenium,gorlemik/selenium,alexec/selenium,JosephCastro/selenium,soundcloud/selenium,sankha93/selenium,asolntsev/selenium,livioc/selenium,xmhubj/selenium,onedox/selenium,livioc/selenium,gotcha/selenium,titusfortner/selenium,Ardesco/selenium,Dude-X/selenium,amikey/selenium,houchj/selenium,rrussell39/selenium,MeetMe/selenium,Appdynamics/selenium,lukeis/selenium,p0deje/selenium,sri85/selenium,bayandin/selenium,HtmlUnit/selenium,gotcha/selenium,livioc/selenium,krmahadevan/selenium,juangj/selenium,jknguyen/josephknguyen-selenium,twalpole/selenium,SeleniumHQ/selenium,vinay-qa/vinayit-android-server-apk,MeetMe/selenium,quoideneuf/selenium,sevaseva/selenium,dkentw/selenium,carlosroh/selenium,oddui/selenium,TikhomirovSergey/selenium,gabrielsimas/selenium,joshbruning/selenium,yukaReal/selenium,vinay-qa/vinayit-android-server-apk,meksh/selenium,RamaraoDonta/ramarao-clone,sebady/selenium,TikhomirovSergey/selenium,krosenvold/selenium,livioc/selenium,anshumanchatterji/selenium,dimacus/selenium,minhthuanit/selenium,o-schneider/selenium,SouWilliams/selenium,asashour/selenium,knorrium/selenium,SouWilliams/selenium,lukeis/selenium,blackboarddd/selenium,davehunt/selenium,HtmlUnit/selenium,gabrielsimas/selenium,MCGallaspy/selenium,stupidnetizen/selenium,bayandin/selenium,temyers/selenium,SouWilliams/selenium,dimacus/selenium,krosenvold/selenium,soundcloud/selenium,alb-i986/selenium,i17c/selenium,xmhubj/selenium,JosephCastro/selenium,actmd/selenium,oddui/selenium,chrisblock/selenium,compstak/selenium,joshmgrant/selenium,jabbrwcky/selenium,compstak/selenium,s2oBCN/selenium,minhthuanit/selenium,aluedeke/chromedriver,denis-vilyuzhanin/selenium-fastview,joshbruning/selenium,onedox/selenium,BlackSmith/selenium,carlosroh/selenium,BlackSmith/selenium,petruc/selenium,stupidnetizen/selenium,blueyed/selenium,livioc/selenium,gotcha/selenium,DrMarcII/selenium,dandv/selenium,jsakamoto/selenium,Dude-X/selenium,onedox/selenium,pulkitsinghal/selenium,xsyntrex/selenium,sebady/selenium,RamaraoDonta/ramarao-clone,doungni/selenium,SeleniumHQ/selenium,rrussell39/selenium,HtmlUnit/selenium,compstak/selenium,krmahadevan/selenium,lukeis/selenium,sri85/selenium,telefonicaid/selenium,Ardesco/selenium,sevaseva/selenium,SouWilliams/selenium,joshuaduffy/selenium,blackboarddd/selenium,soundcloud/selenium,AutomatedTester/selenium,chrsmithdemos/selenium,jabbrwcky/selenium,thanhpete/selenium,alexec/selenium,MeetMe/selenium,vveliev/selenium,aluedeke/chromedriver,gemini-testing/selenium,SouWilliams/selenium,asashour/selenium,SeleniumHQ/selenium,amikey/selenium,houchj/selenium,twalpole/selenium,manuelpirez/selenium,dkentw/selenium,misttechnologies/selenium,BlackSmith/selenium,eric-stanley/selenium,dbo/selenium,eric-stanley/selenium,livioc/selenium,anshumanchatterji/selenium,wambat/selenium,valfirst/selenium,lrowe/selenium,anshumanchatterji/selenium,joshmgrant/selenium,livioc/selenium,slongwang/selenium,gotcha/selenium,dandv/selenium,s2oBCN/selenium,o-schneider/selenium,mestihudson/selenium,titusfortner/selenium,bayandin/selenium,sebady/selenium,mojwang/selenium,jsarenik/jajomojo-selenium,onedox/selenium,gemini-testing/selenium,temyers/selenium,misttechnologies/selenium,tkurnosova/selenium,soundcloud/selenium,sevaseva/selenium,onedox/selenium,jsakamoto/selenium,sevaseva/selenium,asashour/selenium,valfirst/selenium,p0deje/selenium,petruc/selenium,tarlabs/selenium,rplevka/selenium,Jarob22/selenium,BlackSmith/selenium,minhthuanit/selenium,asolntsev/selenium,juangj/selenium,sebady/selenium,sag-enorman/selenium,dbo/selenium,joshuaduffy/selenium,telefonicaid/selenium,carsonmcdonald/selenium,o-schneider/selenium,i17c/selenium,freynaud/selenium,titusfortner/selenium,gorlemik/selenium,tbeadle/selenium,HtmlUnit/selenium,actmd/selenium,actmd/selenium,juangj/selenium,skurochkin/selenium,markodolancic/selenium,MeetMe/selenium,markodolancic/selenium,knorrium/selenium,lrowe/selenium,valfirst/selenium,krmahadevan/selenium,chrisblock/selenium,markodolancic/selenium,p0deje/selenium,isaksky/selenium,pulkitsinghal/selenium,i17c/selenium,arunsingh/selenium,jknguyen/josephknguyen-selenium,rovner/selenium,dkentw/selenium,petruc/selenium,doungni/selenium,twalpole/selenium,valfirst/selenium,stupidnetizen/selenium,yukaReal/selenium,JosephCastro/selenium,joshmgrant/selenium,stupidnetizen/selenium,knorrium/selenium,isaksky/selenium,minhthuanit/selenium,sebady/selenium,customcommander/selenium,uchida/selenium,livioc/selenium,alb-i986/selenium,jknguyen/josephknguyen-selenium,sri85/selenium,actmd/selenium,gorlemik/selenium,5hawnknight/selenium,amikey/selenium,xsyntrex/selenium,TheBlackTuxCorp/selenium,SouWilliams/selenium,rrussell39/selenium,HtmlUnit/selenium,Sravyaksr/selenium,tarlabs/selenium,gemini-testing/selenium,anshumanchatterji/selenium,valfirst/selenium,gotcha/selenium,gurayinan/selenium,Herst/selenium,lukeis/selenium,dcjohnson1989/selenium,DrMarcII/selenium,tarlabs/selenium,dkentw/selenium,lrowe/selenium,jabbrwcky/selenium,RamaraoDonta/ramarao-clone,tkurnosova/selenium,gabrielsimas/selenium,amar-sharma/selenium,houchj/selenium,freynaud/selenium,xsyntrex/selenium,zenefits/selenium,jabbrwcky/selenium,TheBlackTuxCorp/selenium,p0deje/selenium,clavery/selenium,denis-vilyuzhanin/selenium-fastview,chrsmithdemos/selenium,anshumanchatterji/selenium,jabbrwcky/selenium,p0deje/selenium,orange-tv-blagnac/selenium,sevaseva/selenium,Jarob22/selenium,sag-enorman/selenium,minhthuanit/selenium,actmd/selenium,mestihudson/selenium,actmd/selenium,yukaReal/selenium,Sravyaksr/selenium,thanhpete/selenium,joshbruning/selenium,blackboarddd/selenium,GorK-ChO/selenium,quoideneuf/selenium,manuelpirez/selenium,jabbrwcky/selenium,lrowe/selenium,MeetMe/selenium,telefonicaid/selenium,dkentw/selenium,DrMarcII/selenium,carsonmcdonald/selenium,rovner/selenium,gurayinan/selenium,5hawnknight/selenium,dandv/selenium,joshmgrant/selenium,mach6/selenium,Ardesco/selenium,thanhpete/selenium,juangj/selenium,chrisblock/selenium,BlackSmith/selenium,gurayinan/selenium,SevInf/IEDriver,rplevka/selenium,tkurnosova/selenium,thanhpete/selenium,asashour/selenium,rovner/selenium,Ardesco/selenium,rovner/selenium,eric-stanley/selenium,GorK-ChO/selenium,bayandin/selenium,orange-tv-blagnac/selenium,Tom-Trumper/selenium,jsarenik/jajomojo-selenium,jsarenik/jajomojo-selenium,HtmlUnit/selenium,jsakamoto/selenium,vveliev/selenium,skurochkin/selenium,bayandin/selenium,tbeadle/selenium,amar-sharma/selenium,Jarob22/selenium,krmahadevan/selenium,wambat/selenium,Sravyaksr/selenium,MeetMe/selenium,manuelpirez/selenium,TikhomirovSergey/selenium,sankha93/selenium,o-schneider/selenium,davehunt/selenium,mestihudson/selenium,amar-sharma/selenium,RamaraoDonta/ramarao-clone,davehunt/selenium,chrsmithdemos/selenium,kalyanjvn1/selenium,TheBlackTuxCorp/selenium,gregerrag/selenium,meksh/selenium,JosephCastro/selenium,aluedeke/chromedriver,i17c/selenium,tarlabs/selenium,Dude-X/selenium,compstak/selenium,temyers/selenium,gregerrag/selenium,xmhubj/selenium,thanhpete/selenium,isaksky/selenium,sri85/selenium,dibagga/selenium,oddui/selenium,RamaraoDonta/ramarao-clone,Tom-Trumper/selenium,vinay-qa/vinayit-android-server-apk,davehunt/selenium,lilredindy/selenium,vinay-qa/vinayit-android-server-apk,mojwang/selenium,TheBlackTuxCorp/selenium,HtmlUnit/selenium,vveliev/selenium,juangj/selenium,joshbruning/selenium,jsakamoto/selenium,MCGallaspy/selenium,JosephCastro/selenium,carlosroh/selenium,chrisblock/selenium,rplevka/selenium,freynaud/selenium,i17c/selenium,pulkitsinghal/selenium,dimacus/selenium,slongwang/selenium,blueyed/selenium,meksh/selenium,bmannix/selenium,bmannix/selenium,aluedeke/chromedriver,zenefits/selenium,blueyed/selenium,misttechnologies/selenium,amar-sharma/selenium,yukaReal/selenium,quoideneuf/selenium,gotcha/selenium,lmtierney/selenium,BlackSmith/selenium,bmannix/selenium,mojwang/selenium,skurochkin/selenium,gabrielsimas/selenium,SevInf/IEDriver,tbeadle/selenium,s2oBCN/selenium,telefonicaid/selenium,jerome-jacob/selenium,arunsingh/selenium,tkurnosova/selenium,yukaReal/selenium,SeleniumHQ/selenium,wambat/selenium,vveliev/selenium,dibagga/selenium,quoideneuf/selenium,GorK-ChO/selenium,petruc/selenium,gotcha/selenium,kalyanjvn1/selenium,knorrium/selenium,rplevka/selenium,chrsmithdemos/selenium,wambat/selenium,Appdynamics/selenium,bartolkaruza/selenium,tkurnosova/selenium,yukaReal/selenium,DrMarcII/selenium,rovner/selenium,chrsmithdemos/selenium,rrussell39/selenium,o-schneider/selenium,carlosroh/selenium,onedox/selenium,SeleniumHQ/selenium,BlackSmith/selenium,tarlabs/selenium,soundcloud/selenium,lmtierney/selenium,Dude-X/selenium,lrowe/selenium,rrussell39/selenium,gregerrag/selenium,gabrielsimas/selenium,dcjohnson1989/selenium,thanhpete/selenium,quoideneuf/selenium,blueyed/selenium,lrowe/selenium,i17c/selenium,GorK-ChO/selenium,arunsingh/selenium,meksh/selenium,Jarob22/selenium,jerome-jacob/selenium,bmannix/selenium,carsonmcdonald/selenium,Herst/selenium,blueyed/selenium,mestihudson/selenium,wambat/selenium,joshbruning/selenium,misttechnologies/selenium,Sravyaksr/selenium,meksh/selenium,stupidnetizen/selenium,asolntsev/selenium,SevInf/IEDriver,anshumanchatterji/selenium,gurayinan/selenium,MCGallaspy/selenium,kalyanjvn1/selenium,gregerrag/selenium,lukeis/selenium,dkentw/selenium,skurochkin/selenium,markodolancic/selenium,blackboarddd/selenium,dibagga/selenium,aluedeke/chromedriver,sevaseva/selenium,knorrium/selenium,petruc/selenium,sri85/selenium,carlosroh/selenium,sebady/selenium,vinay-qa/vinayit-android-server-apk,knorrium/selenium,knorrium/selenium,yukaReal/selenium,juangj/selenium,SevInf/IEDriver,skurochkin/selenium,Appdynamics/selenium,titusfortner/selenium,TheBlackTuxCorp/selenium,MeetMe/selenium,xmhubj/selenium,mach6/selenium,xmhubj/selenium,misttechnologies/selenium,stupidnetizen/selenium,joshuaduffy/selenium,compstak/selenium,jknguyen/josephknguyen-selenium,lmtierney/selenium,wambat/selenium,isaksky/selenium,dibagga/selenium,asashour/selenium,SeleniumHQ/selenium,soundcloud/selenium,mach6/selenium,gabrielsimas/selenium,freynaud/selenium,Herst/selenium,misttechnologies/selenium,mach6/selenium,thanhpete/selenium,rplevka/selenium,SouWilliams/selenium,jerome-jacob/selenium,dbo/selenium,onedox/selenium,AutomatedTester/selenium,denis-vilyuzhanin/selenium-fastview,RamaraoDonta/ramarao-clone,titusfortner/selenium,Tom-Trumper/selenium,petruc/selenium,gurayinan/selenium,eric-stanley/selenium,titusfortner/selenium,compstak/selenium,vinay-qa/vinayit-android-server-apk,arunsingh/selenium,5hawnknight/selenium,jabbrwcky/selenium,vveliev/selenium,mojwang/selenium,Tom-Trumper/selenium,gorlemik/selenium,temyers/selenium,bartolkaruza/selenium,Tom-Trumper/selenium,clavery/selenium,joshuaduffy/selenium,asashour/selenium,SeleniumHQ/selenium,tarlabs/selenium,uchida/selenium,Ardesco/selenium,zenefits/selenium,customcommander/selenium,clavery/selenium,MeetMe/selenium,AutomatedTester/selenium,jsarenik/jajomojo-selenium,dandv/selenium,gotcha/selenium,amikey/selenium,orange-tv-blagnac/selenium,krosenvold/selenium,Ardesco/selenium,s2oBCN/selenium,asolntsev/selenium,kalyanjvn1/selenium,twalpole/selenium,bartolkaruza/selenium,gabrielsimas/selenium,dibagga/selenium,MCGallaspy/selenium,jabbrwcky/selenium,doungni/selenium,s2oBCN/selenium,thanhpete/selenium,alexec/selenium,misttechnologies/selenium,pulkitsinghal/selenium,asashour/selenium,alb-i986/selenium,juangj/selenium,yukaReal/selenium,titusfortner/selenium,AutomatedTester/selenium,zenefits/selenium,xmhubj/selenium,temyers/selenium,lmtierney/selenium,blueyed/selenium,onedox/selenium,lilredindy/selenium,aluedeke/chromedriver,MCGallaspy/selenium,vveliev/selenium,valfirst/selenium,TikhomirovSergey/selenium,manuelpirez/selenium,rrussell39/selenium,mojwang/selenium,gregerrag/selenium,DrMarcII/selenium,JosephCastro/selenium,soundcloud/selenium,jsakamoto/selenium,krosenvold/selenium,gurayinan/selenium,carsonmcdonald/selenium,dcjohnson1989/selenium,bartolkaruza/selenium,RamaraoDonta/ramarao-clone,lrowe/selenium,jsarenik/jajomojo-selenium,actmd/selenium,misttechnologies/selenium,sri85/selenium,dandv/selenium,joshuaduffy/selenium,customcommander/selenium,dimacus/selenium,valfirst/selenium,slongwang/selenium,meksh/selenium,vinay-qa/vinayit-android-server-apk,knorrium/selenium,jknguyen/josephknguyen-selenium,mach6/selenium,asolntsev/selenium,rplevka/selenium,bmannix/selenium,tbeadle/selenium,sebady/selenium,oddui/selenium,i17c/selenium,tarlabs/selenium,TikhomirovSergey/selenium,mestihudson/selenium,gemini-testing/selenium,dbo/selenium,uchida/selenium,oddui/selenium,onedox/selenium,Appdynamics/selenium,gemini-testing/selenium,gurayinan/selenium,skurochkin/selenium,temyers/selenium,jsarenik/jajomojo-selenium,chrisblock/selenium,krosenvold/selenium,xsyntrex/selenium,sag-enorman/selenium,MCGallaspy/selenium,rrussell39/selenium,joshbruning/selenium,SevInf/IEDriver,tkurnosova/selenium,pulkitsinghal/selenium,carsonmcdonald/selenium,compstak/selenium,slongwang/selenium,lmtierney/selenium,joshbruning/selenium,doungni/selenium,isaksky/selenium,livioc/selenium,pulkitsinghal/selenium,lilredindy/selenium,p0deje/selenium,joshbruning/selenium,AutomatedTester/selenium,lilredindy/selenium,dcjohnson1989/selenium,bartolkaruza/selenium,arunsingh/selenium,blackboarddd/selenium,sankha93/selenium,RamaraoDonta/ramarao-clone,jsakamoto/selenium,oddui/selenium,bmannix/selenium,s2oBCN/selenium,Dude-X/selenium,Jarob22/selenium,slongwang/selenium,amikey/selenium,DrMarcII/selenium,Jarob22/selenium,gorlemik/selenium,alb-i986/selenium,jknguyen/josephknguyen-selenium,mestihudson/selenium,tbeadle/selenium,actmd/selenium,TheBlackTuxCorp/selenium,alexec/selenium,chrsmithdemos/selenium,jabbrwcky/selenium,bartolkaruza/selenium,AutomatedTester/selenium,chrisblock/selenium,uchida/selenium,dcjohnson1989/selenium,lilredindy/selenium,kalyanjvn1/selenium,alb-i986/selenium,Herst/selenium,bartolkaruza/selenium,alb-i986/selenium,freynaud/selenium,krmahadevan/selenium,soundcloud/selenium,misttechnologies/selenium,petruc/selenium,tbeadle/selenium,TikhomirovSergey/selenium,Herst/selenium,skurochkin/selenium,rplevka/selenium,SevInf/IEDriver,lmtierney/selenium,xsyntrex/selenium,dimacus/selenium,pulkitsinghal/selenium,jerome-jacob/selenium,sri85/selenium,Sravyaksr/selenium,Appdynamics/selenium,joshmgrant/selenium,lilredindy/selenium,s2oBCN/selenium,lrowe/selenium,isaksky/selenium,twalpole/selenium,markodolancic/selenium,gemini-testing/selenium,orange-tv-blagnac/selenium,carsonmcdonald/selenium,markodolancic/selenium,gabrielsimas/selenium,AutomatedTester/selenium,aluedeke/chromedriver,uchida/selenium,dcjohnson1989/selenium,sag-enorman/selenium,SeleniumHQ/selenium,lmtierney/selenium,lukeis/selenium,clavery/selenium,sankha93/selenium,slongwang/selenium,o-schneider/selenium,vveliev/selenium,bmannix/selenium,tkurnosova/selenium,xsyntrex/selenium,5hawnknight/selenium,davehunt/selenium,5hawnknight/selenium,mestihudson/selenium,telefonicaid/selenium,Dude-X/selenium,asolntsev/selenium,mach6/selenium,amikey/selenium,JosephCastro/selenium,joshmgrant/selenium,BlackSmith/selenium,blackboarddd/selenium,mojwang/selenium,Ardesco/selenium,soundcloud/selenium,skurochkin/selenium,bmannix/selenium,krmahadevan/selenium,davehunt/selenium,chrisblock/selenium,amar-sharma/selenium,juangj/selenium,orange-tv-blagnac/selenium,jerome-jacob/selenium,asolntsev/selenium,denis-vilyuzhanin/selenium-fastview,asashour/selenium,SouWilliams/selenium,kalyanjvn1/selenium,blueyed/selenium,eric-stanley/selenium,RamaraoDonta/ramarao-clone,rovner/selenium,Dude-X/selenium,lukeis/selenium,tbeadle/selenium,rplevka/selenium,minhthuanit/selenium,lmtierney/selenium,5hawnknight/selenium,wambat/selenium,joshmgrant/selenium,dcjohnson1989/selenium,titusfortner/selenium,valfirst/selenium,sankha93/selenium,Appdynamics/selenium,clavery/selenium,davehunt/selenium,AutomatedTester/selenium,Appdynamics/selenium,manuelpirez/selenium,krmahadevan/selenium,blueyed/selenium,rrussell39/selenium,carsonmcdonald/selenium,lmtierney/selenium,alexec/selenium,meksh/selenium,stupidnetizen/selenium,mestihudson/selenium,Jarob22/selenium,valfirst/selenium,krosenvold/selenium,SeleniumHQ/selenium,joshbruning/selenium,sankha93/selenium,alb-i986/selenium,slongwang/selenium,sankha93/selenium,dibagga/selenium,sebady/selenium,joshuaduffy/selenium,asolntsev/selenium,tbeadle/selenium,gemini-testing/selenium,mojwang/selenium,p0deje/selenium,sebady/selenium,alexec/selenium,chrsmithdemos/selenium,kalyanjvn1/selenium,dibagga/selenium,Herst/selenium,gorlemik/selenium,quoideneuf/selenium,vinay-qa/vinayit-android-server-apk,temyers/selenium,alb-i986/selenium,s2oBCN/selenium,doungni/selenium,denis-vilyuzhanin/selenium-fastview,eric-stanley/selenium,denis-vilyuzhanin/selenium-fastview,asolntsev/selenium,sag-enorman/selenium,alexec/selenium,freynaud/selenium,Jarob22/selenium,manuelpirez/selenium,SevInf/IEDriver,dimacus/selenium,customcommander/selenium,gregerrag/selenium,skurochkin/selenium,TheBlackTuxCorp/selenium,actmd/selenium,compstak/selenium,krosenvold/selenium,Tom-Trumper/selenium,petruc/selenium,Ardesco/selenium,MeetMe/selenium,dimacus/selenium,HtmlUnit/selenium,mach6/selenium,MCGallaspy/selenium,SevInf/IEDriver,clavery/selenium,valfirst/selenium,joshmgrant/selenium,eric-stanley/selenium,tkurnosova/selenium,SevInf/IEDriver,oddui/selenium,jerome-jacob/selenium,stupidnetizen/selenium,joshuaduffy/selenium,slongwang/selenium,doungni/selenium,blackboarddd/selenium,amikey/selenium,arunsingh/selenium,gregerrag/selenium,gregerrag/selenium,gurayinan/selenium,telefonicaid/selenium,chrsmithdemos/selenium,minhthuanit/selenium,SouWilliams/selenium,o-schneider/selenium,joshmgrant/selenium,HtmlUnit/selenium,sevaseva/selenium,twalpole/selenium,AutomatedTester/selenium,Sravyaksr/selenium,rovner/selenium,sag-enorman/selenium,5hawnknight/selenium,houchj/selenium,houchj/selenium,carlosroh/selenium,telefonicaid/selenium,carlosroh/selenium,manuelpirez/selenium,5hawnknight/selenium,lilredindy/selenium,tkurnosova/selenium,krmahadevan/selenium,dbo/selenium,mojwang/selenium,blackboarddd/selenium,joshuaduffy/selenium,GorK-ChO/selenium,zenefits/selenium | /*
Copyright 2011 Selenium committers
Copyright 2011 Software Freedom Conservancy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.testing.drivers;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
public class SauceDriver extends RemoteWebDriver {
private static final String SAUCE_JOB_NAME_ENV_NAME = "SAUCE_JOB_NAME";
private static final String SELENIUM_VERSION_ENV_NAME = "SAUCE_SELENIUM_VERSION";
private static final String SELENIUM_IEDRIVER_ENV_NAME = "SAUCE_IEDRIVER_VERSION";
private static final String SAUCE_APIKEY_ENV_NAME = "SAUCE_APIKEY";
private static final String SAUCE_USERNAME_ENV_NAME = "SAUCE_USERNAME";
private static final String DESIRED_BROWSER_VERSION_ENV_NAME = "SAUCE_BROWSER_VERSION";
private static final String SAUCE_DISABLE_VIDEO_ENV_NAME = "SAUCE_DISABLE_VIDEO";
private static final String SAUCE_BUILD_ENV_NAME = "SAUCE_BUILD_NUMBER";
private static final String SAUCE_NATIVE_ENV_NAME = "native_events";
private static final String SAUCE_REQUIRE_FOCUS_ENV_NAME = "REQUIRE_FOCUS";
private static final String USE_SAUCE_ENV_NAME = "USE_SAUCE";
// Should be one of the values listed for Platform, e.g. xp, win7, android, ...
private static final String DESIRED_OS_ENV_NAME = "SAUCE_OS";
// Optional to override default
private static final String SAUCE_URL_ENV_NAME = "SAUCE_URL";
private static final String DEFAULT_SAUCE_URL = "ondemand.saucelabs.com:80";
public SauceDriver(Capabilities desiredCapabilities) {
super(getSauceEndpoint(),
munge(
desiredCapabilities,
getSeleniumVersion(),
getDesiredBrowserVersion(),
getEffectivePlatform()));
System.out.println("Started new SauceDriver; see job at https://saucelabs.com/jobs/" + this.getSessionId());
}
private static String getDesiredBrowserVersion() {
return System.getenv(DESIRED_BROWSER_VERSION_ENV_NAME);
}
private static String getDesiredOS() {
return getNonNullEnv(DESIRED_OS_ENV_NAME);
}
private static String getSeleniumVersion() {
return getNonNullEnv(SELENIUM_VERSION_ENV_NAME);
}
private static String getNonNullEnv(String propertyName) {
String value = System.getenv(propertyName);
Preconditions.checkNotNull(value);
return value;
}
private static URL getSauceEndpoint() {
String sauceUsername = getNonNullEnv(SAUCE_USERNAME_ENV_NAME);
String sauceKey = getNonNullEnv(SAUCE_APIKEY_ENV_NAME);
String sauceUrl = System.getenv(SAUCE_URL_ENV_NAME);
if (sauceUrl == null) {
sauceUrl = DEFAULT_SAUCE_URL;
}
try {
return new URL(String.format("http://%s:%s@%s/wd/hub", sauceUsername, sauceKey, sauceUrl));
} catch (MalformedURLException e) {
Throwables.propagate(e);
}
throw new IllegalStateException("Should have returned or thrown");
}
private static Capabilities munge(Capabilities desiredCapabilities, String seleniumVersion, String browserVersion, Platform platform) {
DesiredCapabilities mungedCapabilities = new DesiredCapabilities(desiredCapabilities);
mungedCapabilities.setCapability("selenium-version", seleniumVersion);
mungedCapabilities.setCapability("idle-timeout", 180);
mungedCapabilities.setCapability("disable-popup-handler", true);
mungedCapabilities.setCapability("public", "public");
mungedCapabilities.setCapability("record-video", shouldRecordVideo());
mungedCapabilities.setCapability("build", System.getenv(SAUCE_BUILD_ENV_NAME));
String nativeEvents = System.getenv(SAUCE_NATIVE_ENV_NAME);
if (nativeEvents != null) {
String[] tags = {nativeEvents};
mungedCapabilities.setCapability("tags", tags);
}
mungedCapabilities.setCapability("prevent-requeue", false);
if (!Strings.isNullOrEmpty(browserVersion)) {
mungedCapabilities.setVersion(browserVersion);
}
mungedCapabilities.setPlatform(platform);
String jobName = System.getenv(SAUCE_JOB_NAME_ENV_NAME);
if (jobName != null) {
mungedCapabilities.setCapability("name", jobName);
}
if (DesiredCapabilities.internetExplorer().getBrowserName().equals(desiredCapabilities.getBrowserName())) {
String ieDriverVersion = System.getenv(SELENIUM_IEDRIVER_ENV_NAME);
if (ieDriverVersion != null) {
mungedCapabilities.setCapability("iedriver-version", ieDriverVersion);
}
mungedCapabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true);
}
String requireFocus = System.getenv(SAUCE_REQUIRE_FOCUS_ENV_NAME);
if (requireFocus != null) {
mungedCapabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS,
Boolean.parseBoolean(requireFocus));
}
return mungedCapabilities;
}
public static boolean shouldUseSauce() {
return System.getenv(USE_SAUCE_ENV_NAME) != null;
}
public static boolean shouldRecordVideo() {
return ! Boolean.parseBoolean(System.getenv(SAUCE_DISABLE_VIDEO_ENV_NAME));
}
public static Platform getEffectivePlatform() {
return Platform.extractFromSysProperty(getDesiredOS());
}
}
| java/client/test/org/openqa/selenium/testing/drivers/SauceDriver.java | /*
Copyright 2011 Selenium committers
Copyright 2011 Software Freedom Conservancy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.testing.drivers;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
public class SauceDriver extends RemoteWebDriver {
private static final String SAUCE_JOB_NAME_ENV_NAME = "SAUCE_JOB_NAME";
private static final String SELENIUM_VERSION_ENV_NAME = "SAUCE_SELENIUM_VERSION";
private static final String SELENIUM_IEDRIVER_ENV_NAME = "SAUCE_IEDRIVER_VERSION";
private static final String SAUCE_APIKEY_ENV_NAME = "SAUCE_APIKEY";
private static final String SAUCE_USERNAME_ENV_NAME = "SAUCE_USERNAME";
private static final String DESIRED_BROWSER_VERSION_ENV_NAME = "SAUCE_BROWSER_VERSION";
private static final String SAUCE_DISABLE_VIDEO_ENV_NAME = "SAUCE_DISABLE_VIDEO";
private static final String SAUCE_BUILD_ENV_NAME = "SAUCE_BUILD_NUMBER";
private static final String SAUCE_NATIVE_ENV_NAME = "native_events";
private static final String SAUCE_REQUIRE_FOCUS_ENV_NAME = "REQUIRE_FOCUS";
private static final String USE_SAUCE_ENV_NAME = "USE_SAUCE";
// Should be one of the values listed for Platform, e.g. xp, win7, android, ...
private static final String DESIRED_OS_ENV_NAME = "SAUCE_OS";
// Optional to override default
private static final String SAUCE_URL_ENV_NAME = "SAUCE_URL";
private static final String DEFAULT_SAUCE_URL = "ondemand.saucelabs.com:80";
public SauceDriver(Capabilities desiredCapabilities) {
super(getSauceEndpoint(),
munge(
desiredCapabilities,
getSeleniumVersion(),
getDesiredBrowserVersion(),
getEffectivePlatform()));
System.out.println("Started new SauceDriver; see job at https://saucelabs.com/jobs/" + this.getSessionId());
}
private static String getDesiredBrowserVersion() {
return System.getenv(DESIRED_BROWSER_VERSION_ENV_NAME);
}
private static String getDesiredOS() {
return getNonNullEnv(DESIRED_OS_ENV_NAME);
}
private static String getSeleniumVersion() {
return getNonNullEnv(SELENIUM_VERSION_ENV_NAME);
}
private static String getNonNullEnv(String propertyName) {
String value = System.getenv(propertyName);
Preconditions.checkNotNull(value);
return value;
}
private static URL getSauceEndpoint() {
String sauceUsername = getNonNullEnv(SAUCE_USERNAME_ENV_NAME);
String sauceKey = getNonNullEnv(SAUCE_APIKEY_ENV_NAME);
String sauceUrl = System.getenv(SAUCE_URL_ENV_NAME);
if (sauceUrl == null) {
sauceUrl = DEFAULT_SAUCE_URL;
}
try {
return new URL(String.format("http://%s:%s@%s/wd/hub", sauceUsername, sauceKey, sauceUrl));
} catch (MalformedURLException e) {
Throwables.propagate(e);
}
throw new IllegalStateException("Should have returned or thrown");
}
private static Capabilities munge(Capabilities desiredCapabilities, String seleniumVersion, String browserVersion, Platform platform) {
DesiredCapabilities mungedCapabilities = new DesiredCapabilities(desiredCapabilities);
mungedCapabilities.setCapability("selenium-version", seleniumVersion);
mungedCapabilities.setCapability("idle-timeout", 180);
mungedCapabilities.setCapability("disable-popup-handler", true);
mungedCapabilities.setCapability("public", "public");
mungedCapabilities.setCapability("record-video", shouldRecordVideo());
mungedCapabilities.setCapability("build", System.getenv(SAUCE_BUILD_ENV_NAME));
String nativeEvents = System.getenv(SAUCE_NATIVE_ENV_NAME);
if (nativeEvents != null) {
String[] tags = {nativeEvents};
mungedCapabilities.setCapability("tags", tags);
}
mungedCapabilities.setCapability("prevent-requeue", false);
if (!Strings.isNullOrEmpty(browserVersion)) {
mungedCapabilities.setVersion(browserVersion);
}
mungedCapabilities.setPlatform(platform);
String jobName = System.getenv(SAUCE_JOB_NAME_ENV_NAME);
if (jobName != null) {
mungedCapabilities.setCapability("name", jobName);
}
if (DesiredCapabilities.internetExplorer().getBrowserName().equals(desiredCapabilities.getBrowserName())) {
String ieDriverVersion = System.getenv(SELENIUM_IEDRIVER_ENV_NAME);
if (ieDriverVersion != null) {
mungedCapabilities.setCapability("iedriver-version", ieDriverVersion);
}
}
String requireFocus = System.getenv(SAUCE_REQUIRE_FOCUS_ENV_NAME);
if (requireFocus != null) {
mungedCapabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS,
Boolean.parseBoolean(requireFocus));
}
return mungedCapabilities;
}
public static boolean shouldUseSauce() {
return System.getenv(USE_SAUCE_ENV_NAME) != null;
}
public static boolean shouldRecordVideo() {
return ! Boolean.parseBoolean(System.getenv(SAUCE_DISABLE_VIDEO_ENV_NAME));
}
public static Platform getEffectivePlatform() {
return Platform.extractFromSysProperty(getDesiredOS());
}
}
| Setting requireWindowFocus to true when running tests on Sauce
| java/client/test/org/openqa/selenium/testing/drivers/SauceDriver.java | Setting requireWindowFocus to true when running tests on Sauce | <ide><path>ava/client/test/org/openqa/selenium/testing/drivers/SauceDriver.java
<ide> if (ieDriverVersion != null) {
<ide> mungedCapabilities.setCapability("iedriver-version", ieDriverVersion);
<ide> }
<add> mungedCapabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true);
<ide> }
<ide>
<ide> String requireFocus = System.getenv(SAUCE_REQUIRE_FOCUS_ENV_NAME); |
|
Java | apache-2.0 | 892114f613e21282141175ff9d86b2892d64cacd | 0 | samaxes/javaee-cache-filter | /*
*
* Copyright 2011 samaxes.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.samaxes.filter.util;
/**
* Possible Cache-Control directives for cacheable responses.
*
* @author Samuel Santos
* @author John Yeary
* @version 2.0.1
*/
public enum Cacheability {
/**
* Indicates that the response MAY be cached by any cache, even if it would
* normally be non-cacheable or cacheable only within a non-shared cache.
*/
PUBLIC("public"),
/**
* Indicates that all or part of the response message is intended for a
* single user and MUST NOT be cached by a shared cache. This allows an
* origin server to state that the specified parts of the response are
* intended for only one user and are not a valid response for requests by
* other users. A private (non-shared) cache MAY cache the response.
*/
PRIVATE("private");
private final String value;
private Cacheability(String value) {
this.value = value;
}
/**
* Gets the Cache-Control directive value.
*
* @return the Cache-Control directive value
*/
public String getValue() {
return this.value;
}
}
| src/main/java/com/samaxes/filter/util/Cacheability.java | /*
* $Id$
*
* Copyright 2011 samaxes.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.samaxes.filter.util;
/**
* Possible Cache-Control directives for cacheable responses.
*
* @author Samuel Santos
* @version $Revision$
*/
public enum Cacheability {
/**
* Indicates that the response MAY be cached by any cache, even if it would normally be non-cacheable or cacheable
* only within a non-shared cache.
*/
PUBLIC("public"),
/**
* Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a
* shared cache. This allows an origin server to state that the specified parts of the response are intended for
* only one user and are not a valid response for requests by other users. A private (non-shared) cache MAY cache
* the response.
*/
PRIVATE("private");
private String value;
private Cacheability(String value) {
this.value = value;
}
/**
* Gets the Cache-Control directive value.
*
* @return the Cache-Control directive value
*/
public String getValue() {
return this.value;
}
}
| Set the value to final. | src/main/java/com/samaxes/filter/util/Cacheability.java | Set the value to final. | <ide><path>rc/main/java/com/samaxes/filter/util/Cacheability.java
<ide> /*
<del> * $Id$
<ide> *
<ide> * Copyright 2011 samaxes.com
<ide> *
<ide>
<ide> /**
<ide> * Possible Cache-Control directives for cacheable responses.
<del> *
<add> *
<ide> * @author Samuel Santos
<del> * @version $Revision$
<add> * @author John Yeary
<add> * @version 2.0.1
<ide> */
<ide> public enum Cacheability {
<add>
<ide> /**
<del> * Indicates that the response MAY be cached by any cache, even if it would normally be non-cacheable or cacheable
<del> * only within a non-shared cache.
<add> * Indicates that the response MAY be cached by any cache, even if it would
<add> * normally be non-cacheable or cacheable only within a non-shared cache.
<ide> */
<ide> PUBLIC("public"),
<ide> /**
<del> * Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a
<del> * shared cache. This allows an origin server to state that the specified parts of the response are intended for
<del> * only one user and are not a valid response for requests by other users. A private (non-shared) cache MAY cache
<del> * the response.
<add> * Indicates that all or part of the response message is intended for a
<add> * single user and MUST NOT be cached by a shared cache. This allows an
<add> * origin server to state that the specified parts of the response are
<add> * intended for only one user and are not a valid response for requests by
<add> * other users. A private (non-shared) cache MAY cache the response.
<ide> */
<ide> PRIVATE("private");
<ide>
<del> private String value;
<add> private final String value;
<ide>
<ide> private Cacheability(String value) {
<ide> this.value = value;
<ide>
<ide> /**
<ide> * Gets the Cache-Control directive value.
<del> *
<add> *
<ide> * @return the Cache-Control directive value
<ide> */
<ide> public String getValue() { |
|
Java | lgpl-2.1 | cb0d66cbabaf7fd41e5e536530e07cdb7c52086e | 0 | johnscancella/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,sewe/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.FieldOrMethod;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Synthetic;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.OpcodeStack.Item;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
public class SerializableIdiom extends BytecodeScanningDetector
{
boolean sawSerialVersionUID;
boolean isSerializable, implementsSerializableDirectly;
boolean isExternalizable;
boolean isGUIClass;
boolean foundSynthetic;
boolean seenTransientField;
boolean foundSynchronizedMethods;
boolean writeObjectIsSynchronized;
private BugReporter bugReporter;
boolean isAbstract;
private List<BugInstance> fieldWarningList = new LinkedList<BugInstance>();
private HashMap<String, XField> fieldsThatMightBeAProblem = new HashMap<String, XField>();
private HashMap<String, XField> transientFields = new HashMap<String, XField>();
private HashMap<String, Integer> transientFieldsUpdates = new HashMap<String, Integer>();
private HashSet<String> transientFieldsSetInConstructor = new HashSet<String>();
private boolean sawReadExternal;
private boolean sawWriteExternal;
private boolean sawReadObject;
private boolean sawReadResolve;
private boolean sawWriteObject;
private boolean superClassImplementsSerializable;
private boolean hasPublicVoidConstructor;
private boolean superClassHasVoidConstructor;
private boolean directlyImplementsExternalizable;
//private JavaClass serializable;
//private JavaClass collection;
//private JavaClass map;
//private boolean isRemote;
public SerializableIdiom(BugReporter bugReporter) {
this.bugReporter = bugReporter;
//try {
//serializable = Repository.lookupClass("java.io.Serializable");
//collection = Repository.lookupClass("java.util.Collection");
//map = Repository.lookupClass("java.util.Map");
//} catch (ClassNotFoundException e) {
// can't do anything
//}
}
@Override
public void visitClassContext(ClassContext classContext) {
classContext.getJavaClass().accept(this);
flush();
}
private void flush() {
if (!isAbstract &&
!((sawReadExternal && sawWriteExternal) || (sawReadObject && sawWriteObject))) {
for (BugInstance aFieldWarningList : fieldWarningList)
bugReporter.reportBug(aFieldWarningList);
}
fieldWarningList.clear();
}
static Pattern anonymousInnerClassNamePattern =
Pattern.compile(".+\\$\\d+");
boolean isAnonymousInnerClass;
private boolean isEnum;
@Override
public void visit(JavaClass obj) {
String superClassname = obj.getSuperclassName();
// System.out.println("superclass of " + getClassName() + " is " + superClassname);
isEnum = superClassname.equals("java.lang.Enum");
if (isEnum) return;
int flags = obj.getAccessFlags();
isAbstract = (flags & ACC_ABSTRACT) != 0
|| (flags & ACC_INTERFACE) != 0;
isAnonymousInnerClass
= anonymousInnerClassNamePattern
.matcher(getClassName()).matches();
sawSerialVersionUID = false;
isSerializable = implementsSerializableDirectly = false;
isExternalizable = false;
directlyImplementsExternalizable = false;
isGUIClass = false;
seenTransientField = false;
boolean isEnum = obj.getSuperclassName().equals("java.lang.Enum");
fieldsThatMightBeAProblem.clear();
transientFields.clear();
transientFieldsUpdates.clear();
transientFieldsSetInConstructor.clear();
//isRemote = false;
// Does this class directly implement Serializable?
String[] interface_names = obj.getInterfaceNames();
for (String interface_name : interface_names) {
if (interface_name.equals("java.io.Externalizable")) {
directlyImplementsExternalizable = true;
isExternalizable = true;
// System.out.println("Directly implements Externalizable: " + betterClassName);
} else if (interface_name.equals("java.io.Serializable")) {
implementsSerializableDirectly = true;
isSerializable = true;
break;
}
}
// Does this class indirectly implement Serializable?
if (!isSerializable) {
try {
if (Repository.instanceOf(obj, "java.io.Externalizable"))
isExternalizable = true;
if (Repository.instanceOf(obj, "java.io.Serializable"))
isSerializable = true;
/*
if (Repository.instanceOf(obj,"java.rmi.Remote")) {
isRemote = true;
}
*/
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
hasPublicVoidConstructor = false;
superClassHasVoidConstructor = true;
superClassImplementsSerializable = isSerializable && !implementsSerializableDirectly;
try {
JavaClass superClass = obj.getSuperClass();
if (superClass != null) {
Method[] superClassMethods = superClass.getMethods();
superClassImplementsSerializable = Repository.instanceOf(superClass,
"java.io.Serializable");
superClassHasVoidConstructor = false;
for (Method m : superClassMethods) {
/*
if (!m.isPrivate())
System.out.println("Supercase of " + className
+ " has an accessible method named " + m.getName()
+ " with sig " + m.getSignature());
*/
if (m.getName().equals("<init>")
&& m.getSignature().equals("()V")
&& !m.isPrivate()
) {
// System.out.println(" super has void constructor");
superClassHasVoidConstructor = true;
break;
}
}
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
// Is this a GUI or other class that is rarely serialized?
try {
isGUIClass =
Repository.instanceOf(obj, "java.lang.Throwable")
|| Repository.instanceOf(obj, "java.awt.Component")
|| Repository.implementationOf(obj, "java.awt.event.ActionListener")
|| Repository.implementationOf(obj, "java.util.EventListener")
;
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
foundSynthetic = false;
foundSynchronizedMethods = false;
writeObjectIsSynchronized = false;
sawReadExternal = sawWriteExternal = sawReadObject = sawWriteObject = false;
}
@Override
public void visitAfter(JavaClass obj) {
if (isEnum) return;
if (false) {
System.out.println(getDottedClassName());
System.out.println(" hasPublicVoidConstructor: " + hasPublicVoidConstructor);
System.out.println(" superClassHasVoidConstructor: " + superClassHasVoidConstructor);
System.out.println(" isExternalizable: " + isExternalizable);
System.out.println(" isSerializable: " + isSerializable);
System.out.println(" isAbstract: " + isAbstract);
System.out.println(" superClassImplementsSerializable: " + superClassImplementsSerializable);
}
if (isSerializable && !sawReadObject && seenTransientField) {
for(Map.Entry<String,Integer> e : transientFieldsUpdates.entrySet()) {
XField fieldX = transientFields.get(e.getKey());
int priority = NORMAL_PRIORITY;
if (transientFieldsSetInConstructor.contains(e.getKey()))
priority--;
else {
if (isGUIClass) priority++;
if (e.getValue() < 3)
priority++;
}
try {
double isSerializable = Analyze.isDeepSerializable(fieldX.getSignature());
if (isSerializable < 0.6) priority++;
} catch (ClassNotFoundException e1) {
// ignore it
}
bugReporter.reportBug(new BugInstance(this, "SE_TRANSIENT_FIELD_NOT_RESTORED",
priority )
.addClass(getThisClass())
.addField(fieldX));
}
}
if (isSerializable && !isExternalizable
&& !superClassHasVoidConstructor
&& !superClassImplementsSerializable)
bugReporter.reportBug(new BugInstance(this, "SE_NO_SUITABLE_CONSTRUCTOR",
implementsSerializableDirectly|| seenTransientField ? HIGH_PRIORITY :
( sawSerialVersionUID ? NORMAL_PRIORITY : LOW_PRIORITY))
.addClass(getThisClass().getClassName()));
// Downgrade class-level warnings if it's a GUI class.
int priority = false && isGUIClass ? LOW_PRIORITY : NORMAL_PRIORITY;
if (obj.getClassName().endsWith("_Stub")) priority++;
if (isExternalizable && !hasPublicVoidConstructor && !isAbstract)
bugReporter.reportBug(new BugInstance(this, "SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION",
directlyImplementsExternalizable ?
HIGH_PRIORITY : NORMAL_PRIORITY)
.addClass(getThisClass().getClassName()));
if (!foundSynthetic) priority++;
if (seenTransientField) priority--;
if (!isAnonymousInnerClass
&& !isExternalizable && !isGUIClass
&& isSerializable && !isAbstract && !sawSerialVersionUID)
bugReporter.reportBug(new BugInstance(this, "SE_NO_SERIALVERSIONID", priority).addClass(this));
if (writeObjectIsSynchronized && !foundSynchronizedMethods)
bugReporter.reportBug(new BugInstance(this, "WS_WRITEOBJECT_SYNC", LOW_PRIORITY).addClass(this));
}
@Override
public void visit(Method obj) {
int accessFlags = obj.getAccessFlags();
boolean isSynchronized = (accessFlags & ACC_SYNCHRONIZED) != 0;
if (getMethodName().equals("<init>") && getMethodSig().equals("()V")
&& (accessFlags & ACC_PUBLIC) != 0
)
hasPublicVoidConstructor = true;
if (!getMethodName().equals("<init>")
&& isSynthetic(obj))
foundSynthetic = true;
// System.out.println(methodName + isSynchronized);
if (getMethodName().equals("readExternal")
&& getMethodSig().equals("(Ljava/io/ObjectInput;)V")) {
sawReadExternal = true;
if (false && !obj.isPrivate())
System.out.println("Non-private readExternal method in: " + getDottedClassName());
} else if (getMethodName().equals("writeExternal")
&& getMethodSig().equals("(Ljava/io/Objectoutput;)V")) {
sawWriteExternal = true;
if (false && !obj.isPrivate())
System.out.println("Non-private writeExternal method in: " + getDottedClassName());
}
else if (getMethodName().equals("readResolve")
&& getMethodSig().startsWith("()")
&& isSerializable) {
sawReadResolve = true;
if (!getMethodSig().equals("()Ljava/lang/Object;"))
bugReporter.reportBug(new BugInstance(this, "SE_READ_RESOLVE_MUST_RETURN_OBJECT", HIGH_PRIORITY)
.addClassAndMethod(this));
}else if (getMethodName().equals("readObject")
&& getMethodSig().equals("(Ljava/io/ObjectInputStream;)V")
&& isSerializable) {
sawReadObject = true;
if (!obj.isPrivate())
bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
.addClassAndMethod(this));
} else if (getMethodName().equals("readObjectNoData")
&& getMethodSig().equals("()V")
&& isSerializable) {
if (!obj.isPrivate())
bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
.addClassAndMethod(this));
}else if (getMethodName().equals("writeObject")
&& getMethodSig().equals("(Ljava/io/ObjectOutputStream;)V")
&& isSerializable) {
sawReadObject = true;
if (!obj.isPrivate())
bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
.addClassAndMethod(this));
}
if (isSynchronized) {
if (getMethodName().equals("readObject") &&
getMethodSig().equals("(Ljava/io/ObjectInputStream;)V") &&
isSerializable)
bugReporter.reportBug(new BugInstance(this, "RS_READOBJECT_SYNC", NORMAL_PRIORITY).addClass(this));
else if (getMethodName().equals("writeObject")
&& getMethodSig().equals("(Ljava/io/ObjectOutputStream;)V")
&& isSerializable)
writeObjectIsSynchronized = true;
else
foundSynchronizedMethods = true;
}
super.visit(obj);
}
boolean isSynthetic(FieldOrMethod obj) {
Attribute[] a = obj.getAttributes();
for (Attribute aA : a)
if (aA instanceof Synthetic) return true;
return false;
}
@Override
public void visit(Code obj) {
if (isSerializable) {
stack.resetForMethodEntry(this);
super.visit(obj);
}
}
@Override
public void sawOpcode(int seen) {
stack.mergeJumps(this);
if (seen == PUTFIELD) {
String nameOfClass = getClassConstantOperand();
if ( getClassName().equals(nameOfClass)) {
Item first = stack.getStackItem(0);
boolean isPutOfDefaultValue = first.isNull() || first.getConstant() != null
&& first.getConstant().equals(0);
if (!isPutOfDefaultValue) {
String nameOfField = getNameConstantOperand();
if (transientFieldsUpdates.containsKey(nameOfField) ) {
if (getMethodName().equals("<init>")) transientFieldsSetInConstructor.add(nameOfField);
else transientFieldsUpdates.put(nameOfField, transientFieldsUpdates.get(nameOfField)+1);
} else if (fieldsThatMightBeAProblem.containsKey(nameOfField)) {
try {
JavaClass classStored = first.getJavaClass();
double isSerializable = Analyze
.isDeepSerializable(classStored);
if (isSerializable <= 0.2) {
XField f = fieldsThatMightBeAProblem.get(nameOfField);
String sig = f.getSignature();
// System.out.println("Field signature: " + sig);
// System.out.println("Class stored: " +
// classStored.getClassName());
String genSig = "L"
+ classStored.getClassName().replace('.', '/')
+ ";";
if (!sig.equals(genSig)) {
double bias = 0.0;
if (!getMethodName().equals("<init>")) bias = 1.0;
int priority = computePriority(isSerializable, bias);
fieldWarningList.add(new BugInstance(this,
"SE_BAD_FIELD_STORE", priority).addClass(
getThisClass().getClassName()).addField(f)
.addClass(classStored).addSourceLine(this));
}
}
} catch (Exception e) {
// ignore it
}
}
}
}
}
stack.sawOpcode(this,seen);
}
private OpcodeStack stack = new OpcodeStack();
@Override
public void visit(Field obj) {
int flags = obj.getAccessFlags();
if (obj.isTransient()) {
seenTransientField = true;
transientFields.put(obj.getName(), XFactory.createXField(this));
transientFieldsUpdates.put(obj.getName(), 0);
}
else if (getClassName().indexOf("ObjectStreamClass") == -1
&& isSerializable
&& !isExternalizable
&& getFieldSig().indexOf("L") >= 0 && !obj.isTransient() && !obj.isStatic()) {
try {
double isSerializable = Analyze.isDeepSerializable(getFieldSig());
if (isSerializable < 1.0)
fieldsThatMightBeAProblem.put(obj.getName(), XFactory.createXField(this));
if (isSerializable < 0.9) {
// Priority is LOW for GUI classes (unless explicitly marked Serializable),
// HIGH if the class directly implements Serializable,
// NORMAL otherwise.
int priority = computePriority(isSerializable, 0);
if (priority > NORMAL_PRIORITY
&& obj.getName().startsWith("this$"))
priority = NORMAL_PRIORITY;
if (false)
System.out.println("SE_BAD_FIELD: " + getThisClass().getClassName()
+" " + obj.getName()
+" " + isSerializable
+" " + implementsSerializableDirectly
+" " + sawSerialVersionUID
+" " + isGUIClass);
// Report is queued until after the entire class has been seen.
fieldWarningList.add(new BugInstance(this, "SE_BAD_FIELD", priority)
.addClass(getThisClass().getClassName())
.addField(getDottedClassName(), obj.getName(), getFieldSig(), false));
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
if (!getFieldName().startsWith("this")
&& isSynthetic(obj))
foundSynthetic = true;
if (!getFieldName().equals("serialVersionUID")) return;
int mask = ACC_STATIC | ACC_FINAL;
if (!getFieldSig().equals("I")
&& !getFieldSig().equals("J"))
return;
if ((flags & mask) == mask
&& getFieldSig().equals("I")) {
bugReporter.reportBug(new BugInstance(this, "SE_NONLONG_SERIALVERSIONID", LOW_PRIORITY)
.addClass(this)
.addVisitedField(this));
sawSerialVersionUID = true;
return;
} else if ((flags & ACC_STATIC) == 0) {
bugReporter.reportBug(new BugInstance(this, "SE_NONSTATIC_SERIALVERSIONID", NORMAL_PRIORITY)
.addClass(this)
.addVisitedField(this));
return;
} else if ((flags & ACC_FINAL) == 0) {
bugReporter.reportBug(new BugInstance(this, "SE_NONFINAL_SERIALVERSIONID", NORMAL_PRIORITY)
.addClass(this)
.addVisitedField(this));
return;
}
sawSerialVersionUID = true;
}
private int computePriority(double isSerializable, double bias) {
int priority = (int)(1.9+isSerializable*3 + bias);
if (implementsSerializableDirectly || sawSerialVersionUID || sawReadObject)
priority--;
if (!implementsSerializableDirectly && priority == HIGH_PRIORITY)
priority = NORMAL_PRIORITY;
return priority;
}
}
| findbugs/src/java/edu/umd/cs/findbugs/detect/SerializableIdiom.java | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.FieldOrMethod;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Synthetic;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
public class SerializableIdiom extends BytecodeScanningDetector
{
boolean sawSerialVersionUID;
boolean isSerializable, implementsSerializableDirectly;
boolean isExternalizable;
boolean isGUIClass;
boolean foundSynthetic;
boolean seenTransientField;
boolean foundSynchronizedMethods;
boolean writeObjectIsSynchronized;
private BugReporter bugReporter;
boolean isAbstract;
private List<BugInstance> fieldWarningList = new LinkedList<BugInstance>();
private HashMap<String, XField> fieldsThatMightBeAProblem = new HashMap<String, XField>();
private HashMap<String, XField> transientFields = new HashMap<String, XField>();
private HashMap<String, Integer> transientFieldsUpdates = new HashMap<String, Integer>();
private HashSet<String> transientFieldsSetInConstructor = new HashSet<String>();
private boolean sawReadExternal;
private boolean sawWriteExternal;
private boolean sawReadObject;
private boolean sawReadResolve;
private boolean sawWriteObject;
private boolean superClassImplementsSerializable;
private boolean hasPublicVoidConstructor;
private boolean superClassHasVoidConstructor;
private boolean directlyImplementsExternalizable;
//private JavaClass serializable;
//private JavaClass collection;
//private JavaClass map;
//private boolean isRemote;
public SerializableIdiom(BugReporter bugReporter) {
this.bugReporter = bugReporter;
//try {
//serializable = Repository.lookupClass("java.io.Serializable");
//collection = Repository.lookupClass("java.util.Collection");
//map = Repository.lookupClass("java.util.Map");
//} catch (ClassNotFoundException e) {
// can't do anything
//}
}
@Override
public void visitClassContext(ClassContext classContext) {
classContext.getJavaClass().accept(this);
flush();
}
private void flush() {
if (!isAbstract &&
!((sawReadExternal && sawWriteExternal) || (sawReadObject && sawWriteObject))) {
for (BugInstance aFieldWarningList : fieldWarningList)
bugReporter.reportBug(aFieldWarningList);
}
fieldWarningList.clear();
}
static Pattern anonymousInnerClassNamePattern =
Pattern.compile(".+\\$\\d+");
boolean isAnonymousInnerClass;
private boolean isEnum;
@Override
public void visit(JavaClass obj) {
String superClassname = obj.getSuperclassName();
// System.out.println("superclass of " + getClassName() + " is " + superClassname);
isEnum = superClassname.equals("java.lang.Enum");
if (isEnum) return;
int flags = obj.getAccessFlags();
isAbstract = (flags & ACC_ABSTRACT) != 0
|| (flags & ACC_INTERFACE) != 0;
isAnonymousInnerClass
= anonymousInnerClassNamePattern
.matcher(getClassName()).matches();
sawSerialVersionUID = false;
isSerializable = implementsSerializableDirectly = false;
isExternalizable = false;
directlyImplementsExternalizable = false;
isGUIClass = false;
seenTransientField = false;
boolean isEnum = obj.getSuperclassName().equals("java.lang.Enum");
fieldsThatMightBeAProblem.clear();
transientFields.clear();
transientFieldsUpdates.clear();
transientFieldsSetInConstructor.clear();
//isRemote = false;
// Does this class directly implement Serializable?
String[] interface_names = obj.getInterfaceNames();
for (String interface_name : interface_names) {
if (interface_name.equals("java.io.Externalizable")) {
directlyImplementsExternalizable = true;
isExternalizable = true;
// System.out.println("Directly implements Externalizable: " + betterClassName);
} else if (interface_name.equals("java.io.Serializable")) {
implementsSerializableDirectly = true;
isSerializable = true;
break;
}
}
// Does this class indirectly implement Serializable?
if (!isSerializable) {
try {
if (Repository.instanceOf(obj, "java.io.Externalizable"))
isExternalizable = true;
if (Repository.instanceOf(obj, "java.io.Serializable"))
isSerializable = true;
/*
if (Repository.instanceOf(obj,"java.rmi.Remote")) {
isRemote = true;
}
*/
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
hasPublicVoidConstructor = false;
superClassHasVoidConstructor = true;
superClassImplementsSerializable = isSerializable && !implementsSerializableDirectly;
try {
JavaClass superClass = obj.getSuperClass();
if (superClass != null) {
Method[] superClassMethods = superClass.getMethods();
superClassImplementsSerializable = Repository.instanceOf(superClass,
"java.io.Serializable");
superClassHasVoidConstructor = false;
for (Method m : superClassMethods) {
/*
if (!m.isPrivate())
System.out.println("Supercase of " + className
+ " has an accessible method named " + m.getName()
+ " with sig " + m.getSignature());
*/
if (m.getName().equals("<init>")
&& m.getSignature().equals("()V")
&& !m.isPrivate()
) {
// System.out.println(" super has void constructor");
superClassHasVoidConstructor = true;
break;
}
}
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
// Is this a GUI or other class that is rarely serialized?
try {
isGUIClass =
Repository.instanceOf(obj, "java.lang.Throwable")
|| Repository.instanceOf(obj, "java.awt.Component")
|| Repository.implementationOf(obj, "java.awt.event.ActionListener")
|| Repository.implementationOf(obj, "java.util.EventListener")
;
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
foundSynthetic = false;
foundSynchronizedMethods = false;
writeObjectIsSynchronized = false;
sawReadExternal = sawWriteExternal = sawReadObject = sawWriteObject = false;
}
@Override
public void visitAfter(JavaClass obj) {
if (isEnum) return;
if (false) {
System.out.println(getDottedClassName());
System.out.println(" hasPublicVoidConstructor: " + hasPublicVoidConstructor);
System.out.println(" superClassHasVoidConstructor: " + superClassHasVoidConstructor);
System.out.println(" isExternalizable: " + isExternalizable);
System.out.println(" isSerializable: " + isSerializable);
System.out.println(" isAbstract: " + isAbstract);
System.out.println(" superClassImplementsSerializable: " + superClassImplementsSerializable);
}
if (isSerializable && !sawReadObject && seenTransientField) {
for(Map.Entry<String,Integer> e : transientFieldsUpdates.entrySet()) {
XField fieldX = transientFields.get(e.getKey());
int priority = NORMAL_PRIORITY;
if (transientFieldsSetInConstructor.contains(e.getKey()))
priority--;
else {
if (isGUIClass) priority++;
if (e.getValue() < 3)
priority++;
}
try {
double isSerializable = Analyze.isDeepSerializable(fieldX.getSignature());
if (isSerializable < 0.6) priority++;
} catch (ClassNotFoundException e1) {
// ignore it
}
bugReporter.reportBug(new BugInstance(this, "SE_TRANSIENT_FIELD_NOT_RESTORED",
priority )
.addClass(getThisClass())
.addField(fieldX));
}
}
if (isSerializable && !isExternalizable
&& !superClassHasVoidConstructor
&& !superClassImplementsSerializable)
bugReporter.reportBug(new BugInstance(this, "SE_NO_SUITABLE_CONSTRUCTOR",
implementsSerializableDirectly|| seenTransientField ? HIGH_PRIORITY :
( sawSerialVersionUID ? NORMAL_PRIORITY : LOW_PRIORITY))
.addClass(getThisClass().getClassName()));
// Downgrade class-level warnings if it's a GUI class.
int priority = false && isGUIClass ? LOW_PRIORITY : NORMAL_PRIORITY;
if (obj.getClassName().endsWith("_Stub")) priority++;
if (isExternalizable && !hasPublicVoidConstructor && !isAbstract)
bugReporter.reportBug(new BugInstance(this, "SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION",
directlyImplementsExternalizable ?
HIGH_PRIORITY : NORMAL_PRIORITY)
.addClass(getThisClass().getClassName()));
if (!foundSynthetic) priority++;
if (seenTransientField) priority--;
if (!isAnonymousInnerClass
&& !isExternalizable && !isGUIClass
&& isSerializable && !isAbstract && !sawSerialVersionUID)
bugReporter.reportBug(new BugInstance(this, "SE_NO_SERIALVERSIONID", priority).addClass(this));
if (writeObjectIsSynchronized && !foundSynchronizedMethods)
bugReporter.reportBug(new BugInstance(this, "WS_WRITEOBJECT_SYNC", LOW_PRIORITY).addClass(this));
}
@Override
public void visit(Method obj) {
int accessFlags = obj.getAccessFlags();
boolean isSynchronized = (accessFlags & ACC_SYNCHRONIZED) != 0;
if (getMethodName().equals("<init>") && getMethodSig().equals("()V")
&& (accessFlags & ACC_PUBLIC) != 0
)
hasPublicVoidConstructor = true;
if (!getMethodName().equals("<init>")
&& isSynthetic(obj))
foundSynthetic = true;
// System.out.println(methodName + isSynchronized);
if (getMethodName().equals("readExternal")
&& getMethodSig().equals("(Ljava/io/ObjectInput;)V")) {
sawReadExternal = true;
if (false && !obj.isPrivate())
System.out.println("Non-private readExternal method in: " + getDottedClassName());
} else if (getMethodName().equals("writeExternal")
&& getMethodSig().equals("(Ljava/io/Objectoutput;)V")) {
sawWriteExternal = true;
if (false && !obj.isPrivate())
System.out.println("Non-private writeExternal method in: " + getDottedClassName());
}
else if (getMethodName().equals("readResolve")
&& getMethodSig().startsWith("()")
&& isSerializable) {
sawReadResolve = true;
if (!getMethodSig().equals("()Ljava/lang/Object;"))
bugReporter.reportBug(new BugInstance(this, "SE_READ_RESOLVE_MUST_RETURN_OBJECT", HIGH_PRIORITY)
.addClassAndMethod(this));
}else if (getMethodName().equals("readObject")
&& getMethodSig().equals("(Ljava/io/ObjectInputStream;)V")
&& isSerializable) {
sawReadObject = true;
if (!obj.isPrivate())
bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
.addClassAndMethod(this));
} else if (getMethodName().equals("readObjectNoData")
&& getMethodSig().equals("()V")
&& isSerializable) {
if (!obj.isPrivate())
bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
.addClassAndMethod(this));
}else if (getMethodName().equals("writeObject")
&& getMethodSig().equals("(Ljava/io/ObjectOutputStream;)V")
&& isSerializable) {
sawReadObject = true;
if (!obj.isPrivate())
bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
.addClassAndMethod(this));
}
if (isSynchronized) {
if (getMethodName().equals("readObject") &&
getMethodSig().equals("(Ljava/io/ObjectInputStream;)V") &&
isSerializable)
bugReporter.reportBug(new BugInstance(this, "RS_READOBJECT_SYNC", NORMAL_PRIORITY).addClass(this));
else if (getMethodName().equals("writeObject")
&& getMethodSig().equals("(Ljava/io/ObjectOutputStream;)V")
&& isSerializable)
writeObjectIsSynchronized = true;
else
foundSynchronizedMethods = true;
}
super.visit(obj);
}
boolean isSynthetic(FieldOrMethod obj) {
Attribute[] a = obj.getAttributes();
for (Attribute aA : a)
if (aA instanceof Synthetic) return true;
return false;
}
@Override
public void visit(Code obj) {
if (isSerializable) {
stack.resetForMethodEntry(this);
super.visit(obj);
}
}
@Override
public void sawOpcode(int seen) {
stack.mergeJumps(this);
if (seen == PUTFIELD) {
String nameOfClass = getClassConstantOperand();
if ( getClassName().equals(nameOfClass)) {
String nameOfField = getNameConstantOperand();
if (transientFieldsUpdates.containsKey(nameOfField) ) {
if (getMethodName().equals("<init>")) transientFieldsSetInConstructor.add(nameOfField);
else transientFieldsUpdates.put(nameOfField, transientFieldsUpdates.get(nameOfField)+1);
} else if (fieldsThatMightBeAProblem.containsKey(nameOfField)) {
try {
OpcodeStack.Item first = stack.getStackItem(0);
JavaClass classStored = first.getJavaClass();
double isSerializable = Analyze
.isDeepSerializable(classStored);
if (isSerializable <= 0.2) {
XField f = fieldsThatMightBeAProblem.get(nameOfField);
String sig = f.getSignature();
// System.out.println("Field signature: " + sig);
// System.out.println("Class stored: " +
// classStored.getClassName());
String genSig = "L"
+ classStored.getClassName().replace('.', '/')
+ ";";
if (!sig.equals(genSig)) {
double bias = 0.0;
if (!getMethodName().equals("<init>")) bias = 1.0;
int priority = computePriority(isSerializable, bias);
fieldWarningList.add(new BugInstance(this,
"SE_BAD_FIELD_STORE", priority).addClass(
getThisClass().getClassName()).addField(f)
.addClass(classStored).addSourceLine(this));
}
}
} catch (Exception e) {
// ignore it
}
}
}
}
stack.sawOpcode(this,seen);
}
private OpcodeStack stack = new OpcodeStack();
@Override
public void visit(Field obj) {
int flags = obj.getAccessFlags();
if (obj.isTransient()) {
seenTransientField = true;
transientFields.put(obj.getName(), XFactory.createXField(this));
transientFieldsUpdates.put(obj.getName(), 0);
}
else if (getClassName().indexOf("ObjectStreamClass") == -1
&& isSerializable
&& !isExternalizable
&& getFieldSig().indexOf("L") >= 0 && !obj.isTransient() && !obj.isStatic()) {
try {
double isSerializable = Analyze.isDeepSerializable(getFieldSig());
if (isSerializable < 1.0)
fieldsThatMightBeAProblem.put(obj.getName(), XFactory.createXField(this));
if (isSerializable < 0.9) {
// Priority is LOW for GUI classes (unless explicitly marked Serializable),
// HIGH if the class directly implements Serializable,
// NORMAL otherwise.
int priority = computePriority(isSerializable, 0);
if (priority > NORMAL_PRIORITY
&& obj.getName().startsWith("this$"))
priority = NORMAL_PRIORITY;
if (false)
System.out.println("SE_BAD_FIELD: " + getThisClass().getClassName()
+" " + obj.getName()
+" " + isSerializable
+" " + implementsSerializableDirectly
+" " + sawSerialVersionUID
+" " + isGUIClass);
// Report is queued until after the entire class has been seen.
fieldWarningList.add(new BugInstance(this, "SE_BAD_FIELD", priority)
.addClass(getThisClass().getClassName())
.addField(getDottedClassName(), obj.getName(), getFieldSig(), false));
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
if (!getFieldName().startsWith("this")
&& isSynthetic(obj))
foundSynthetic = true;
if (!getFieldName().equals("serialVersionUID")) return;
int mask = ACC_STATIC | ACC_FINAL;
if (!getFieldSig().equals("I")
&& !getFieldSig().equals("J"))
return;
if ((flags & mask) == mask
&& getFieldSig().equals("I")) {
bugReporter.reportBug(new BugInstance(this, "SE_NONLONG_SERIALVERSIONID", LOW_PRIORITY)
.addClass(this)
.addVisitedField(this));
sawSerialVersionUID = true;
return;
} else if ((flags & ACC_STATIC) == 0) {
bugReporter.reportBug(new BugInstance(this, "SE_NONSTATIC_SERIALVERSIONID", NORMAL_PRIORITY)
.addClass(this)
.addVisitedField(this));
return;
} else if ((flags & ACC_FINAL) == 0) {
bugReporter.reportBug(new BugInstance(this, "SE_NONFINAL_SERIALVERSIONID", NORMAL_PRIORITY)
.addClass(this)
.addVisitedField(this));
return;
}
sawSerialVersionUID = true;
}
private int computePriority(double isSerializable, double bias) {
int priority = (int)(1.9+isSerializable*3 + bias);
if (implementsSerializableDirectly || sawSerialVersionUID || sawReadObject)
priority--;
if (!implementsSerializableDirectly && priority == HIGH_PRIORITY)
priority = NORMAL_PRIORITY;
return priority;
}
}
| Ignore puts of default value
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@5783 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugs/src/java/edu/umd/cs/findbugs/detect/SerializableIdiom.java | Ignore puts of default value | <ide><path>indbugs/src/java/edu/umd/cs/findbugs/detect/SerializableIdiom.java
<ide> import edu.umd.cs.findbugs.BugReporter;
<ide> import edu.umd.cs.findbugs.BytecodeScanningDetector;
<ide> import edu.umd.cs.findbugs.OpcodeStack;
<add>import edu.umd.cs.findbugs.OpcodeStack.Item;
<ide> import edu.umd.cs.findbugs.ba.ClassContext;
<ide> import edu.umd.cs.findbugs.ba.XFactory;
<ide> import edu.umd.cs.findbugs.ba.XField;
<ide> if (seen == PUTFIELD) {
<ide> String nameOfClass = getClassConstantOperand();
<ide> if ( getClassName().equals(nameOfClass)) {
<add> Item first = stack.getStackItem(0);
<add> boolean isPutOfDefaultValue = first.isNull() || first.getConstant() != null
<add> && first.getConstant().equals(0);
<add> if (!isPutOfDefaultValue) {
<ide> String nameOfField = getNameConstantOperand();
<ide> if (transientFieldsUpdates.containsKey(nameOfField) ) {
<ide> if (getMethodName().equals("<init>")) transientFieldsSetInConstructor.add(nameOfField);
<ide> else transientFieldsUpdates.put(nameOfField, transientFieldsUpdates.get(nameOfField)+1);
<ide> } else if (fieldsThatMightBeAProblem.containsKey(nameOfField)) {
<ide> try {
<del> OpcodeStack.Item first = stack.getStackItem(0);
<add>
<ide> JavaClass classStored = first.getJavaClass();
<ide> double isSerializable = Analyze
<ide> .isDeepSerializable(classStored);
<ide> } catch (Exception e) {
<ide> // ignore it
<ide> }
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 0c9d0cbdad3db7ef38932bc3384ac156c2dc8841 | 0 | meetdestiny/geronimo-trader,apache/geronimo,meetdestiny/geronimo-trader,apache/geronimo,vibe13/geronimo,vibe13/geronimo,vibe13/geronimo,meetdestiny/geronimo-trader,apache/geronimo,apache/geronimo,vibe13/geronimo | /**
*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.axis.server;
import java.lang.reflect.Method;
import javax.xml.rpc.holders.IntHolder;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.MessageContext;
import org.apache.axis.Handler;
import org.apache.geronimo.webservices.WebServiceContainer;
/**
* @version $Rev$ $Date$
*/
public class POJOProvider extends RPCProvider {
public POJOProvider() {
}
public Object getServiceObject(MessageContext msgContext, Handler service, String clsName, IntHolder scopeHolder) throws Exception {
WebServiceContainer.Request request = (WebServiceContainer.Request) msgContext.getProperty(AxisWebServiceContainer.REQUEST);
return request.getAttribute(WebServiceContainer.POJO_INSTANCE);
}
protected Object invokeMethod(MessageContext msgContext, Method interfaceMethod, Object pojo, Object[] arguments) throws Exception {
Class pojoClass = pojo.getClass();
Method pojoMethod = null;
try {
pojoMethod = pojoClass.getMethod(interfaceMethod.getName(), interfaceMethod.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new NoSuchMethodException("The pojo class '"+pojoClass.getName()+"' does not have a method matching signature: "+interfaceMethod);
}
return pojoMethod.invoke(pojo, arguments);
}
}
| modules/axis/src/java/org/apache/geronimo/axis/server/POJOProvider.java | /**
*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.axis.server;
import javax.xml.rpc.holders.IntHolder;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.MessageContext;
import org.apache.axis.Handler;
import org.apache.geronimo.webservices.WebServiceContainer;
/**
* @version $Rev$ $Date$
*/
public class POJOProvider extends RPCProvider {
public POJOProvider() {
}
public Object getServiceObject(MessageContext msgContext, Handler service, String clsName, IntHolder scopeHolder) throws Exception {
WebServiceContainer.Request request = (WebServiceContainer.Request) msgContext.getProperty(AxisWebServiceContainer.REQUEST);
return request.getAttribute(WebServiceContainer.POJO_INSTANCE);
}
}
| The pojo class does not need to implement the service endpoint interface.
git-svn-id: d69ffe4ccc4861bf06065bd0072b85c931fba7ed@179291 13f79535-47bb-0310-9956-ffa450edef68
| modules/axis/src/java/org/apache/geronimo/axis/server/POJOProvider.java | The pojo class does not need to implement the service endpoint interface. | <ide><path>odules/axis/src/java/org/apache/geronimo/axis/server/POJOProvider.java
<ide> */
<ide> package org.apache.geronimo.axis.server;
<ide>
<add>import java.lang.reflect.Method;
<ide> import javax.xml.rpc.holders.IntHolder;
<ide>
<ide> import org.apache.axis.providers.java.RPCProvider;
<ide> WebServiceContainer.Request request = (WebServiceContainer.Request) msgContext.getProperty(AxisWebServiceContainer.REQUEST);
<ide> return request.getAttribute(WebServiceContainer.POJO_INSTANCE);
<ide> }
<add>
<add>
<add> protected Object invokeMethod(MessageContext msgContext, Method interfaceMethod, Object pojo, Object[] arguments) throws Exception {
<add> Class pojoClass = pojo.getClass();
<add>
<add> Method pojoMethod = null;
<add> try {
<add> pojoMethod = pojoClass.getMethod(interfaceMethod.getName(), interfaceMethod.getParameterTypes());
<add> } catch (NoSuchMethodException e) {
<add> throw new NoSuchMethodException("The pojo class '"+pojoClass.getName()+"' does not have a method matching signature: "+interfaceMethod);
<add> }
<add>
<add> return pojoMethod.invoke(pojo, arguments);
<add> }
<ide> } |
|
Java | mit | b0a99a3bcf227148345997f4493f18560e6c22e1 | 0 | SpongePowered/SpongeCommon,SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/SpongeCommon,SpongePowered/Sponge | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.world;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.MapMaker;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.datafix.FixTypes;
import net.minecraft.world.DimensionType;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameType;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.minecraft.world.chunk.storage.AnvilSaveHandler;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import org.spongepowered.api.GameState;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.world.UnloadWorldEvent;
import org.spongepowered.api.util.file.CopyFileVisitor;
import org.spongepowered.api.util.file.DeleteFileVisitor;
import org.spongepowered.api.util.file.ForwardingFileVisitor;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.SerializationBehaviors;
import org.spongepowered.api.world.WorldArchetype;
import org.spongepowered.api.world.storage.WorldProperties;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.bridge.entity.player.ServerPlayerEntityBridge;
import org.spongepowered.common.bridge.server.MinecraftServerBridge;
import org.spongepowered.common.bridge.server.integrated.IntegratedServerBridge;
import org.spongepowered.common.bridge.world.DimensionTypeBridge;
import org.spongepowered.common.bridge.world.ServerWorldBridge;
import org.spongepowered.common.bridge.world.ServerWorldBridge_AsyncLighting;
import org.spongepowered.common.bridge.world.WorldBridge;
import org.spongepowered.common.bridge.world.WorldInfoBridge;
import org.spongepowered.common.bridge.world.WorldSettingsBridge;
import org.spongepowered.common.bridge.world.chunk.ServerChunkProviderBridge;
import org.spongepowered.common.config.SpongeConfig;
import org.spongepowered.common.config.type.GeneralConfigBase;
import org.spongepowered.common.config.type.GlobalConfig;
import org.spongepowered.common.data.util.DataUtil;
import org.spongepowered.common.event.tracking.PhaseContext;
import org.spongepowered.common.event.tracking.phase.general.GeneralPhase;
import org.spongepowered.common.mixin.core.server.MinecraftServerAccessor;
import org.spongepowered.common.util.Constants;
import org.spongepowered.common.util.SpongeHooks;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
@SuppressWarnings("ConstantConditions")
public final class WorldManager {
private static final DirectoryStream.Filter<Path> LEVEL_AND_SPONGE =
entry -> Files.isDirectory(entry) && Files.exists(entry.resolve("level.dat")) && Files.exists(entry.resolve("level_sponge.dat"));
private static final Int2ObjectMap<DimensionType> dimensionTypeByTypeId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectMap<DimensionType> dimensionTypeByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectMap<Path> dimensionPathByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectOpenHashMap<WorldServer> worldByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Map<String, WorldProperties> worldPropertiesByFolderName = new HashMap<>(3);
private static final Map<UUID, WorldProperties> worldPropertiesByWorldUuid = new HashMap<>(3);
private static final Map<Integer, String> worldFolderByDimensionId = new HashMap<>();
private static final BiMap<String, UUID> worldUuidByFolderName = HashBiMap.create(3);
private static final IntSet usedDimensionIds = new IntOpenHashSet();
private static final Map<WorldServer, WorldServer> weakWorldByWorld = new MapMaker().weakKeys().weakValues().concurrencyLevel(1).makeMap();
private static final Queue<WorldServer> unloadQueue = new ArrayDeque<>();
private static final Comparator<WorldServer>
WORLD_SERVER_COMPARATOR =
(world1, world2) -> {
final int world1DimId = ((ServerWorldBridge) world1).bridge$getDimensionId();
if (world2 == null) {
return world1DimId;
}
final int world2DimId = ((ServerWorldBridge) world2).bridge$getDimensionId();
return world1DimId - world2DimId;
};
private static boolean isVanillaRegistered = false;
private static int lastUsedDimensionId = 0;
public static void registerVanillaTypesAndDimensions() {
if (!isVanillaRegistered) {
WorldManager.registerDimensionType(0, DimensionType.OVERWORLD);
WorldManager.registerDimensionType(-1, DimensionType.NETHER);
WorldManager.registerDimensionType(1, DimensionType.THE_END);
WorldManager.registerDimension(0, DimensionType.OVERWORLD);
WorldManager.registerDimension(-1, DimensionType.NETHER);
WorldManager.registerDimension(1, DimensionType.THE_END);
}
isVanillaRegistered = true;
}
public static void registerDimensionType(final DimensionType type) {
checkNotNull(type);
final Optional<Integer> optNextDimensionTypeId = getNextFreeDimensionTypeId();
optNextDimensionTypeId.ifPresent(integer -> registerDimensionType(integer, type));
}
public static void registerDimensionType(final int dimensionTypeId, final DimensionType type) {
checkNotNull(type);
if (dimensionTypeByTypeId.containsKey(dimensionTypeId)) {
return;
}
dimensionTypeByTypeId.put(dimensionTypeId, type);
}
private static Optional<Integer> getNextFreeDimensionTypeId() {
Integer highestDimensionTypeId = null;
for (final Integer dimensionTypeId : dimensionTypeByTypeId.keySet()) {
if (highestDimensionTypeId == null || highestDimensionTypeId < dimensionTypeId) {
highestDimensionTypeId = dimensionTypeId;
}
}
if (highestDimensionTypeId != null && highestDimensionTypeId < 127) {
return Optional.of(++highestDimensionTypeId);
}
return Optional.empty();
}
public static Integer getNextFreeDimensionId() {
int next = lastUsedDimensionId;
while (usedDimensionIds.contains(next) || !checkAvailable(next)) {
next++;
}
return lastUsedDimensionId = next;
}
private static boolean checkAvailable(final int dimensionId) {
if (worldByDimensionId.containsKey(dimensionId)) {
usedDimensionIds.add(dimensionId);
return false;
}
return true;
}
public static void registerDimension(final int dimensionId, final DimensionType type) {
checkNotNull(type);
if (!dimensionTypeByTypeId.containsValue(type)) {
return;
}
if (dimensionTypeByDimensionId.containsKey(dimensionId)) {
return;
}
dimensionTypeByDimensionId.put(dimensionId, type);
if (dimensionId >= 0) {
usedDimensionIds.add(dimensionId);
}
}
public static void unregisterDimension(final int dimensionId) {
if (!dimensionTypeByDimensionId.containsKey(dimensionId))
{
throw new IllegalArgumentException("Failed to unregister dimension [" + dimensionId + "] as it is not registered!");
}
dimensionTypeByDimensionId.remove(dimensionId);
}
private static void registerVanillaDimensionPaths(final Path savePath) {
WorldManager.registerDimensionPath(0, savePath);
WorldManager.registerDimensionPath(-1, savePath.resolve("DIM-1"));
WorldManager.registerDimensionPath(1, savePath.resolve("DIM1"));
}
public static void registerDimensionPath(final int dimensionId, final Path dimensionDataRoot) {
checkNotNull(dimensionDataRoot);
dimensionPathByDimensionId.put(dimensionId, dimensionDataRoot);
}
public static Path getDimensionPath(final int dimensionId) {
return dimensionPathByDimensionId.get(dimensionId);
}
public static Optional<DimensionType> getDimensionType(final int dimensionId) {
return Optional.ofNullable(dimensionTypeByDimensionId.get(dimensionId));
}
public static Optional<DimensionType> getDimensionTypeByTypeId(final int dimensionTypeId) {
return Optional.ofNullable(dimensionTypeByTypeId.get(dimensionTypeId));
}
public static Optional<DimensionType> getDimensionType(final Class<? extends WorldProvider> providerClass) {
checkNotNull(providerClass);
for (final Object rawDimensionType : dimensionTypeByTypeId.values()) {
final DimensionType dimensionType = (DimensionType) rawDimensionType;
if (((org.spongepowered.api.world.DimensionType) (Object) dimensionType).getDimensionClass().equals(providerClass)) {
return Optional.of(dimensionType);
}
}
return Optional.empty();
}
public static Collection<DimensionType> getDimensionTypes() {
return dimensionTypeByTypeId.values();
}
public static int[] getRegisteredDimensionIdsFor(final DimensionType type) {
return dimensionTypeByDimensionId.int2ObjectEntrySet().stream()
.filter(entry -> entry.getValue() == type)
.mapToInt(Int2ObjectMap.Entry::getIntKey)
.toArray();
}
public static int[] getRegisteredDimensionIds() {
return dimensionTypeByDimensionId.keySet().toIntArray();
}
@Nullable
private static Path getWorldFolder(final DimensionType dimensionType, final int dimensionId) {
return dimensionPathByDimensionId.get(dimensionId);
}
public static boolean isDimensionRegistered(final int dimensionId) {
return dimensionTypeByDimensionId.containsKey(dimensionId);
}
private static Map<Integer, DimensionType> sortedDimensionMap() {
final Int2ObjectMap<DimensionType> copy = new Int2ObjectOpenHashMap<>(dimensionTypeByDimensionId);
final HashMap<Integer, DimensionType> newMap = new LinkedHashMap<>();
newMap.put(0, copy.remove(0));
DimensionType removed = copy.remove(-1);
if (removed != null) {
newMap.put(-1, removed);
}
removed = copy.remove(1);
if (removed != null) {
newMap.put(1, removed);
}
final int[] ids = copy.keySet().toIntArray();
Arrays.sort(ids);
for (final int id : ids) {
newMap.put(id, copy.get(id));
}
return newMap;
}
public static ObjectIterator<Int2ObjectMap.Entry<WorldServer>> worldsIterator() {
return worldByDimensionId.int2ObjectEntrySet().fastIterator();
}
public static Collection<WorldServer> getWorlds() {
return worldByDimensionId.values();
}
public static Optional<WorldServer> getWorldByDimensionId(final int dimensionId) {
return Optional.ofNullable(worldByDimensionId.get(dimensionId));
}
public static Optional<String> getWorldFolderByDimensionId(final int dimensionId) {
return Optional.ofNullable(worldFolderByDimensionId.get(dimensionId));
}
public static int[] getLoadedWorldDimensionIds() {
return worldByDimensionId.keySet().toIntArray();
}
public static Optional<WorldServer> getWorld(final String worldName) {
for (final WorldServer worldServer : getWorlds()) {
final org.spongepowered.api.world.World apiWorld = (org.spongepowered.api.world.World) worldServer;
if (apiWorld.getName().equals(worldName)) {
return Optional.of(worldServer);
}
}
return Optional.empty();
}
private static void registerWorldProperties(final WorldProperties properties) {
checkNotNull(properties);
worldPropertiesByFolderName.put(properties.getWorldName(), properties);
worldPropertiesByWorldUuid.put(properties.getUniqueId(), properties);
worldUuidByFolderName.put(properties.getWorldName(), properties.getUniqueId());
worldFolderByDimensionId.put(((WorldInfoBridge) properties).bridge$getDimensionId(), properties.getWorldName());
usedDimensionIds.add(((WorldInfoBridge) properties).bridge$getDimensionId());
}
public static void unregisterWorldProperties(final WorldProperties properties, final boolean freeDimensionId) {
checkNotNull(properties);
worldPropertiesByFolderName.remove(properties.getWorldName());
worldPropertiesByWorldUuid.remove(properties.getUniqueId());
worldUuidByFolderName.remove(properties.getWorldName());
worldFolderByDimensionId.remove(((WorldInfoBridge) properties).bridge$getDimensionId());
if (((WorldInfoBridge) properties).bridge$getDimensionId() != null && freeDimensionId) {
usedDimensionIds.remove(((WorldInfoBridge) properties).bridge$getDimensionId());
}
}
// used by SpongeForge client
public static void unregisterAllWorldSettings() {
worldPropertiesByFolderName.clear();
worldPropertiesByWorldUuid.clear();
worldUuidByFolderName.clear();
worldByDimensionId.clear();
worldFolderByDimensionId.clear();
dimensionTypeByDimensionId.clear();
dimensionPathByDimensionId.clear();
usedDimensionIds.clear();
weakWorldByWorld.clear();
isVanillaRegistered = false;
// This is needed to ensure that DimensionType is usable by GuiListWorldSelection, which is only ever used when the server isn't running
registerVanillaTypesAndDimensions();
}
public static Optional<WorldProperties> getWorldProperties(final String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldPropertiesByFolderName.get(folderName));
}
public static Collection<WorldProperties> getAllWorldProperties() {
return Collections.unmodifiableCollection(worldPropertiesByFolderName.values());
}
public static Optional<WorldProperties> getWorldProperties(final UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldPropertiesByWorldUuid.get(uuid));
}
public static Optional<UUID> getUuidForFolder(final String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldUuidByFolderName.get(folderName));
}
public static Optional<String> getFolderForUuid(final UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldUuidByFolderName.inverse().get(uuid));
}
public static WorldProperties createWorldProperties(final String folderName, final WorldArchetype archetype) {
return createWorldProperties(folderName, archetype, null);
}
@SuppressWarnings("ConstantConditions")
public static WorldProperties createWorldProperties(final String folderName, final WorldArchetype archetype, @Nullable final Integer dimensionId) {
checkNotNull(folderName);
checkNotNull(archetype);
final Optional<WorldServer> optWorldServer = getWorld(folderName);
if (optWorldServer.isPresent()) {
return ((org.spongepowered.api.world.World) optWorldServer.get()).getProperties();
}
final Optional<WorldProperties> optWorldProperties = WorldManager.getWorldProperties(folderName);
if (optWorldProperties.isPresent()) {
return optWorldProperties.get();
}
final ISaveHandler saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), folderName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer());
WorldInfo worldInfo = saveHandler.loadWorldInfo();
if (worldInfo == null) {
worldInfo = new WorldInfo((WorldSettings) (Object) archetype, folderName);
// Don't want to randomize the seed if there is an existing save file!
if (archetype.isSeedRandomized()) {
((WorldProperties) worldInfo).setSeed(SpongeImpl.random.nextLong());
}
} else {
// DimensionType must be set before world config is created to get proper path
((WorldInfoBridge) worldInfo).bridge$setDimensionType(archetype.getDimensionType());
((WorldInfoBridge) worldInfo).bridge$createWorldConfig();
((WorldProperties) worldInfo).setGeneratorModifiers(archetype.getGeneratorModifiers());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), (WorldProperties) worldInfo);
if (dimensionId != null) {
((WorldInfoBridge) worldInfo).bridge$setDimensionId(dimensionId);
} else if (((WorldInfoBridge) worldInfo).bridge$getDimensionId() == null
//|| ((WorldInfoBridge) worldInfo).bridge$bridge$getDimensionId() == Integer.MIN_VALUE // TODO: Evaulate all uses of Integer.MIN_VALUE for dimension ids
|| getWorldByDimensionId(((WorldInfoBridge) worldInfo).bridge$getDimensionId()).isPresent()) {
// DimensionID is null or 0 or the dimensionID is already assinged to a loaded world
((WorldInfoBridge) worldInfo).bridge$setDimensionId(WorldManager.getNextFreeDimensionId());
}
((WorldProperties) worldInfo).setGeneratorType(archetype.getGeneratorType());
((WorldInfoBridge) worldInfo).bridge$getConfigAdapter().save();
registerWorldProperties((WorldProperties) worldInfo);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Sponge.getCauseStackManager().getCurrentCause(), archetype,
(WorldProperties) worldInfo));
saveHandler.saveWorldInfoWithPlayer(worldInfo, SpongeImpl.getServer().getPlayerList().getHostPlayerData());
return (WorldProperties) worldInfo;
}
public static boolean saveWorldProperties(final WorldProperties properties) {
checkNotNull(properties);
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(((WorldInfoBridge) properties).bridge$getDimensionId());
// If the World represented in the properties is still loaded, save the properties and have the World reload its info
if (optWorldServer.isPresent()) {
final WorldServer worldServer = optWorldServer.get();
worldServer.getSaveHandler().saveWorldInfo((WorldInfo) properties);
worldServer.getSaveHandler().loadWorldInfo();
} else {
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), properties.getWorldName(), true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer()).saveWorldInfo((WorldInfo) properties);
}
((WorldInfoBridge) properties).bridge$getConfigAdapter().save();
// No return values or exceptions so can only assume true.
return true;
}
public static void unloadQueuedWorlds() {
WorldServer server;
while ((server = unloadQueue.poll()) != null) {
unloadWorld(server, true, false);
}
unloadQueue.clear();
}
public static void queueWorldToUnload(final WorldServer worldServer) {
checkNotNull(worldServer);
unloadQueue.add(worldServer);
}
// TODO Result
public static boolean unloadWorld(final WorldServer worldServer, final boolean checkConfig, final boolean isShuttingDown) {
checkNotNull(worldServer);
final MinecraftServer server = SpongeImpl.getServer();
// Likely leaked, don't want to drop leaked world data
if (!worldByDimensionId.containsValue(worldServer)) {
return false;
}
// Vanilla sometimes doesn't remove player entities from world first
if (!isShuttingDown) {
if (!worldServer.playerEntities.isEmpty()) {
return false;
}
// We only check config if base game wants to unload world. If mods/plugins say unload, we unload
if (checkConfig) {
if (((WorldProperties) worldServer.getWorldInfo()).doesKeepSpawnLoaded()) {
return false;
}
}
}
final SpongeConfig<GlobalConfig> globalConfigAdapter = SpongeImpl.getGlobalConfigAdapter();
try (final PhaseContext<?> ignored = GeneralPhase.State.WORLD_UNLOAD.createPhaseContext().source(worldServer)) {
ignored.buildAndSwitch();
final UnloadWorldEvent event = SpongeEventFactory.createUnloadWorldEvent(Sponge.getCauseStackManager().getCurrentCause(),
(org.spongepowered.api.world.World) worldServer);
final boolean isCancelled = SpongeImpl.postEvent(event);
if (!isShuttingDown && isCancelled) {
return false;
}
final ServerWorldBridge mixinWorldServer = (ServerWorldBridge) worldServer;
final int dimensionId = mixinWorldServer.bridge$getDimensionId();
try {
// Don't save if server is stopping to avoid duplicate saving.
if (!isShuttingDown) {
saveWorld(worldServer, true);
}
((WorldInfoBridge) worldServer.getWorldInfo()).bridge$getConfigAdapter().save();
} catch (MinecraftException e) {
e.printStackTrace();
} finally {
SpongeImpl.getLogger().info("Unloading world [{}] ({}/{})", worldServer.getWorldInfo().getWorldName(),
((org.spongepowered.api.world.World) worldServer).getDimension().getType().getId(), dimensionId);
// Stop the lighting executor only when the world is going to unload - there's no point in running any more lighting tasks.
if (globalConfigAdapter.getConfig().getModules().useOptimizations() && globalConfigAdapter.getConfig().getOptimizations().useAsyncLighting()) {
((ServerWorldBridge_AsyncLighting) worldServer).asyncLightingBridge$getLightingExecutor().shutdownNow();
}
worldByDimensionId.remove(dimensionId);
weakWorldByWorld.remove(worldServer);
((MinecraftServerBridge) server).bridge$removeWorldTickTimes(dimensionId);
reorderWorldsVanillaFirst();
}
}
return true;
}
public static void saveWorld(final WorldServer worldServer, final boolean flush) throws MinecraftException {
if (((WorldProperties) worldServer.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) {
return;
} else {
worldServer.saveAllChunks(true, null);
}
if (flush) {
worldServer.flush();
}
}
public static Optional<WorldServer> loadWorld(final UUID uuid) {
checkNotNull(uuid);
// If someone tries to load loaded world, return it
final Optional<org.spongepowered.api.world.World> optWorld = Sponge.getServer().getWorld(uuid);
if (optWorld.isPresent()) {
return Optional.of((WorldServer) optWorld.get());
}
// Check if we even know of this UUID's folder
final String worldFolder = worldUuidByFolderName.inverse().get(uuid);
// We don't know of this UUID at all.
if (worldFolder == null) {
return Optional.empty();
}
return loadWorld(worldFolder, null);
}
public static Optional<WorldServer> loadWorld(final String worldName) {
checkNotNull(worldName);
return loadWorld(worldName, null);
}
public static Optional<WorldServer> loadWorld(final WorldProperties properties) {
checkNotNull(properties);
return loadWorld(properties.getWorldName(), properties);
}
private static Optional<WorldServer> loadWorld(final String worldName, @Nullable WorldProperties properties) {
checkNotNull(worldName);
final Path currentSavesDir = WorldManager.getCurrentSavesDirectory().orElseThrow(() -> new IllegalStateException("Attempt "
+ "made to load world too early!"));
final MinecraftServer server = SpongeImpl.getServer();
final Optional<WorldServer> optExistingWorldServer = getWorld(worldName);
if (optExistingWorldServer.isPresent()) {
return optExistingWorldServer;
}
if (!server.getAllowNether()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. Multi-world is disabled via [allow-nether] in [server.properties].", worldName);
return Optional.empty();
}
final Path worldFolder = currentSavesDir.resolve(worldName);
if (!Files.isDirectory(worldFolder)) {
SpongeImpl.getLogger().error("Unable to load world [{}]. We cannot find its folder under [{}].", worldFolder, currentSavesDir);
return Optional.empty();
}
final ISaveHandler saveHandler = new AnvilSaveHandler(currentSavesDir.toFile(), worldName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer());
// We weren't given a properties, see if one is cached
if (properties == null) {
properties = (WorldProperties) saveHandler.loadWorldInfo();
// We tried :'(
if (properties == null) {
SpongeImpl.getLogger().error("Unable to load world [{}]. No world properties was found!", worldName);
return Optional.empty();
}
}
// TODO: Evaulate all uses of Integer.MIN_VALUE for dimension ids
if (((WorldInfoBridge) properties).bridge$getDimensionId() == null /*|| ((WorldInfoBridge) properties).bridge$bridge$getDimensionId() == Integer.MIN_VALUE*/) {
((WorldInfoBridge) properties).bridge$setDimensionId(getNextFreeDimensionId());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), properties);
registerWorldProperties(properties);
final WorldInfo worldInfo = (WorldInfo) properties;
((WorldInfoBridge) worldInfo).bridge$createWorldConfig();
// check if enabled
if (!((WorldProperties) worldInfo).isEnabled()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. It is disabled.", worldName);
return Optional.empty();
}
final int dimensionId = ((WorldInfoBridge) properties).bridge$getDimensionId();
registerDimension(dimensionId, (DimensionType) (Object) properties.getDimensionType());
registerDimensionPath(dimensionId, worldFolder);
SpongeImpl.getLogger().info("Loading world [{}] ({}/{})", properties.getWorldName(), properties.getDimensionType().getId(), dimensionId);
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, (WorldInfo) properties, new WorldSettings((WorldInfo)
properties));
// Set the worlds on the Minecraft server
reorderWorldsVanillaFirst();
return Optional.of(worldServer);
}
public static void loadAllWorlds(final long defaultSeed, final WorldType defaultWorldType, final String generatorOptions) {
final MinecraftServer server = SpongeImpl.getServer();
// We cannot call getCurrentSavesDirectory here as that would generate a savehandler and trigger a session lock.
// We'll go ahead and make the directories for the save name here so that the migrator won't fail
final Path currentSavesDir = ((MinecraftServerAccessor) server).accessor$getAnvilFile().toPath().resolve(server.getFolderName());
try {
// Symlink needs special handling
if (Files.isSymbolicLink(currentSavesDir)) {
final Path actualPathLink = Files.readSymbolicLink(currentSavesDir);
if (Files.notExists(actualPathLink)) {
Files.createDirectories(actualPathLink);
} else if (!Files.isDirectory(actualPathLink)) {
throw new IOException("Saves directory [" + currentSavesDir + "] symlinked to [" + actualPathLink + "] is not a directory!");
}
} else {
Files.createDirectories(currentSavesDir);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
WorldManager.registerVanillaDimensionPaths(currentSavesDir);
WorldMigrator.migrateWorldsTo(currentSavesDir);
registerExistingSpongeDimensions(currentSavesDir);
for (final Map.Entry<Integer, DimensionType> entry: sortedDimensionMap().entrySet()) {
final int dimensionId = entry.getKey();
final DimensionType dimensionType = entry.getValue();
final org.spongepowered.api.world.DimensionType apiDimensionType = (org.spongepowered.api.world.DimensionType) (Object) dimensionType;
// Skip all worlds besides dimension 0 if multi-world is disabled
if (dimensionId != 0 && !server.getAllowNether()) {
continue;
}
// Skip already loaded worlds by plugins
if (getWorldByDimensionId(dimensionId).isPresent()) {
continue;
}
// Step 1 - Grab the world's data folder
final Path worldFolder = getWorldFolder(dimensionType, dimensionId);
if (worldFolder == null) {
SpongeImpl.getLogger().error("An attempt was made to load a world in dimension [{}] ({}) that has no registered world folder!",
apiDimensionType.getId(), dimensionId);
continue;
}
final String worldFolderName = worldFolder.getFileName().toString();
// Step 2 - See if we are allowed to load it
if (dimensionId != 0) {
final SpongeConfig<? extends GeneralConfigBase> spongeConfig = SpongeHooks.getConfigAdapter(((DimensionTypeBridge)(Object) dimensionType).bridge$getConfigPath(), worldFolderName);
if (!spongeConfig.getConfig().getWorld().isWorldEnabled()) {
SpongeImpl.getLogger().warn("World [{}] ({}/{}) is disabled. World will not be loaded...", worldFolder,
apiDimensionType.getId(), dimensionId);
continue;
}
}
// Step 3 - Get our world information from disk
final ISaveHandler saveHandler;
if (dimensionId == 0) {
saveHandler = server.getActiveAnvilConverter().getSaveLoader(server.getFolderName(), true);
} else {
saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), worldFolderName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer());
}
WorldInfo worldInfo = saveHandler.loadWorldInfo();
final WorldSettings worldSettings;
// If this is integrated server, we need to use the WorldSettings from the client's Single Player menu to construct the worlds
if (server instanceof IntegratedServerBridge) {
worldSettings = ((IntegratedServerBridge) server).bridge$getSettings();
// If this is overworld and a new save, the WorldInfo has already been made but we want to still fire the construct event.
if (dimensionId == 0 && ((IntegratedServerBridge) server).bridge$isNewSave()) {
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Sponge.getCauseStackManager().getCurrentCause(), (WorldArchetype)
(Object) worldSettings, (WorldProperties) worldInfo));
}
} else {
// WorldSettings will be null here on dedicated server so we need to build one
worldSettings = new WorldSettings(defaultSeed, server.getGameType(), server.canStructuresSpawn(), server.isHardcore(),
defaultWorldType);
}
if (worldInfo == null) {
// Step 4 - At this point, we have either have the WorldInfo or we have none. If we have none, we'll use the settings built above to
// create the WorldInfo
worldInfo = createWorldInfoFromSettings(currentSavesDir, apiDimensionType,
dimensionId, worldFolderName, worldSettings, generatorOptions);
} else {
// create config
((WorldInfoBridge) worldInfo).bridge$setDimensionType(apiDimensionType);
((WorldInfoBridge) worldInfo).bridge$createWorldConfig();
((WorldProperties) worldInfo).setGenerateSpawnOnLoad(((DimensionTypeBridge) (Object) dimensionType).bridge$shouldGenerateSpawnOnLoad());
}
// Safety check to ensure we'll get a unique id no matter what
UUID uniqueId = ((WorldProperties) worldInfo).getUniqueId();
if (uniqueId == null) {
setUuidOnProperties(dimensionId == 0 ? currentSavesDir.getParent() : currentSavesDir, (WorldProperties) worldInfo);
uniqueId = ((WorldProperties) worldInfo).getUniqueId();
}
// Check if this world's unique id has already been registered
final String previousWorldForUUID = worldUuidByFolderName.inverse().get(uniqueId);
if (previousWorldForUUID != null) {
SpongeImpl.getLogger().error("UUID [{}] has already been registered by world [{}] but is attempting to be registered by world [{}]."
+ " This means worlds have been copied outside of Sponge. Skipping world load...", uniqueId, previousWorldForUUID, worldInfo.getWorldName());
continue;
}
// Safety check to ensure the world info has the dimension id set
if (((WorldInfoBridge) worldInfo).bridge$getDimensionId() == null) {
((WorldInfoBridge) worldInfo).bridge$setDimensionId(dimensionId);
}
// Keep the LevelName in the LevelInfo up to date with the directory name
if (!worldInfo.getWorldName().equals(worldFolderName)) {
worldInfo.setWorldName(worldFolderName);
}
// Step 5 - Load server resource pack from dimension 0
if (dimensionId == 0) {
((MinecraftServerAccessor) server).accessor$setResourcePackFromWorld(worldFolderName, saveHandler);
}
// Step 6 - Cache the WorldProperties we've made so we don't load from disk later.
registerWorldProperties((WorldProperties) worldInfo);
if (dimensionId != 0 && !((WorldProperties) worldInfo).loadOnStartup()) {
SpongeImpl.getLogger().warn("World [{}] ({}/{}) is set to not load on startup. To load it later, enable "
+ "[load-on-startup] in config or use a plugin.", worldInfo.getWorldName(), apiDimensionType.getId(), dimensionId);
continue;
}
// Step 7 - Finally, we can create the world and tell it to load
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, worldInfo, worldSettings);
;
SpongeImpl.getLogger().info("Loading world [{}] ({}/{})", ((org.spongepowered.api.world.World) worldServer).getName(),
apiDimensionType.getId(), dimensionId);
}
// Set the worlds on the Minecraft server
reorderWorldsVanillaFirst();
}
private static WorldInfo createWorldInfoFromSettings(final Path currentSaveRoot, final org.spongepowered.api.world.DimensionType dimensionType, final int
dimensionId, final String worldFolderName, final WorldSettings worldSettings, final String generatorOptions) {
worldSettings.setGeneratorOptions(generatorOptions);
((WorldSettingsBridge) (Object) worldSettings).bridge$setDimensionType(dimensionType);
((WorldSettingsBridge)(Object) worldSettings).bridge$setGenerateSpawnOnLoad(((DimensionTypeBridge) dimensionType).bridge$shouldGenerateSpawnOnLoad());
final WorldInfo worldInfo = new WorldInfo(worldSettings, worldFolderName);
setUuidOnProperties(dimensionId == 0 ? currentSaveRoot.getParent() : currentSaveRoot, (WorldProperties) worldInfo);
((WorldInfoBridge) worldInfo).bridge$setDimensionId(dimensionId);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Sponge.getCauseStackManager().getCurrentCause(),
(WorldArchetype) (Object) worldSettings, (WorldProperties) worldInfo));
return worldInfo;
}
@SuppressWarnings("ConstantConditions")
private static WorldServer createWorldFromProperties(
final int dimensionId, final ISaveHandler saveHandler, final WorldInfo worldInfo, @Nullable final WorldSettings
worldSettings) {
final MinecraftServer server = SpongeImpl.getServer();
final WorldServer worldServer = new WorldServer(server, saveHandler, worldInfo, dimensionId, server.profiler);
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
WorldManager.reorderWorldsVanillaFirst();
((MinecraftServerBridge) server).bridge$putWorldTickTimes(dimensionId, new long[100]);
worldServer.init();
worldServer.addEventListener(new ServerWorldEventHandler(server, worldServer));
// This code changes from Mojang's to account for per-world API-set GameModes.
if (!server.isSinglePlayer() && worldServer.getWorldInfo().getGameType() == GameType.NOT_SET) {
worldServer.getWorldInfo().setGameType(server.getGameType());
}
((ServerChunkProviderBridge) worldServer.getChunkProvider()).bridge$setForceChunkRequests(true);
try {
SpongeImpl.postEvent(SpongeEventFactory.createLoadWorldEvent(Sponge.getCauseStackManager().getCurrentCause(),
(org.spongepowered.api.world.World) worldServer));
// WorldSettings is only non-null here if this is a newly generated WorldInfo and therefore we need to initialize to calculate spawn.
if (worldSettings != null) {
worldServer.initialize(worldSettings);
}
if (((DimensionTypeBridge) ((org.spongepowered.api.world.World) worldServer).getDimension().getType()).bridge$shouldLoadSpawn()) {
((MinecraftServerBridge) server).bridge$prepareSpawnArea(worldServer);
}
// While we try to prevnt mods from changing a worlds' WorldInfo, we aren't always
// successful. We re-do the fake world check to catch any changes made to WorldInfo
// that would make it invalid
((WorldBridge) worldServer).bridge$clearFakeCheck();
return worldServer;
} finally {
((ServerChunkProviderBridge) worldServer.getChunkProvider()).bridge$setForceChunkRequests(false);
}
}
/**
* Internal use only - Namely for SpongeForge.
* @param dimensionId The world instance dimension id
* @param worldServer The world server
*/
public static void forceAddWorld(final int dimensionId, final WorldServer worldServer) {
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
((MinecraftServerBridge) SpongeImpl.getServer()).bridge$putWorldTickTimes(dimensionId, new long[100]);
}
public static void reorderWorldsVanillaFirst() {
final List<WorldServer> sorted = new LinkedList<>();
final List<Integer> vanillaWorldIds = new ArrayList<>();
WorldServer worldServer = worldByDimensionId.get(0);
if (worldServer != null) {
vanillaWorldIds.add(0);
sorted.add(worldServer);
}
worldServer = worldByDimensionId.get(-1);
if (worldServer != null) {
vanillaWorldIds.add(-1);
sorted.add(worldServer);
}
worldServer = worldByDimensionId.get(1);
if (worldServer != null) {
vanillaWorldIds.add(1);
sorted.add(worldServer);
}
final List<WorldServer> worlds = new ArrayList<>(worldByDimensionId.values());
final Iterator<WorldServer> iterator = worlds.iterator();
while(iterator.hasNext()) {
final ServerWorldBridge mixinWorld = (ServerWorldBridge) iterator.next();
final int dimensionId = mixinWorld.bridge$getDimensionId();
if (vanillaWorldIds.contains(dimensionId)) {
iterator.remove();
}
}
worlds.sort(WORLD_SERVER_COMPARATOR);
sorted.addAll(worlds);
SpongeImpl.getServer().worlds = sorted.toArray(new WorldServer[0]);
}
/**
* Parses a {@link UUID} from disk from other known plugin platforms and sets it on the
* {@link WorldProperties}. Currently only Bukkit is supported.
*/
private static void setUuidOnProperties(final Path savesRoot, final WorldProperties properties) {
checkNotNull(properties);
UUID uuid;
if (properties.getUniqueId() == null || properties.getUniqueId().equals
(UUID.fromString("00000000-0000-0000-0000-000000000000"))) {
// Check if Bukkit's uid.dat file is here and use it
final Path uidPath = savesRoot.resolve(properties.getWorldName()).resolve("uid.dat");
if (Files.notExists(uidPath)) {
uuid = UUID.randomUUID();
} else {
try(final DataInputStream dis = new DataInputStream(Files.newInputStream(uidPath))) {
uuid = new UUID(dis.readLong(), dis.readLong());
} catch (IOException e) {
SpongeImpl.getLogger().error("World folder [{}] has an existing Bukkit unique identifier for it but we encountered issues parsing "
+ "the file. We will have to use a new unique id. Please report this to Sponge ASAP.", properties.getWorldName(), e);
uuid = UUID.randomUUID();
}
}
} else {
uuid = properties.getUniqueId();
}
((WorldInfoBridge) properties).bridge$setUniqueId(uuid);
}
/**
* Handles registering existing Sponge dimensions that are not the root dimension (known as overworld).
*/
private static void registerExistingSpongeDimensions(final Path rootPath) {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(rootPath, LEVEL_AND_SPONGE)) {
for (final Path worldPath : stream) {
final Path spongeLevelPath = worldPath.resolve("level_sponge.dat");
final String worldFolderName = worldPath.getFileName().toString();
final NBTTagCompound compound;
try {
compound = CompressedStreamTools.readCompressed(Files.newInputStream(spongeLevelPath));
} catch (IOException e) {
SpongeImpl.getLogger().error("Failed loading Sponge data for World [{}]}. Report to Sponge ASAP.", worldFolderName, e);
continue;
}
NBTTagCompound spongeDataCompound = compound.getCompoundTag(Constants.Sponge.SPONGE_DATA);
if (!compound.hasKey(Constants.Sponge.SPONGE_DATA)) {
SpongeImpl.getLogger()
.error("World [{}] has Sponge related data in the form of [level-sponge.dat] but the structure is not proper."
+ " Generally, the data is within a [{}] tag but it is not for this world. Report to Sponge ASAP.",
worldFolderName, Constants.Sponge.SPONGE_DATA);
continue;
}
if (!spongeDataCompound.hasKey(Constants.Sponge.World.DIMENSION_ID)) {
SpongeImpl.getLogger().error("World [{}] has no dimension id. Report this to Sponge ASAP.", worldFolderName);
continue;
}
final int dimensionId = spongeDataCompound.getInteger(Constants.Sponge.World.DIMENSION_ID);
// TODO: Evaulate all uses of Integer.MIN_VALUE for dimension ids
/*if (dimensionId == Integer.MIN_VALUE) {
// temporary fix for existing worlds created with wrong dimension id
dimensionId = WorldManager.getNextFreeDimensionId();
}*/
// We do not handle Vanilla dimensions, skip them
if (dimensionId == 0 || dimensionId == -1 || dimensionId == 1) {
continue;
}
spongeDataCompound = DataUtil.spongeDataFixer.process(FixTypes.LEVEL, spongeDataCompound);
String dimensionTypeId = "overworld";
if (spongeDataCompound.hasKey(Constants.Sponge.World.DIMENSION_TYPE)) {
dimensionTypeId = spongeDataCompound.getString(Constants.Sponge.World.DIMENSION_TYPE);
} else {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has no specified dimension type. Defaulting to [{}}]...", worldFolderName,
dimensionId, DimensionTypes.OVERWORLD.getName());
}
dimensionTypeId = fixDimensionTypeId(dimensionTypeId);
final org.spongepowered.api.world.DimensionType dimensionType
= Sponge.getRegistry().getType(org.spongepowered.api.world.DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has specified dimension type that is not registered. Skipping...",
worldFolderName, dimensionId);
continue;
}
spongeDataCompound.setString(Constants.Sponge.World.DIMENSION_TYPE, dimensionTypeId);
if (!spongeDataCompound.hasUniqueId(Constants.UUID)) {
SpongeImpl.getLogger().error("World [{}] (DIM{}) has no valid unique identifier. This is a critical error and should be reported"
+ " to Sponge ASAP.", worldFolderName, dimensionId);
continue;
}
worldFolderByDimensionId.put(dimensionId, worldFolderName);
registerDimensionPath(dimensionId, rootPath.resolve(worldFolderName));
registerDimension(dimensionId, (DimensionType)(Object) dimensionType);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Checks if the saved dimension type contains a modid and if not, attempts to locate one
public static String fixDimensionTypeId(final String name) {
// Since we now store the modid, we need to support older save files that only include id without modid.
if (!name.contains(":")) {
for (final org.spongepowered.api.world.DimensionType type : Sponge.getRegistry().getAllOf(org.spongepowered.api.world.DimensionType.class)) {
final String typeId = (type.getId().substring(type.getId().lastIndexOf(":") + 1));
if (typeId.equals(name)) {
return type.getId();
// Note: We don't update the NBT here but instead fix it on next
// world save in case there are 2 types using same name.
}
}
}
return name;
}
public static CompletableFuture<Optional<WorldProperties>> copyWorld(final WorldProperties worldProperties, final String copyName) {
checkArgument(worldPropertiesByFolderName.containsKey(worldProperties.getWorldName()), "World properties not registered!");
checkArgument(!worldPropertiesByFolderName.containsKey(copyName), "Destination world name already is registered!");
final WorldInfo info = (WorldInfo) worldProperties;
final WorldServer worldServer = worldByDimensionId.get(((WorldInfoBridge) info).bridge$getDimensionId().intValue());
if (worldServer != null) {
try {
saveWorld(worldServer, true);
} catch (MinecraftException e) {
throw new RuntimeException(e);
}
((MinecraftServerBridge) SpongeImpl.getServer()).bridge$setSaveEnabled(false);
}
final CompletableFuture<Optional<WorldProperties>> future = SpongeImpl.getScheduler().submitAsyncTask(new CopyWorldTask(info, copyName));
if (worldServer != null) { // World was loaded
future.thenRun(() -> ((MinecraftServerBridge) SpongeImpl.getServer()).bridge$setSaveEnabled(true));
}
return future;
}
public static Optional<WorldProperties> renameWorld(final WorldProperties worldProperties, final String newName) {
checkNotNull(worldProperties);
checkNotNull(newName);
checkState(!worldByDimensionId.containsKey(((WorldInfoBridge) worldProperties).bridge$getDimensionId()), "World is still loaded!");
final Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(worldProperties.getWorldName());
final Path newWorldFolder = oldWorldFolder.resolveSibling(newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
try {
Files.move(oldWorldFolder, newWorldFolder);
} catch (IOException e) {
return Optional.empty();
}
unregisterWorldProperties(worldProperties, false);
final WorldInfo info = new WorldInfo((WorldInfo) worldProperties);
info.setWorldName(newName);
// As we are moving a world, we want to move the dimension ID and UUID with the world to ensure
// plugins and Sponge do not break.
((WorldInfoBridge) info).bridge$setUniqueId(worldProperties.getUniqueId());
if (((WorldInfoBridge) worldProperties).bridge$getDimensionId() != null) {
((WorldInfoBridge) info).bridge$setDimensionId(((WorldInfoBridge) worldProperties).bridge$getDimensionId());
}
((WorldInfoBridge) info).bridge$createWorldConfig();
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), newName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer())
.saveWorldInfo(info);
registerWorldProperties((WorldProperties) info);
return Optional.of((WorldProperties) info);
}
public static CompletableFuture<Boolean> deleteWorld(final WorldProperties worldProperties) {
checkNotNull(worldProperties);
checkArgument(worldPropertiesByWorldUuid.containsKey(worldProperties.getUniqueId()), "World properties not registered!");
checkState(!worldByDimensionId.containsKey(((WorldInfoBridge) worldProperties).bridge$getDimensionId()), "World not unloaded!");
return SpongeImpl.getScheduler().submitAsyncTask(new DeleteWorldTask(worldProperties));
}
/**
* Called when the server wants to update the difficulty on all worlds.
*
* If the world has a difficulty set via external means (command, plugin, mod) then we honor that difficulty always.
*/
public static void updateServerDifficulty() {
final EnumDifficulty serverDifficulty = SpongeImpl.getServer().getDifficulty();
for (final WorldServer worldServer : getWorlds()) {
final boolean alreadySet = ((WorldInfoBridge) worldServer.getWorldInfo()).bridge$hasCustomDifficulty();
adjustWorldForDifficulty(worldServer, alreadySet ? worldServer.getWorldInfo().getDifficulty() : serverDifficulty, false);
}
}
public static void adjustWorldForDifficulty(final WorldServer worldServer, EnumDifficulty difficulty, final boolean isCustom) {
final MinecraftServer server = SpongeImpl.getServer();
final boolean alreadySet = ((WorldInfoBridge) worldServer.getWorldInfo()).bridge$hasCustomDifficulty();
if (worldServer.getWorldInfo().isHardcoreModeEnabled()) {
difficulty = EnumDifficulty.HARD;
worldServer.setAllowedSpawnTypes(true, true);
} else if (SpongeImpl.getServer().isSinglePlayer()) {
worldServer.setAllowedSpawnTypes(worldServer.getDifficulty() != EnumDifficulty.PEACEFUL, true);
} else {
worldServer.setAllowedSpawnTypes(server.allowSpawnMonsters(), server.getCanSpawnAnimals());
}
if (!alreadySet) {
if (!isCustom) {
((WorldInfoBridge) worldServer.getWorldInfo()).bridge$forceSetDifficulty(difficulty);
} else {
worldServer.getWorldInfo().setDifficulty(difficulty);
}
}
}
private static class CopyWorldTask implements Callable<Optional<WorldProperties>> {
private final WorldInfo oldInfo;
private final String newName;
CopyWorldTask(final WorldInfo info, final String newName) {
this.oldInfo = info;
this.newName = newName;
}
@Override
public Optional<WorldProperties> call() throws Exception {
Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(this.oldInfo.getWorldName());
final Path newWorldFolder = getCurrentSavesDirectory().get().resolve(this.newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
FileVisitor<Path> visitor = new CopyFileVisitor(newWorldFolder);
if (((WorldInfoBridge) this.oldInfo).bridge$getDimensionId() == 0) {
oldWorldFolder = getCurrentSavesDirectory().get();
visitor = new ForwardingFileVisitor<Path>(visitor) {
private boolean root = true;
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
if (!this.root && Files.exists(dir.resolve("level.dat"))) {
return FileVisitResult.SKIP_SUBTREE;
}
this.root = false;
return super.preVisitDirectory(dir, attrs);
}
};
}
// Copy the world folder
Files.walkFileTree(oldWorldFolder, visitor);
final WorldInfo info = new WorldInfo(this.oldInfo);
info.setWorldName(this.newName);
((WorldInfoBridge) info).bridge$setDimensionId(getNextFreeDimensionId());
((WorldInfoBridge) info).bridge$setUniqueId(UUID.randomUUID());
((WorldInfoBridge) info).bridge$createWorldConfig();
registerWorldProperties((WorldProperties) info);
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), this.newName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer())
.saveWorldInfo(info);
return Optional.of((WorldProperties) info);
}
}
private static class DeleteWorldTask implements Callable<Boolean> {
private final WorldProperties props;
DeleteWorldTask(final WorldProperties props) {
this.props = props;
}
@Override
public Boolean call() {
final Path worldFolder = getCurrentSavesDirectory().get().resolve(this.props.getWorldName());
if (!Files.exists(worldFolder)) {
unregisterWorldProperties(this.props, true);
return true;
}
try {
Files.walkFileTree(worldFolder, DeleteFileVisitor.INSTANCE);
unregisterWorldProperties(this.props, true);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
public static void sendDimensionRegistration(final EntityPlayerMP playerMP, final WorldProvider provider) {
// Do nothing in Common
}
public static void loadDimensionDataMap(@Nullable final NBTTagCompound compound) {
usedDimensionIds.clear();
lastUsedDimensionId = 0;
if (compound == null) {
dimensionTypeByDimensionId.keySet().stream().filter(dimensionId -> dimensionId >= 0).forEach(usedDimensionIds::add);
} else {
for (final int id : compound.getIntArray(Constants.Forge.USED_DIMENSION_IDS)) {
usedDimensionIds.add(id);
}
// legacy data (load but don't save)
final int[] intArray = compound.getIntArray(Constants.Legacy.LEGACY_DIMENSION_ARRAY);
for (int i = 0; i < intArray.length; i++) {
final int data = intArray[i];
if (data == 0) continue;
for (int j = 0; j < Integer.SIZE; j++) {
if ((data & (1 << j)) != 0) usedDimensionIds.add(i * Integer.SIZE + j);
}
}
}
}
public static NBTTagCompound saveDimensionDataMap() {
final NBTTagCompound dimMap = new NBTTagCompound();
dimMap.setIntArray(Constants.Forge.USED_DIMENSION_IDS, usedDimensionIds.toIntArray());
return dimMap;
}
public static Optional<Path> getCurrentSavesDirectory() {
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0);
if (optWorldServer.isPresent()) {
return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath());
} else if (SpongeImpl.getGame().getState().ordinal() >= GameState.SERVER_ABOUT_TO_START.ordinal()) {
final SaveHandler saveHandler = (SaveHandler) SpongeImpl.getServer().getActiveAnvilConverter().getSaveLoader(SpongeImpl.getServer().getFolderName(), false);
return Optional.of(saveHandler.getWorldDirectory().toPath());
}
return Optional.empty();
}
public static Map<WorldServer, WorldServer> getWeakWorldMap() {
return weakWorldByWorld;
}
public static int getClientDimensionId(final EntityPlayerMP player, final World world) {
if (!((ServerPlayerEntityBridge) player).bridge$usesCustomClient()) {
final DimensionType type = world.provider.getDimensionType();
if (type == DimensionType.OVERWORLD) {
return 0;
} else if (type == DimensionType.NETHER) {
return -1;
}
return 1;
}
return ((ServerWorldBridge) world).bridge$getDimensionId();
}
public static boolean isKnownWorld(final WorldServer world) {
return weakWorldByWorld.containsKey(world);
}
}
| src/main/java/org/spongepowered/common/world/WorldManager.java | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.world;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.MapMaker;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.datafix.FixTypes;
import net.minecraft.world.DimensionType;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameType;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.minecraft.world.chunk.storage.AnvilSaveHandler;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import org.spongepowered.api.GameState;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.world.UnloadWorldEvent;
import org.spongepowered.api.util.file.CopyFileVisitor;
import org.spongepowered.api.util.file.DeleteFileVisitor;
import org.spongepowered.api.util.file.ForwardingFileVisitor;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.SerializationBehaviors;
import org.spongepowered.api.world.WorldArchetype;
import org.spongepowered.api.world.storage.WorldProperties;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.bridge.entity.player.ServerPlayerEntityBridge;
import org.spongepowered.common.bridge.server.MinecraftServerBridge;
import org.spongepowered.common.bridge.server.integrated.IntegratedServerBridge;
import org.spongepowered.common.bridge.world.DimensionTypeBridge;
import org.spongepowered.common.bridge.world.ServerWorldBridge;
import org.spongepowered.common.bridge.world.ServerWorldBridge_AsyncLighting;
import org.spongepowered.common.bridge.world.WorldBridge;
import org.spongepowered.common.bridge.world.WorldInfoBridge;
import org.spongepowered.common.bridge.world.WorldSettingsBridge;
import org.spongepowered.common.bridge.world.chunk.ServerChunkProviderBridge;
import org.spongepowered.common.config.SpongeConfig;
import org.spongepowered.common.config.type.GeneralConfigBase;
import org.spongepowered.common.config.type.GlobalConfig;
import org.spongepowered.common.data.util.DataUtil;
import org.spongepowered.common.event.tracking.PhaseContext;
import org.spongepowered.common.event.tracking.phase.general.GeneralPhase;
import org.spongepowered.common.mixin.core.server.MinecraftServerAccessor;
import org.spongepowered.common.util.Constants;
import org.spongepowered.common.util.SpongeHooks;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
@SuppressWarnings("ConstantConditions")
public final class WorldManager {
private static final DirectoryStream.Filter<Path> LEVEL_AND_SPONGE =
entry -> Files.isDirectory(entry) && Files.exists(entry.resolve("level.dat")) && Files.exists(entry.resolve("level_sponge.dat"));
private static final Int2ObjectMap<DimensionType> dimensionTypeByTypeId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectMap<DimensionType> dimensionTypeByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectMap<Path> dimensionPathByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectOpenHashMap<WorldServer> worldByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Map<String, WorldProperties> worldPropertiesByFolderName = new HashMap<>(3);
private static final Map<UUID, WorldProperties> worldPropertiesByWorldUuid = new HashMap<>(3);
private static final Map<Integer, String> worldFolderByDimensionId = new HashMap<>();
private static final BiMap<String, UUID> worldUuidByFolderName = HashBiMap.create(3);
private static final IntSet usedDimensionIds = new IntOpenHashSet();
private static final Map<WorldServer, WorldServer> weakWorldByWorld = new MapMaker().weakKeys().weakValues().concurrencyLevel(1).makeMap();
private static final Queue<WorldServer> unloadQueue = new ArrayDeque<>();
private static final Comparator<WorldServer>
WORLD_SERVER_COMPARATOR =
(world1, world2) -> {
final int world1DimId = ((ServerWorldBridge) world1).bridge$getDimensionId();
if (world2 == null) {
return world1DimId;
}
final int world2DimId = ((ServerWorldBridge) world2).bridge$getDimensionId();
return world1DimId - world2DimId;
};
private static boolean isVanillaRegistered = false;
private static int lastUsedDimensionId = 0;
public static void registerVanillaTypesAndDimensions() {
if (!isVanillaRegistered) {
WorldManager.registerDimensionType(0, DimensionType.OVERWORLD);
WorldManager.registerDimensionType(-1, DimensionType.NETHER);
WorldManager.registerDimensionType(1, DimensionType.THE_END);
WorldManager.registerDimension(0, DimensionType.OVERWORLD);
WorldManager.registerDimension(-1, DimensionType.NETHER);
WorldManager.registerDimension(1, DimensionType.THE_END);
}
isVanillaRegistered = true;
}
public static void registerDimensionType(final DimensionType type) {
checkNotNull(type);
final Optional<Integer> optNextDimensionTypeId = getNextFreeDimensionTypeId();
optNextDimensionTypeId.ifPresent(integer -> registerDimensionType(integer, type));
}
public static void registerDimensionType(final int dimensionTypeId, final DimensionType type) {
checkNotNull(type);
if (dimensionTypeByTypeId.containsKey(dimensionTypeId)) {
return;
}
dimensionTypeByTypeId.put(dimensionTypeId, type);
}
private static Optional<Integer> getNextFreeDimensionTypeId() {
Integer highestDimensionTypeId = null;
for (final Integer dimensionTypeId : dimensionTypeByTypeId.keySet()) {
if (highestDimensionTypeId == null || highestDimensionTypeId < dimensionTypeId) {
highestDimensionTypeId = dimensionTypeId;
}
}
if (highestDimensionTypeId != null && highestDimensionTypeId < 127) {
return Optional.of(++highestDimensionTypeId);
}
return Optional.empty();
}
public static Integer getNextFreeDimensionId() {
int next = lastUsedDimensionId;
while (usedDimensionIds.contains(next) || !checkAvailable(next)) {
next++;
}
return lastUsedDimensionId = next;
}
private static boolean checkAvailable(final int dimensionId) {
if (worldByDimensionId.containsKey(dimensionId)) {
usedDimensionIds.add(dimensionId);
return false;
}
return true;
}
public static void registerDimension(final int dimensionId, final DimensionType type) {
checkNotNull(type);
if (!dimensionTypeByTypeId.containsValue(type)) {
return;
}
if (dimensionTypeByDimensionId.containsKey(dimensionId)) {
return;
}
dimensionTypeByDimensionId.put(dimensionId, type);
if (dimensionId >= 0) {
usedDimensionIds.add(dimensionId);
}
}
public static void unregisterDimension(final int dimensionId) {
if (!dimensionTypeByDimensionId.containsKey(dimensionId))
{
throw new IllegalArgumentException("Failed to unregister dimension [" + dimensionId + "] as it is not registered!");
}
dimensionTypeByDimensionId.remove(dimensionId);
}
private static void registerVanillaDimensionPaths(final Path savePath) {
WorldManager.registerDimensionPath(0, savePath);
WorldManager.registerDimensionPath(-1, savePath.resolve("DIM-1"));
WorldManager.registerDimensionPath(1, savePath.resolve("DIM1"));
}
public static void registerDimensionPath(final int dimensionId, final Path dimensionDataRoot) {
checkNotNull(dimensionDataRoot);
dimensionPathByDimensionId.put(dimensionId, dimensionDataRoot);
}
public static Path getDimensionPath(final int dimensionId) {
return dimensionPathByDimensionId.get(dimensionId);
}
public static Optional<DimensionType> getDimensionType(final int dimensionId) {
return Optional.ofNullable(dimensionTypeByDimensionId.get(dimensionId));
}
public static Optional<DimensionType> getDimensionTypeByTypeId(final int dimensionTypeId) {
return Optional.ofNullable(dimensionTypeByTypeId.get(dimensionTypeId));
}
public static Optional<DimensionType> getDimensionType(final Class<? extends WorldProvider> providerClass) {
checkNotNull(providerClass);
for (final Object rawDimensionType : dimensionTypeByTypeId.values()) {
final DimensionType dimensionType = (DimensionType) rawDimensionType;
if (((org.spongepowered.api.world.DimensionType) (Object) dimensionType).getDimensionClass().equals(providerClass)) {
return Optional.of(dimensionType);
}
}
return Optional.empty();
}
public static Collection<DimensionType> getDimensionTypes() {
return dimensionTypeByTypeId.values();
}
public static int[] getRegisteredDimensionIdsFor(final DimensionType type) {
return dimensionTypeByDimensionId.int2ObjectEntrySet().stream()
.filter(entry -> entry.getValue() == type)
.mapToInt(Int2ObjectMap.Entry::getIntKey)
.toArray();
}
public static int[] getRegisteredDimensionIds() {
return dimensionTypeByDimensionId.keySet().toIntArray();
}
@Nullable
private static Path getWorldFolder(final DimensionType dimensionType, final int dimensionId) {
return dimensionPathByDimensionId.get(dimensionId);
}
public static boolean isDimensionRegistered(final int dimensionId) {
return dimensionTypeByDimensionId.containsKey(dimensionId);
}
private static Map<Integer, DimensionType> sortedDimensionMap() {
final Int2ObjectMap<DimensionType> copy = new Int2ObjectOpenHashMap<>(dimensionTypeByDimensionId);
final HashMap<Integer, DimensionType> newMap = new LinkedHashMap<>();
newMap.put(0, copy.remove(0));
DimensionType removed = copy.remove(-1);
if (removed != null) {
newMap.put(-1, removed);
}
removed = copy.remove(1);
if (removed != null) {
newMap.put(1, removed);
}
final int[] ids = copy.keySet().toIntArray();
Arrays.sort(ids);
for (final int id : ids) {
newMap.put(id, copy.get(id));
}
return newMap;
}
public static ObjectIterator<Int2ObjectMap.Entry<WorldServer>> worldsIterator() {
return worldByDimensionId.int2ObjectEntrySet().fastIterator();
}
public static Collection<WorldServer> getWorlds() {
return worldByDimensionId.values();
}
public static Optional<WorldServer> getWorldByDimensionId(final int dimensionId) {
return Optional.ofNullable(worldByDimensionId.get(dimensionId));
}
public static Optional<String> getWorldFolderByDimensionId(final int dimensionId) {
return Optional.ofNullable(worldFolderByDimensionId.get(dimensionId));
}
public static int[] getLoadedWorldDimensionIds() {
return worldByDimensionId.keySet().toIntArray();
}
public static Optional<WorldServer> getWorld(final String worldName) {
for (final WorldServer worldServer : getWorlds()) {
final org.spongepowered.api.world.World apiWorld = (org.spongepowered.api.world.World) worldServer;
if (apiWorld.getName().equals(worldName)) {
return Optional.of(worldServer);
}
}
return Optional.empty();
}
private static void registerWorldProperties(final WorldProperties properties) {
checkNotNull(properties);
worldPropertiesByFolderName.put(properties.getWorldName(), properties);
worldPropertiesByWorldUuid.put(properties.getUniqueId(), properties);
worldUuidByFolderName.put(properties.getWorldName(), properties.getUniqueId());
worldFolderByDimensionId.put(((WorldInfoBridge) properties).bridge$getDimensionId(), properties.getWorldName());
usedDimensionIds.add(((WorldInfoBridge) properties).bridge$getDimensionId());
}
public static void unregisterWorldProperties(final WorldProperties properties, final boolean freeDimensionId) {
checkNotNull(properties);
worldPropertiesByFolderName.remove(properties.getWorldName());
worldPropertiesByWorldUuid.remove(properties.getUniqueId());
worldUuidByFolderName.remove(properties.getWorldName());
worldFolderByDimensionId.remove(((WorldInfoBridge) properties).bridge$getDimensionId());
if (((WorldInfoBridge) properties).bridge$getDimensionId() != null && freeDimensionId) {
usedDimensionIds.remove(((WorldInfoBridge) properties).bridge$getDimensionId());
}
}
// used by SpongeForge client
public static void unregisterAllWorldSettings() {
worldPropertiesByFolderName.clear();
worldPropertiesByWorldUuid.clear();
worldUuidByFolderName.clear();
worldByDimensionId.clear();
worldFolderByDimensionId.clear();
dimensionTypeByDimensionId.clear();
dimensionPathByDimensionId.clear();
usedDimensionIds.clear();
weakWorldByWorld.clear();
isVanillaRegistered = false;
// This is needed to ensure that DimensionType is usable by GuiListWorldSelection, which is only ever used when the server isn't running
registerVanillaTypesAndDimensions();
}
public static Optional<WorldProperties> getWorldProperties(final String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldPropertiesByFolderName.get(folderName));
}
public static Collection<WorldProperties> getAllWorldProperties() {
return Collections.unmodifiableCollection(worldPropertiesByFolderName.values());
}
public static Optional<WorldProperties> getWorldProperties(final UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldPropertiesByWorldUuid.get(uuid));
}
public static Optional<UUID> getUuidForFolder(final String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldUuidByFolderName.get(folderName));
}
public static Optional<String> getFolderForUuid(final UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldUuidByFolderName.inverse().get(uuid));
}
public static WorldProperties createWorldProperties(final String folderName, final WorldArchetype archetype) {
return createWorldProperties(folderName, archetype, null);
}
@SuppressWarnings("ConstantConditions")
public static WorldProperties createWorldProperties(final String folderName, final WorldArchetype archetype, @Nullable final Integer dimensionId) {
checkNotNull(folderName);
checkNotNull(archetype);
final Optional<WorldServer> optWorldServer = getWorld(folderName);
if (optWorldServer.isPresent()) {
return ((org.spongepowered.api.world.World) optWorldServer.get()).getProperties();
}
final Optional<WorldProperties> optWorldProperties = WorldManager.getWorldProperties(folderName);
if (optWorldProperties.isPresent()) {
return optWorldProperties.get();
}
final ISaveHandler saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), folderName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer());
WorldInfo worldInfo = saveHandler.loadWorldInfo();
if (worldInfo == null) {
worldInfo = new WorldInfo((WorldSettings) (Object) archetype, folderName);
// Don't want to randomize the seed if there is an existing save file!
if (archetype.isSeedRandomized()) {
((WorldProperties) worldInfo).setSeed(SpongeImpl.random.nextLong());
}
} else {
// DimensionType must be set before world config is created to get proper path
((WorldInfoBridge) worldInfo).bridge$setDimensionType(archetype.getDimensionType());
((WorldInfoBridge) worldInfo).bridge$createWorldConfig();
((WorldProperties) worldInfo).setGeneratorModifiers(archetype.getGeneratorModifiers());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), (WorldProperties) worldInfo);
if (dimensionId != null) {
((WorldInfoBridge) worldInfo).bridge$setDimensionId(dimensionId);
} else if (((WorldInfoBridge) worldInfo).bridge$getDimensionId() == null
//|| ((WorldInfoBridge) worldInfo).bridge$bridge$getDimensionId() == Integer.MIN_VALUE // TODO: Evaulate all uses of Integer.MIN_VALUE for dimension ids
|| getWorldByDimensionId(((WorldInfoBridge) worldInfo).bridge$getDimensionId()).isPresent()) {
// DimensionID is null or 0 or the dimensionID is already assinged to a loaded world
((WorldInfoBridge) worldInfo).bridge$setDimensionId(WorldManager.getNextFreeDimensionId());
}
((WorldProperties) worldInfo).setGeneratorType(archetype.getGeneratorType());
((WorldInfoBridge) worldInfo).bridge$getConfigAdapter().save();
registerWorldProperties((WorldProperties) worldInfo);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Sponge.getCauseStackManager().getCurrentCause(), archetype,
(WorldProperties) worldInfo));
saveHandler.saveWorldInfoWithPlayer(worldInfo, SpongeImpl.getServer().getPlayerList().getHostPlayerData());
return (WorldProperties) worldInfo;
}
public static boolean saveWorldProperties(final WorldProperties properties) {
checkNotNull(properties);
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(((WorldInfoBridge) properties).bridge$getDimensionId());
// If the World represented in the properties is still loaded, save the properties and have the World reload its info
if (optWorldServer.isPresent()) {
final WorldServer worldServer = optWorldServer.get();
worldServer.getSaveHandler().saveWorldInfo((WorldInfo) properties);
worldServer.getSaveHandler().loadWorldInfo();
} else {
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), properties.getWorldName(), true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer()).saveWorldInfo((WorldInfo) properties);
}
((WorldInfoBridge) properties).bridge$getConfigAdapter().save();
// No return values or exceptions so can only assume true.
return true;
}
public static void unloadQueuedWorlds() {
WorldServer server;
while ((server = unloadQueue.poll()) != null) {
unloadWorld(server, true, false);
}
unloadQueue.clear();
}
public static void queueWorldToUnload(final WorldServer worldServer) {
checkNotNull(worldServer);
unloadQueue.add(worldServer);
}
// TODO Result
public static boolean unloadWorld(final WorldServer worldServer, final boolean checkConfig, final boolean isShuttingDown) {
checkNotNull(worldServer);
final MinecraftServer server = SpongeImpl.getServer();
// Likely leaked, don't want to drop leaked world data
if (!worldByDimensionId.containsValue(worldServer)) {
return false;
}
final SpongeConfig<GlobalConfig> globalConfigAdapter = SpongeImpl.getGlobalConfigAdapter();
if (globalConfigAdapter.getConfig().getModules().useOptimizations() &&
globalConfigAdapter.getConfig().getOptimizations().useAsyncLighting()) {
// The world is unloading - there's no point in running any more lighting tasks
((ServerWorldBridge_AsyncLighting) worldServer).asyncLightingBridge$getLightingExecutor().shutdownNow();
}
// Vanilla sometimes doesn't remove player entities from world first
if (!isShuttingDown) {
if (!worldServer.playerEntities.isEmpty()) {
return false;
}
// We only check config if base game wants to unload world. If mods/plugins say unload, we unload
if (checkConfig) {
if (((WorldProperties) worldServer.getWorldInfo()).doesKeepSpawnLoaded()) {
return false;
}
}
}
try (final PhaseContext<?> ignored = GeneralPhase.State.WORLD_UNLOAD.createPhaseContext().source(worldServer)) {
ignored.buildAndSwitch();
final UnloadWorldEvent event = SpongeEventFactory.createUnloadWorldEvent(Sponge.getCauseStackManager().getCurrentCause(),
(org.spongepowered.api.world.World) worldServer);
final boolean isCancelled = SpongeImpl.postEvent(event);
if (!isShuttingDown && isCancelled) {
return false;
}
final ServerWorldBridge mixinWorldServer = (ServerWorldBridge) worldServer;
final int dimensionId = mixinWorldServer.bridge$getDimensionId();
try {
// Don't save if server is stopping to avoid duplicate saving.
if (!isShuttingDown) {
saveWorld(worldServer, true);
}
((WorldInfoBridge) worldServer.getWorldInfo()).bridge$getConfigAdapter().save();
} catch (MinecraftException e) {
e.printStackTrace();
} finally {
SpongeImpl.getLogger().info("Unloading world [{}] ({}/{})", worldServer.getWorldInfo().getWorldName(),
((org.spongepowered.api.world.World) worldServer).getDimension().getType().getId(), dimensionId);
worldByDimensionId.remove(dimensionId);
weakWorldByWorld.remove(worldServer);
((MinecraftServerBridge) server).bridge$removeWorldTickTimes(dimensionId);
reorderWorldsVanillaFirst();
}
}
return true;
}
public static void saveWorld(final WorldServer worldServer, final boolean flush) throws MinecraftException {
if (((WorldProperties) worldServer.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) {
return;
} else {
worldServer.saveAllChunks(true, null);
}
if (flush) {
worldServer.flush();
}
}
public static Optional<WorldServer> loadWorld(final UUID uuid) {
checkNotNull(uuid);
// If someone tries to load loaded world, return it
final Optional<org.spongepowered.api.world.World> optWorld = Sponge.getServer().getWorld(uuid);
if (optWorld.isPresent()) {
return Optional.of((WorldServer) optWorld.get());
}
// Check if we even know of this UUID's folder
final String worldFolder = worldUuidByFolderName.inverse().get(uuid);
// We don't know of this UUID at all.
if (worldFolder == null) {
return Optional.empty();
}
return loadWorld(worldFolder, null);
}
public static Optional<WorldServer> loadWorld(final String worldName) {
checkNotNull(worldName);
return loadWorld(worldName, null);
}
public static Optional<WorldServer> loadWorld(final WorldProperties properties) {
checkNotNull(properties);
return loadWorld(properties.getWorldName(), properties);
}
private static Optional<WorldServer> loadWorld(final String worldName, @Nullable WorldProperties properties) {
checkNotNull(worldName);
final Path currentSavesDir = WorldManager.getCurrentSavesDirectory().orElseThrow(() -> new IllegalStateException("Attempt "
+ "made to load world too early!"));
final MinecraftServer server = SpongeImpl.getServer();
final Optional<WorldServer> optExistingWorldServer = getWorld(worldName);
if (optExistingWorldServer.isPresent()) {
return optExistingWorldServer;
}
if (!server.getAllowNether()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. Multi-world is disabled via [allow-nether] in [server.properties].", worldName);
return Optional.empty();
}
final Path worldFolder = currentSavesDir.resolve(worldName);
if (!Files.isDirectory(worldFolder)) {
SpongeImpl.getLogger().error("Unable to load world [{}]. We cannot find its folder under [{}].", worldFolder, currentSavesDir);
return Optional.empty();
}
final ISaveHandler saveHandler = new AnvilSaveHandler(currentSavesDir.toFile(), worldName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer());
// We weren't given a properties, see if one is cached
if (properties == null) {
properties = (WorldProperties) saveHandler.loadWorldInfo();
// We tried :'(
if (properties == null) {
SpongeImpl.getLogger().error("Unable to load world [{}]. No world properties was found!", worldName);
return Optional.empty();
}
}
// TODO: Evaulate all uses of Integer.MIN_VALUE for dimension ids
if (((WorldInfoBridge) properties).bridge$getDimensionId() == null /*|| ((WorldInfoBridge) properties).bridge$bridge$getDimensionId() == Integer.MIN_VALUE*/) {
((WorldInfoBridge) properties).bridge$setDimensionId(getNextFreeDimensionId());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), properties);
registerWorldProperties(properties);
final WorldInfo worldInfo = (WorldInfo) properties;
((WorldInfoBridge) worldInfo).bridge$createWorldConfig();
// check if enabled
if (!((WorldProperties) worldInfo).isEnabled()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. It is disabled.", worldName);
return Optional.empty();
}
final int dimensionId = ((WorldInfoBridge) properties).bridge$getDimensionId();
registerDimension(dimensionId, (DimensionType) (Object) properties.getDimensionType());
registerDimensionPath(dimensionId, worldFolder);
SpongeImpl.getLogger().info("Loading world [{}] ({}/{})", properties.getWorldName(), properties.getDimensionType().getId(), dimensionId);
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, (WorldInfo) properties, new WorldSettings((WorldInfo)
properties));
// Set the worlds on the Minecraft server
reorderWorldsVanillaFirst();
return Optional.of(worldServer);
}
public static void loadAllWorlds(final long defaultSeed, final WorldType defaultWorldType, final String generatorOptions) {
final MinecraftServer server = SpongeImpl.getServer();
// We cannot call getCurrentSavesDirectory here as that would generate a savehandler and trigger a session lock.
// We'll go ahead and make the directories for the save name here so that the migrator won't fail
final Path currentSavesDir = ((MinecraftServerAccessor) server).accessor$getAnvilFile().toPath().resolve(server.getFolderName());
try {
// Symlink needs special handling
if (Files.isSymbolicLink(currentSavesDir)) {
final Path actualPathLink = Files.readSymbolicLink(currentSavesDir);
if (Files.notExists(actualPathLink)) {
Files.createDirectories(actualPathLink);
} else if (!Files.isDirectory(actualPathLink)) {
throw new IOException("Saves directory [" + currentSavesDir + "] symlinked to [" + actualPathLink + "] is not a directory!");
}
} else {
Files.createDirectories(currentSavesDir);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
WorldManager.registerVanillaDimensionPaths(currentSavesDir);
WorldMigrator.migrateWorldsTo(currentSavesDir);
registerExistingSpongeDimensions(currentSavesDir);
for (final Map.Entry<Integer, DimensionType> entry: sortedDimensionMap().entrySet()) {
final int dimensionId = entry.getKey();
final DimensionType dimensionType = entry.getValue();
final org.spongepowered.api.world.DimensionType apiDimensionType = (org.spongepowered.api.world.DimensionType) (Object) dimensionType;
// Skip all worlds besides dimension 0 if multi-world is disabled
if (dimensionId != 0 && !server.getAllowNether()) {
continue;
}
// Skip already loaded worlds by plugins
if (getWorldByDimensionId(dimensionId).isPresent()) {
continue;
}
// Step 1 - Grab the world's data folder
final Path worldFolder = getWorldFolder(dimensionType, dimensionId);
if (worldFolder == null) {
SpongeImpl.getLogger().error("An attempt was made to load a world in dimension [{}] ({}) that has no registered world folder!",
apiDimensionType.getId(), dimensionId);
continue;
}
final String worldFolderName = worldFolder.getFileName().toString();
// Step 2 - See if we are allowed to load it
if (dimensionId != 0) {
final SpongeConfig<? extends GeneralConfigBase> spongeConfig = SpongeHooks.getConfigAdapter(((DimensionTypeBridge)(Object) dimensionType).bridge$getConfigPath(), worldFolderName);
if (!spongeConfig.getConfig().getWorld().isWorldEnabled()) {
SpongeImpl.getLogger().warn("World [{}] ({}/{}) is disabled. World will not be loaded...", worldFolder,
apiDimensionType.getId(), dimensionId);
continue;
}
}
// Step 3 - Get our world information from disk
final ISaveHandler saveHandler;
if (dimensionId == 0) {
saveHandler = server.getActiveAnvilConverter().getSaveLoader(server.getFolderName(), true);
} else {
saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), worldFolderName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer());
}
WorldInfo worldInfo = saveHandler.loadWorldInfo();
final WorldSettings worldSettings;
// If this is integrated server, we need to use the WorldSettings from the client's Single Player menu to construct the worlds
if (server instanceof IntegratedServerBridge) {
worldSettings = ((IntegratedServerBridge) server).bridge$getSettings();
// If this is overworld and a new save, the WorldInfo has already been made but we want to still fire the construct event.
if (dimensionId == 0 && ((IntegratedServerBridge) server).bridge$isNewSave()) {
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Sponge.getCauseStackManager().getCurrentCause(), (WorldArchetype)
(Object) worldSettings, (WorldProperties) worldInfo));
}
} else {
// WorldSettings will be null here on dedicated server so we need to build one
worldSettings = new WorldSettings(defaultSeed, server.getGameType(), server.canStructuresSpawn(), server.isHardcore(),
defaultWorldType);
}
if (worldInfo == null) {
// Step 4 - At this point, we have either have the WorldInfo or we have none. If we have none, we'll use the settings built above to
// create the WorldInfo
worldInfo = createWorldInfoFromSettings(currentSavesDir, apiDimensionType,
dimensionId, worldFolderName, worldSettings, generatorOptions);
} else {
// create config
((WorldInfoBridge) worldInfo).bridge$setDimensionType(apiDimensionType);
((WorldInfoBridge) worldInfo).bridge$createWorldConfig();
((WorldProperties) worldInfo).setGenerateSpawnOnLoad(((DimensionTypeBridge) (Object) dimensionType).bridge$shouldGenerateSpawnOnLoad());
}
// Safety check to ensure we'll get a unique id no matter what
UUID uniqueId = ((WorldProperties) worldInfo).getUniqueId();
if (uniqueId == null) {
setUuidOnProperties(dimensionId == 0 ? currentSavesDir.getParent() : currentSavesDir, (WorldProperties) worldInfo);
uniqueId = ((WorldProperties) worldInfo).getUniqueId();
}
// Check if this world's unique id has already been registered
final String previousWorldForUUID = worldUuidByFolderName.inverse().get(uniqueId);
if (previousWorldForUUID != null) {
SpongeImpl.getLogger().error("UUID [{}] has already been registered by world [{}] but is attempting to be registered by world [{}]."
+ " This means worlds have been copied outside of Sponge. Skipping world load...", uniqueId, previousWorldForUUID, worldInfo.getWorldName());
continue;
}
// Safety check to ensure the world info has the dimension id set
if (((WorldInfoBridge) worldInfo).bridge$getDimensionId() == null) {
((WorldInfoBridge) worldInfo).bridge$setDimensionId(dimensionId);
}
// Keep the LevelName in the LevelInfo up to date with the directory name
if (!worldInfo.getWorldName().equals(worldFolderName)) {
worldInfo.setWorldName(worldFolderName);
}
// Step 5 - Load server resource pack from dimension 0
if (dimensionId == 0) {
((MinecraftServerAccessor) server).accessor$setResourcePackFromWorld(worldFolderName, saveHandler);
}
// Step 6 - Cache the WorldProperties we've made so we don't load from disk later.
registerWorldProperties((WorldProperties) worldInfo);
if (dimensionId != 0 && !((WorldProperties) worldInfo).loadOnStartup()) {
SpongeImpl.getLogger().warn("World [{}] ({}/{}) is set to not load on startup. To load it later, enable "
+ "[load-on-startup] in config or use a plugin.", worldInfo.getWorldName(), apiDimensionType.getId(), dimensionId);
continue;
}
// Step 7 - Finally, we can create the world and tell it to load
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, worldInfo, worldSettings);
;
SpongeImpl.getLogger().info("Loading world [{}] ({}/{})", ((org.spongepowered.api.world.World) worldServer).getName(),
apiDimensionType.getId(), dimensionId);
}
// Set the worlds on the Minecraft server
reorderWorldsVanillaFirst();
}
private static WorldInfo createWorldInfoFromSettings(final Path currentSaveRoot, final org.spongepowered.api.world.DimensionType dimensionType, final int
dimensionId, final String worldFolderName, final WorldSettings worldSettings, final String generatorOptions) {
worldSettings.setGeneratorOptions(generatorOptions);
((WorldSettingsBridge) (Object) worldSettings).bridge$setDimensionType(dimensionType);
((WorldSettingsBridge)(Object) worldSettings).bridge$setGenerateSpawnOnLoad(((DimensionTypeBridge) dimensionType).bridge$shouldGenerateSpawnOnLoad());
final WorldInfo worldInfo = new WorldInfo(worldSettings, worldFolderName);
setUuidOnProperties(dimensionId == 0 ? currentSaveRoot.getParent() : currentSaveRoot, (WorldProperties) worldInfo);
((WorldInfoBridge) worldInfo).bridge$setDimensionId(dimensionId);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Sponge.getCauseStackManager().getCurrentCause(),
(WorldArchetype) (Object) worldSettings, (WorldProperties) worldInfo));
return worldInfo;
}
@SuppressWarnings("ConstantConditions")
private static WorldServer createWorldFromProperties(
final int dimensionId, final ISaveHandler saveHandler, final WorldInfo worldInfo, @Nullable final WorldSettings
worldSettings) {
final MinecraftServer server = SpongeImpl.getServer();
final WorldServer worldServer = new WorldServer(server, saveHandler, worldInfo, dimensionId, server.profiler);
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
WorldManager.reorderWorldsVanillaFirst();
((MinecraftServerBridge) server).bridge$putWorldTickTimes(dimensionId, new long[100]);
worldServer.init();
worldServer.addEventListener(new ServerWorldEventHandler(server, worldServer));
// This code changes from Mojang's to account for per-world API-set GameModes.
if (!server.isSinglePlayer() && worldServer.getWorldInfo().getGameType() == GameType.NOT_SET) {
worldServer.getWorldInfo().setGameType(server.getGameType());
}
((ServerChunkProviderBridge) worldServer.getChunkProvider()).bridge$setForceChunkRequests(true);
try {
SpongeImpl.postEvent(SpongeEventFactory.createLoadWorldEvent(Sponge.getCauseStackManager().getCurrentCause(),
(org.spongepowered.api.world.World) worldServer));
// WorldSettings is only non-null here if this is a newly generated WorldInfo and therefore we need to initialize to calculate spawn.
if (worldSettings != null) {
worldServer.initialize(worldSettings);
}
if (((DimensionTypeBridge) ((org.spongepowered.api.world.World) worldServer).getDimension().getType()).bridge$shouldLoadSpawn()) {
((MinecraftServerBridge) server).bridge$prepareSpawnArea(worldServer);
}
// While we try to prevnt mods from changing a worlds' WorldInfo, we aren't always
// successful. We re-do the fake world check to catch any changes made to WorldInfo
// that would make it invalid
((WorldBridge) worldServer).bridge$clearFakeCheck();
return worldServer;
} finally {
((ServerChunkProviderBridge) worldServer.getChunkProvider()).bridge$setForceChunkRequests(false);
}
}
/**
* Internal use only - Namely for SpongeForge.
* @param dimensionId The world instance dimension id
* @param worldServer The world server
*/
public static void forceAddWorld(final int dimensionId, final WorldServer worldServer) {
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
((MinecraftServerBridge) SpongeImpl.getServer()).bridge$putWorldTickTimes(dimensionId, new long[100]);
}
public static void reorderWorldsVanillaFirst() {
final List<WorldServer> sorted = new LinkedList<>();
final List<Integer> vanillaWorldIds = new ArrayList<>();
WorldServer worldServer = worldByDimensionId.get(0);
if (worldServer != null) {
vanillaWorldIds.add(0);
sorted.add(worldServer);
}
worldServer = worldByDimensionId.get(-1);
if (worldServer != null) {
vanillaWorldIds.add(-1);
sorted.add(worldServer);
}
worldServer = worldByDimensionId.get(1);
if (worldServer != null) {
vanillaWorldIds.add(1);
sorted.add(worldServer);
}
final List<WorldServer> worlds = new ArrayList<>(worldByDimensionId.values());
final Iterator<WorldServer> iterator = worlds.iterator();
while(iterator.hasNext()) {
final ServerWorldBridge mixinWorld = (ServerWorldBridge) iterator.next();
final int dimensionId = mixinWorld.bridge$getDimensionId();
if (vanillaWorldIds.contains(dimensionId)) {
iterator.remove();
}
}
worlds.sort(WORLD_SERVER_COMPARATOR);
sorted.addAll(worlds);
SpongeImpl.getServer().worlds = sorted.toArray(new WorldServer[0]);
}
/**
* Parses a {@link UUID} from disk from other known plugin platforms and sets it on the
* {@link WorldProperties}. Currently only Bukkit is supported.
*/
private static void setUuidOnProperties(final Path savesRoot, final WorldProperties properties) {
checkNotNull(properties);
UUID uuid;
if (properties.getUniqueId() == null || properties.getUniqueId().equals
(UUID.fromString("00000000-0000-0000-0000-000000000000"))) {
// Check if Bukkit's uid.dat file is here and use it
final Path uidPath = savesRoot.resolve(properties.getWorldName()).resolve("uid.dat");
if (Files.notExists(uidPath)) {
uuid = UUID.randomUUID();
} else {
try(final DataInputStream dis = new DataInputStream(Files.newInputStream(uidPath))) {
uuid = new UUID(dis.readLong(), dis.readLong());
} catch (IOException e) {
SpongeImpl.getLogger().error("World folder [{}] has an existing Bukkit unique identifier for it but we encountered issues parsing "
+ "the file. We will have to use a new unique id. Please report this to Sponge ASAP.", properties.getWorldName(), e);
uuid = UUID.randomUUID();
}
}
} else {
uuid = properties.getUniqueId();
}
((WorldInfoBridge) properties).bridge$setUniqueId(uuid);
}
/**
* Handles registering existing Sponge dimensions that are not the root dimension (known as overworld).
*/
private static void registerExistingSpongeDimensions(final Path rootPath) {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(rootPath, LEVEL_AND_SPONGE)) {
for (final Path worldPath : stream) {
final Path spongeLevelPath = worldPath.resolve("level_sponge.dat");
final String worldFolderName = worldPath.getFileName().toString();
final NBTTagCompound compound;
try {
compound = CompressedStreamTools.readCompressed(Files.newInputStream(spongeLevelPath));
} catch (IOException e) {
SpongeImpl.getLogger().error("Failed loading Sponge data for World [{}]}. Report to Sponge ASAP.", worldFolderName, e);
continue;
}
NBTTagCompound spongeDataCompound = compound.getCompoundTag(Constants.Sponge.SPONGE_DATA);
if (!compound.hasKey(Constants.Sponge.SPONGE_DATA)) {
SpongeImpl.getLogger()
.error("World [{}] has Sponge related data in the form of [level-sponge.dat] but the structure is not proper."
+ " Generally, the data is within a [{}] tag but it is not for this world. Report to Sponge ASAP.",
worldFolderName, Constants.Sponge.SPONGE_DATA);
continue;
}
if (!spongeDataCompound.hasKey(Constants.Sponge.World.DIMENSION_ID)) {
SpongeImpl.getLogger().error("World [{}] has no dimension id. Report this to Sponge ASAP.", worldFolderName);
continue;
}
final int dimensionId = spongeDataCompound.getInteger(Constants.Sponge.World.DIMENSION_ID);
// TODO: Evaulate all uses of Integer.MIN_VALUE for dimension ids
/*if (dimensionId == Integer.MIN_VALUE) {
// temporary fix for existing worlds created with wrong dimension id
dimensionId = WorldManager.getNextFreeDimensionId();
}*/
// We do not handle Vanilla dimensions, skip them
if (dimensionId == 0 || dimensionId == -1 || dimensionId == 1) {
continue;
}
spongeDataCompound = DataUtil.spongeDataFixer.process(FixTypes.LEVEL, spongeDataCompound);
String dimensionTypeId = "overworld";
if (spongeDataCompound.hasKey(Constants.Sponge.World.DIMENSION_TYPE)) {
dimensionTypeId = spongeDataCompound.getString(Constants.Sponge.World.DIMENSION_TYPE);
} else {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has no specified dimension type. Defaulting to [{}}]...", worldFolderName,
dimensionId, DimensionTypes.OVERWORLD.getName());
}
dimensionTypeId = fixDimensionTypeId(dimensionTypeId);
final org.spongepowered.api.world.DimensionType dimensionType
= Sponge.getRegistry().getType(org.spongepowered.api.world.DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has specified dimension type that is not registered. Skipping...",
worldFolderName, dimensionId);
continue;
}
spongeDataCompound.setString(Constants.Sponge.World.DIMENSION_TYPE, dimensionTypeId);
if (!spongeDataCompound.hasUniqueId(Constants.UUID)) {
SpongeImpl.getLogger().error("World [{}] (DIM{}) has no valid unique identifier. This is a critical error and should be reported"
+ " to Sponge ASAP.", worldFolderName, dimensionId);
continue;
}
worldFolderByDimensionId.put(dimensionId, worldFolderName);
registerDimensionPath(dimensionId, rootPath.resolve(worldFolderName));
registerDimension(dimensionId, (DimensionType)(Object) dimensionType);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Checks if the saved dimension type contains a modid and if not, attempts to locate one
public static String fixDimensionTypeId(final String name) {
// Since we now store the modid, we need to support older save files that only include id without modid.
if (!name.contains(":")) {
for (final org.spongepowered.api.world.DimensionType type : Sponge.getRegistry().getAllOf(org.spongepowered.api.world.DimensionType.class)) {
final String typeId = (type.getId().substring(type.getId().lastIndexOf(":") + 1));
if (typeId.equals(name)) {
return type.getId();
// Note: We don't update the NBT here but instead fix it on next
// world save in case there are 2 types using same name.
}
}
}
return name;
}
public static CompletableFuture<Optional<WorldProperties>> copyWorld(final WorldProperties worldProperties, final String copyName) {
checkArgument(worldPropertiesByFolderName.containsKey(worldProperties.getWorldName()), "World properties not registered!");
checkArgument(!worldPropertiesByFolderName.containsKey(copyName), "Destination world name already is registered!");
final WorldInfo info = (WorldInfo) worldProperties;
final WorldServer worldServer = worldByDimensionId.get(((WorldInfoBridge) info).bridge$getDimensionId().intValue());
if (worldServer != null) {
try {
saveWorld(worldServer, true);
} catch (MinecraftException e) {
throw new RuntimeException(e);
}
((MinecraftServerBridge) SpongeImpl.getServer()).bridge$setSaveEnabled(false);
}
final CompletableFuture<Optional<WorldProperties>> future = SpongeImpl.getScheduler().submitAsyncTask(new CopyWorldTask(info, copyName));
if (worldServer != null) { // World was loaded
future.thenRun(() -> ((MinecraftServerBridge) SpongeImpl.getServer()).bridge$setSaveEnabled(true));
}
return future;
}
public static Optional<WorldProperties> renameWorld(final WorldProperties worldProperties, final String newName) {
checkNotNull(worldProperties);
checkNotNull(newName);
checkState(!worldByDimensionId.containsKey(((WorldInfoBridge) worldProperties).bridge$getDimensionId()), "World is still loaded!");
final Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(worldProperties.getWorldName());
final Path newWorldFolder = oldWorldFolder.resolveSibling(newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
try {
Files.move(oldWorldFolder, newWorldFolder);
} catch (IOException e) {
return Optional.empty();
}
unregisterWorldProperties(worldProperties, false);
final WorldInfo info = new WorldInfo((WorldInfo) worldProperties);
info.setWorldName(newName);
// As we are moving a world, we want to move the dimension ID and UUID with the world to ensure
// plugins and Sponge do not break.
((WorldInfoBridge) info).bridge$setUniqueId(worldProperties.getUniqueId());
if (((WorldInfoBridge) worldProperties).bridge$getDimensionId() != null) {
((WorldInfoBridge) info).bridge$setDimensionId(((WorldInfoBridge) worldProperties).bridge$getDimensionId());
}
((WorldInfoBridge) info).bridge$createWorldConfig();
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), newName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer())
.saveWorldInfo(info);
registerWorldProperties((WorldProperties) info);
return Optional.of((WorldProperties) info);
}
public static CompletableFuture<Boolean> deleteWorld(final WorldProperties worldProperties) {
checkNotNull(worldProperties);
checkArgument(worldPropertiesByWorldUuid.containsKey(worldProperties.getUniqueId()), "World properties not registered!");
checkState(!worldByDimensionId.containsKey(((WorldInfoBridge) worldProperties).bridge$getDimensionId()), "World not unloaded!");
return SpongeImpl.getScheduler().submitAsyncTask(new DeleteWorldTask(worldProperties));
}
/**
* Called when the server wants to update the difficulty on all worlds.
*
* If the world has a difficulty set via external means (command, plugin, mod) then we honor that difficulty always.
*/
public static void updateServerDifficulty() {
final EnumDifficulty serverDifficulty = SpongeImpl.getServer().getDifficulty();
for (final WorldServer worldServer : getWorlds()) {
final boolean alreadySet = ((WorldInfoBridge) worldServer.getWorldInfo()).bridge$hasCustomDifficulty();
adjustWorldForDifficulty(worldServer, alreadySet ? worldServer.getWorldInfo().getDifficulty() : serverDifficulty, false);
}
}
public static void adjustWorldForDifficulty(final WorldServer worldServer, EnumDifficulty difficulty, final boolean isCustom) {
final MinecraftServer server = SpongeImpl.getServer();
final boolean alreadySet = ((WorldInfoBridge) worldServer.getWorldInfo()).bridge$hasCustomDifficulty();
if (worldServer.getWorldInfo().isHardcoreModeEnabled()) {
difficulty = EnumDifficulty.HARD;
worldServer.setAllowedSpawnTypes(true, true);
} else if (SpongeImpl.getServer().isSinglePlayer()) {
worldServer.setAllowedSpawnTypes(worldServer.getDifficulty() != EnumDifficulty.PEACEFUL, true);
} else {
worldServer.setAllowedSpawnTypes(server.allowSpawnMonsters(), server.getCanSpawnAnimals());
}
if (!alreadySet) {
if (!isCustom) {
((WorldInfoBridge) worldServer.getWorldInfo()).bridge$forceSetDifficulty(difficulty);
} else {
worldServer.getWorldInfo().setDifficulty(difficulty);
}
}
}
private static class CopyWorldTask implements Callable<Optional<WorldProperties>> {
private final WorldInfo oldInfo;
private final String newName;
CopyWorldTask(final WorldInfo info, final String newName) {
this.oldInfo = info;
this.newName = newName;
}
@Override
public Optional<WorldProperties> call() throws Exception {
Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(this.oldInfo.getWorldName());
final Path newWorldFolder = getCurrentSavesDirectory().get().resolve(this.newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
FileVisitor<Path> visitor = new CopyFileVisitor(newWorldFolder);
if (((WorldInfoBridge) this.oldInfo).bridge$getDimensionId() == 0) {
oldWorldFolder = getCurrentSavesDirectory().get();
visitor = new ForwardingFileVisitor<Path>(visitor) {
private boolean root = true;
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
if (!this.root && Files.exists(dir.resolve("level.dat"))) {
return FileVisitResult.SKIP_SUBTREE;
}
this.root = false;
return super.preVisitDirectory(dir, attrs);
}
};
}
// Copy the world folder
Files.walkFileTree(oldWorldFolder, visitor);
final WorldInfo info = new WorldInfo(this.oldInfo);
info.setWorldName(this.newName);
((WorldInfoBridge) info).bridge$setDimensionId(getNextFreeDimensionId());
((WorldInfoBridge) info).bridge$setUniqueId(UUID.randomUUID());
((WorldInfoBridge) info).bridge$createWorldConfig();
registerWorldProperties((WorldProperties) info);
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), this.newName, true, ((MinecraftServerAccessor) SpongeImpl.getServer()).accessor$getDataFixer())
.saveWorldInfo(info);
return Optional.of((WorldProperties) info);
}
}
private static class DeleteWorldTask implements Callable<Boolean> {
private final WorldProperties props;
DeleteWorldTask(final WorldProperties props) {
this.props = props;
}
@Override
public Boolean call() {
final Path worldFolder = getCurrentSavesDirectory().get().resolve(this.props.getWorldName());
if (!Files.exists(worldFolder)) {
unregisterWorldProperties(this.props, true);
return true;
}
try {
Files.walkFileTree(worldFolder, DeleteFileVisitor.INSTANCE);
unregisterWorldProperties(this.props, true);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
public static void sendDimensionRegistration(final EntityPlayerMP playerMP, final WorldProvider provider) {
// Do nothing in Common
}
public static void loadDimensionDataMap(@Nullable final NBTTagCompound compound) {
usedDimensionIds.clear();
lastUsedDimensionId = 0;
if (compound == null) {
dimensionTypeByDimensionId.keySet().stream().filter(dimensionId -> dimensionId >= 0).forEach(usedDimensionIds::add);
} else {
for (final int id : compound.getIntArray(Constants.Forge.USED_DIMENSION_IDS)) {
usedDimensionIds.add(id);
}
// legacy data (load but don't save)
final int[] intArray = compound.getIntArray(Constants.Legacy.LEGACY_DIMENSION_ARRAY);
for (int i = 0; i < intArray.length; i++) {
final int data = intArray[i];
if (data == 0) continue;
for (int j = 0; j < Integer.SIZE; j++) {
if ((data & (1 << j)) != 0) usedDimensionIds.add(i * Integer.SIZE + j);
}
}
}
}
public static NBTTagCompound saveDimensionDataMap() {
final NBTTagCompound dimMap = new NBTTagCompound();
dimMap.setIntArray(Constants.Forge.USED_DIMENSION_IDS, usedDimensionIds.toIntArray());
return dimMap;
}
public static Optional<Path> getCurrentSavesDirectory() {
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0);
if (optWorldServer.isPresent()) {
return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath());
} else if (SpongeImpl.getGame().getState().ordinal() >= GameState.SERVER_ABOUT_TO_START.ordinal()) {
final SaveHandler saveHandler = (SaveHandler) SpongeImpl.getServer().getActiveAnvilConverter().getSaveLoader(SpongeImpl.getServer().getFolderName(), false);
return Optional.of(saveHandler.getWorldDirectory().toPath());
}
return Optional.empty();
}
public static Map<WorldServer, WorldServer> getWeakWorldMap() {
return weakWorldByWorld;
}
public static int getClientDimensionId(final EntityPlayerMP player, final World world) {
if (!((ServerPlayerEntityBridge) player).bridge$usesCustomClient()) {
final DimensionType type = world.provider.getDimensionType();
if (type == DimensionType.OVERWORLD) {
return 0;
} else if (type == DimensionType.NETHER) {
return -1;
}
return 1;
}
return ((ServerWorldBridge) world).bridge$getDimensionId();
}
public static boolean isKnownWorld(final WorldServer world) {
return weakWorldByWorld.containsKey(world);
}
}
| Stop lighting executor after world is going to be unloaded
| src/main/java/org/spongepowered/common/world/WorldManager.java | Stop lighting executor after world is going to be unloaded | <ide><path>rc/main/java/org/spongepowered/common/world/WorldManager.java
<ide> return false;
<ide> }
<ide>
<del> final SpongeConfig<GlobalConfig> globalConfigAdapter = SpongeImpl.getGlobalConfigAdapter();
<del>
<del> if (globalConfigAdapter.getConfig().getModules().useOptimizations() &&
<del> globalConfigAdapter.getConfig().getOptimizations().useAsyncLighting()) {
<del>
<del> // The world is unloading - there's no point in running any more lighting tasks
<del> ((ServerWorldBridge_AsyncLighting) worldServer).asyncLightingBridge$getLightingExecutor().shutdownNow();
<del> }
<del>
<ide> // Vanilla sometimes doesn't remove player entities from world first
<ide> if (!isShuttingDown) {
<ide> if (!worldServer.playerEntities.isEmpty()) {
<ide> }
<ide> }
<ide> }
<add>
<add> final SpongeConfig<GlobalConfig> globalConfigAdapter = SpongeImpl.getGlobalConfigAdapter();
<ide>
<ide> try (final PhaseContext<?> ignored = GeneralPhase.State.WORLD_UNLOAD.createPhaseContext().source(worldServer)) {
<ide> ignored.buildAndSwitch();
<ide> } finally {
<ide> SpongeImpl.getLogger().info("Unloading world [{}] ({}/{})", worldServer.getWorldInfo().getWorldName(),
<ide> ((org.spongepowered.api.world.World) worldServer).getDimension().getType().getId(), dimensionId);
<add>
<add> // Stop the lighting executor only when the world is going to unload - there's no point in running any more lighting tasks.
<add> if (globalConfigAdapter.getConfig().getModules().useOptimizations() && globalConfigAdapter.getConfig().getOptimizations().useAsyncLighting()) {
<add> ((ServerWorldBridge_AsyncLighting) worldServer).asyncLightingBridge$getLightingExecutor().shutdownNow();
<add> }
<add>
<ide> worldByDimensionId.remove(dimensionId);
<ide> weakWorldByWorld.remove(worldServer);
<ide> ((MinecraftServerBridge) server).bridge$removeWorldTickTimes(dimensionId); |
|
Java | apache-2.0 | f7e59390a40baf1dca76a103429b9265af9cf591 | 0 | data-integrations/salesforce | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.plugin.source.streaming;
import io.cdap.plugin.salesforce.SalesforceConstants;
import io.cdap.plugin.salesforce.authenticator.Authenticator;
import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials;
import io.cdap.plugin.salesforce.plugin.OAuthInfo;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.client.BayeuxClient;
import org.cometd.client.transport.ClientTransport;
import org.cometd.client.transport.LongPollingTransport;
import org.cometd.common.JSONContext;
import org.cometd.common.JacksonJSONContextClient;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Listens to a specific Salesforce pushTopic and adds messages to the blocking queue,
* which can be read by a user of the class.
*/
public class SalesforcePushTopicListener {
private static final Logger LOG = LoggerFactory.getLogger(SalesforcePushTopicListener.class);
private static final String DEFAULT_PUSH_ENDPOINT = "/cometd/" + SalesforceConstants.API_VERSION;
/**
* Timeout of 110 seconds is enforced by Salesforce Streaming API and is not configurable.
* So we enforce the same on client.
*/
private static final long CONNECTION_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(110);
private static final long HANDSHAKE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(110);
private static final int HANDSHAKE_CHECK_INTERVAL_MS = 1000;
// store message string not JSONObject, since it's not serializable for later Spark usage
private final BlockingQueue<String> messagesQueue = new LinkedBlockingQueue<>();
private final AuthenticatorCredentials credentials;
private final String topic;
private BayeuxClient bayeuxClient;
private JSONContext.Client jsonContext;
public SalesforcePushTopicListener(AuthenticatorCredentials credentials, String topic) {
this.credentials = credentials;
this.topic = topic;
}
/**
* Start the Bayeux Client which listens to the Salesforce PushTopic and saves received messages
* to the queue.
*/
public void start() {
try {
createSalesforceListener();
waitForHandshake();
subscribe();
} catch (Exception e) {
throw new RuntimeException("Could not start client", e);
}
}
/**
* Retrieves message from the messages queue, waiting up to the
* specified wait time if necessary for an element to become available.
*
* @param timeout how long to wait before giving up
* @param unit timeunit of timeout
* @return the message, or {@code null} if the specified
* waiting time elapses before an element is available
* @throws InterruptedException blocking call is interrupted
*/
public String getMessage(long timeout, TimeUnit unit) throws InterruptedException {
return messagesQueue.poll(timeout, unit);
}
private BayeuxClient getClient(AuthenticatorCredentials credentials) throws Exception {
OAuthInfo oAuthInfo = Authenticator.getOAuthInfo(credentials);
SslContextFactory sslContextFactory = new SslContextFactory();
// Set up a Jetty HTTP client to use with CometD
HttpClient httpClient = new HttpClient(sslContextFactory);
httpClient.setConnectTimeout(CONNECTION_TIMEOUT_MS);
httpClient.start();
// Use the Jackson implementation
jsonContext = new JacksonJSONContextClient();
Map<String, Object> transportOptions = new HashMap<>();
transportOptions.put(ClientTransport.JSON_CONTEXT_OPTION, jsonContext);
// Adds the OAuth header in LongPollingTransport
LongPollingTransport transport = new LongPollingTransport(
transportOptions, httpClient) {
@Override
protected void customize(Request exchange) {
super.customize(exchange);
exchange.header("Authorization", "OAuth " + oAuthInfo.getAccessToken());
}
};
// Now set up the Bayeux client itself
return new BayeuxClient(oAuthInfo.getInstanceURL() + DEFAULT_PUSH_ENDPOINT, transport);
}
public void createSalesforceListener() throws Exception {
bayeuxClient = getClient(credentials);
bayeuxClient.getChannel(Channel.META_HANDSHAKE).addListener
((ClientSessionChannel.MessageListener) (channel, message) -> {
boolean success = message.isSuccessful();
if (!success) {
String error = (String) message.get("error");
if (error != null) {
throw new RuntimeException(String.format("Error in meta handshake, errorMessage: %s", error));
} else if (message.get("exception") instanceof Exception) {
Exception exception = (Exception) message.get("exception");
if (exception != null) {
throw new RuntimeException(String.format("Exception in meta handshake %s", exception));
}
} else {
throw new RuntimeException(String.format("Error in meta handshake, message: %s", message));
}
}
});
bayeuxClient.getChannel(Channel.META_CONNECT).addListener(
(ClientSessionChannel.MessageListener) (channel, message) -> {
boolean success = message.isSuccessful();
if (!success) {
String error = (String) message.get("error");
Map<String, Object> advice = message.getAdvice();
if (error != null) {
LOG.error("Error during CONNECT: {}", error);
LOG.debug("Advice during CONNECT: {}", advice);
}
// Error Codes Reference in Salesforce Streaming :
// https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/streaming_error_codes
// .htm
if (advice.get("reconnect").equals("handshake")) {
LOG.debug("Reconnecting to Salesforce Push Topic");
try {
reconnectToTopic();
} catch (Exception e) {
throw new RuntimeException("Error in reconnecting to salesforce ", e);
}
} else {
throw new RuntimeException(String.format("Error in meta connect, errorMessage: %s Advice: %s", error,
advice));
}
}
});
bayeuxClient.getChannel(Channel.META_SUBSCRIBE).addListener(
(ClientSessionChannel.MessageListener) (channel, message) -> {
boolean success = message.isSuccessful();
if (!success) {
String error = (String) message.get("error");
if (error != null) {
throw new RuntimeException(String.format("Error in meta subscribe, errorMessage: %s", error));
} else {
throw new RuntimeException(String.format("Error in meta subscribe, message: %s", message));
}
}
});
}
public void reconnectToTopic() throws Exception {
disconnectStream();
createSalesforceListener();
waitForHandshake();
subscribe();
}
private void waitForHandshake() {
bayeuxClient.handshake();
try {
Awaitility.await()
.atMost(SalesforcePushTopicListener.HANDSHAKE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.pollInterval(SalesforcePushTopicListener.HANDSHAKE_CHECK_INTERVAL_MS, TimeUnit.MILLISECONDS)
.until(() -> bayeuxClient.isHandshook());
} catch (ConditionTimeoutException e) {
throw new IllegalStateException("Client could not handshake with Salesforce server", e);
}
LOG.debug("Client handshake done");
}
private void subscribe() {
bayeuxClient.getChannel("/topic/" + topic).subscribe((channel, message) -> {
LOG.debug("Message : {}", message);
messagesQueue.add(jsonContext.getGenerator().generate(message.getDataAsMap()));
});
}
public void disconnectStream() {
bayeuxClient.getChannel("/topic/" + topic).unsubscribe();
bayeuxClient.disconnect();
}
}
| src/main/java/io/cdap/plugin/salesforce/plugin/source/streaming/SalesforcePushTopicListener.java | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.plugin.source.streaming;
import io.cdap.plugin.salesforce.SalesforceConstants;
import io.cdap.plugin.salesforce.authenticator.Authenticator;
import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials;
import io.cdap.plugin.salesforce.plugin.OAuthInfo;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import org.cometd.client.BayeuxClient;
import org.cometd.client.transport.ClientTransport;
import org.cometd.client.transport.LongPollingTransport;
import org.cometd.common.JSONContext;
import org.cometd.common.JacksonJSONContextClient;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Listens to a specific Salesforce pushTopic and adds messages to the blocking queue,
* which can be read by a user of the class.
*/
public class SalesforcePushTopicListener {
private static final Logger LOG = LoggerFactory.getLogger(SalesforcePushTopicListener.class);
private static final String DEFAULT_PUSH_ENDPOINT = "/cometd/" + SalesforceConstants.API_VERSION;
/**
* Timeout of 110 seconds is enforced by Salesforce Streaming API and is not configurable.
* So we enforce the same on client.
*/
private static final long CONNECTION_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(110);
private static final long HANDSHAKE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(110);
private static final int HANDSHAKE_CHECK_INTERVAL_MS = 1000;
// store message string not JSONObject, since it's not serializable for later Spark usage
private final BlockingQueue<String> messagesQueue = new LinkedBlockingQueue<>();
private final AuthenticatorCredentials credentials;
private final String topic;
private JSONContext.Client jsonContext;
public SalesforcePushTopicListener(AuthenticatorCredentials credentials, String topic) {
this.credentials = credentials;
this.topic = topic;
}
/**
* Start the Bayeux Client which listens to the Salesforce PushTopic and saves received messages
* to the queue.
*/
public void start() {
try {
BayeuxClient bayeuxClient = getClient(credentials);
waitForHandshake(bayeuxClient, HANDSHAKE_TIMEOUT_MS, HANDSHAKE_CHECK_INTERVAL_MS);
LOG.debug("Client handshake done");
bayeuxClient.getChannel("/topic/" + topic).subscribe((channel, message) -> {
messagesQueue.add(jsonContext.getGenerator().generate(message.getDataAsMap()));
});
} catch (Exception e) {
throw new RuntimeException("Could not start client", e);
}
}
/**
* Retrieves message from the messages queue, waiting up to the
* specified wait time if necessary for an element to become available.
*
* @param timeout how long to wait before giving up
* @param unit timeunit of timeout
* @return the message, or {@code null} if the specified
* waiting time elapses before an element is available
* @throws InterruptedException blocking call is interrupted
*/
public String getMessage(long timeout, TimeUnit unit) throws InterruptedException {
return messagesQueue.poll(timeout, unit);
}
private BayeuxClient getClient(AuthenticatorCredentials credentials) throws Exception {
OAuthInfo oAuthInfo = Authenticator.getOAuthInfo(credentials);
SslContextFactory sslContextFactory = new SslContextFactory();
// Set up a Jetty HTTP client to use with CometD
HttpClient httpClient = new HttpClient(sslContextFactory);
httpClient.setConnectTimeout(CONNECTION_TIMEOUT_MS);
httpClient.start();
// Use the Jackson implementation
jsonContext = new JacksonJSONContextClient();
Map<String, Object> transportOptions = new HashMap<>();
transportOptions.put(ClientTransport.JSON_CONTEXT_OPTION, jsonContext);
// Adds the OAuth header in LongPollingTransport
LongPollingTransport transport = new LongPollingTransport(
transportOptions, httpClient) {
@Override
protected void customize(Request exchange) {
super.customize(exchange);
exchange.header("Authorization", "OAuth " + oAuthInfo.getAccessToken());
}
};
// Now set up the Bayeux client itself
BayeuxClient client = new BayeuxClient(oAuthInfo.getInstanceURL() + DEFAULT_PUSH_ENDPOINT, transport);
client.handshake();
return client;
}
private void waitForHandshake(BayeuxClient client,
long timeoutInMilliseconds, long intervalInMilliseconds) {
try {
Awaitility.await()
.atMost(timeoutInMilliseconds, TimeUnit.MILLISECONDS)
.pollInterval(intervalInMilliseconds, TimeUnit.MILLISECONDS)
.until(() -> client.isHandshook());
} catch (ConditionTimeoutException e) {
throw new IllegalStateException("Client could not handshake with Salesforce server", e);
}
}
}
| PLUGIN-1435 : Salesforce Streaming Bug Fix
| src/main/java/io/cdap/plugin/salesforce/plugin/source/streaming/SalesforcePushTopicListener.java | PLUGIN-1435 : Salesforce Streaming Bug Fix | <ide><path>rc/main/java/io/cdap/plugin/salesforce/plugin/source/streaming/SalesforcePushTopicListener.java
<ide> import io.cdap.plugin.salesforce.plugin.OAuthInfo;
<ide> import org.awaitility.Awaitility;
<ide> import org.awaitility.core.ConditionTimeoutException;
<add>import org.cometd.bayeux.Channel;
<add>import org.cometd.bayeux.client.ClientSessionChannel;
<ide> import org.cometd.client.BayeuxClient;
<ide> import org.cometd.client.transport.ClientTransport;
<ide> import org.cometd.client.transport.LongPollingTransport;
<ide>
<ide> private final AuthenticatorCredentials credentials;
<ide> private final String topic;
<add> private BayeuxClient bayeuxClient;
<ide>
<ide> private JSONContext.Client jsonContext;
<ide>
<ide> */
<ide> public void start() {
<ide> try {
<del> BayeuxClient bayeuxClient = getClient(credentials);
<del> waitForHandshake(bayeuxClient, HANDSHAKE_TIMEOUT_MS, HANDSHAKE_CHECK_INTERVAL_MS);
<del> LOG.debug("Client handshake done");
<del> bayeuxClient.getChannel("/topic/" + topic).subscribe((channel, message) -> {
<del> messagesQueue.add(jsonContext.getGenerator().generate(message.getDataAsMap()));
<del> });
<del>
<add> createSalesforceListener();
<add> waitForHandshake();
<add> subscribe();
<ide> } catch (Exception e) {
<ide> throw new RuntimeException("Could not start client", e);
<ide> }
<ide> * specified wait time if necessary for an element to become available.
<ide> *
<ide> * @param timeout how long to wait before giving up
<del> * @param unit timeunit of timeout
<add> * @param unit timeunit of timeout
<ide> * @return the message, or {@code null} if the specified
<ide> * waiting time elapses before an element is available
<ide> * @throws InterruptedException blocking call is interrupted
<ide> };
<ide>
<ide> // Now set up the Bayeux client itself
<del> BayeuxClient client = new BayeuxClient(oAuthInfo.getInstanceURL() + DEFAULT_PUSH_ENDPOINT, transport);
<del> client.handshake();
<del>
<del> return client;
<del> }
<del>
<del> private void waitForHandshake(BayeuxClient client,
<del> long timeoutInMilliseconds, long intervalInMilliseconds) {
<add> return new BayeuxClient(oAuthInfo.getInstanceURL() + DEFAULT_PUSH_ENDPOINT, transport);
<add> }
<add>
<add> public void createSalesforceListener() throws Exception {
<add> bayeuxClient = getClient(credentials);
<add> bayeuxClient.getChannel(Channel.META_HANDSHAKE).addListener
<add> ((ClientSessionChannel.MessageListener) (channel, message) -> {
<add>
<add> boolean success = message.isSuccessful();
<add> if (!success) {
<add> String error = (String) message.get("error");
<add> if (error != null) {
<add> throw new RuntimeException(String.format("Error in meta handshake, errorMessage: %s", error));
<add> } else if (message.get("exception") instanceof Exception) {
<add> Exception exception = (Exception) message.get("exception");
<add> if (exception != null) {
<add> throw new RuntimeException(String.format("Exception in meta handshake %s", exception));
<add> }
<add> } else {
<add> throw new RuntimeException(String.format("Error in meta handshake, message: %s", message));
<add> }
<add>
<add> }
<add> });
<add>
<add> bayeuxClient.getChannel(Channel.META_CONNECT).addListener(
<add> (ClientSessionChannel.MessageListener) (channel, message) -> {
<add>
<add> boolean success = message.isSuccessful();
<add> if (!success) {
<add> String error = (String) message.get("error");
<add> Map<String, Object> advice = message.getAdvice();
<add>
<add> if (error != null) {
<add> LOG.error("Error during CONNECT: {}", error);
<add> LOG.debug("Advice during CONNECT: {}", advice);
<add> }
<add> // Error Codes Reference in Salesforce Streaming :
<add> // https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/streaming_error_codes
<add> // .htm
<add> if (advice.get("reconnect").equals("handshake")) {
<add> LOG.debug("Reconnecting to Salesforce Push Topic");
<add> try {
<add> reconnectToTopic();
<add> } catch (Exception e) {
<add> throw new RuntimeException("Error in reconnecting to salesforce ", e);
<add> }
<add> } else {
<add> throw new RuntimeException(String.format("Error in meta connect, errorMessage: %s Advice: %s", error,
<add> advice));
<add> }
<add> }
<add> });
<add>
<add> bayeuxClient.getChannel(Channel.META_SUBSCRIBE).addListener(
<add> (ClientSessionChannel.MessageListener) (channel, message) -> {
<add>
<add> boolean success = message.isSuccessful();
<add> if (!success) {
<add> String error = (String) message.get("error");
<add> if (error != null) {
<add> throw new RuntimeException(String.format("Error in meta subscribe, errorMessage: %s", error));
<add> } else {
<add> throw new RuntimeException(String.format("Error in meta subscribe, message: %s", message));
<add> }
<add> }
<add> });
<add>
<add> }
<add>
<add> public void reconnectToTopic() throws Exception {
<add> disconnectStream();
<add> createSalesforceListener();
<add> waitForHandshake();
<add> subscribe();
<add> }
<add>
<add> private void waitForHandshake() {
<add> bayeuxClient.handshake();
<add>
<ide> try {
<ide> Awaitility.await()
<del> .atMost(timeoutInMilliseconds, TimeUnit.MILLISECONDS)
<del> .pollInterval(intervalInMilliseconds, TimeUnit.MILLISECONDS)
<del> .until(() -> client.isHandshook());
<add> .atMost(SalesforcePushTopicListener.HANDSHAKE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
<add> .pollInterval(SalesforcePushTopicListener.HANDSHAKE_CHECK_INTERVAL_MS, TimeUnit.MILLISECONDS)
<add> .until(() -> bayeuxClient.isHandshook());
<ide> } catch (ConditionTimeoutException e) {
<ide> throw new IllegalStateException("Client could not handshake with Salesforce server", e);
<ide> }
<add> LOG.debug("Client handshake done");
<add> }
<add>
<add> private void subscribe() {
<add> bayeuxClient.getChannel("/topic/" + topic).subscribe((channel, message) -> {
<add> LOG.debug("Message : {}", message);
<add> messagesQueue.add(jsonContext.getGenerator().generate(message.getDataAsMap()));
<add> });
<add> }
<add>
<add> public void disconnectStream() {
<add> bayeuxClient.getChannel("/topic/" + topic).unsubscribe();
<add> bayeuxClient.disconnect();
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | 817d401125f6f4ba93f50bb03dabbf122f08ea4a | 0 | eosimosu/generator-jhipster,danielpetisme/generator-jhipster,duderoot/generator-jhipster,ziogiugno/generator-jhipster,duderoot/generator-jhipster,dimeros/generator-jhipster,robertmilowski/generator-jhipster,vivekmore/generator-jhipster,pascalgrimaud/generator-jhipster,dimeros/generator-jhipster,robertmilowski/generator-jhipster,PierreBesson/generator-jhipster,hdurix/generator-jhipster,ctamisier/generator-jhipster,hdurix/generator-jhipster,duderoot/generator-jhipster,dynamicguy/generator-jhipster,robertmilowski/generator-jhipster,atomfrede/generator-jhipster,erikkemperman/generator-jhipster,liseri/generator-jhipster,vivekmore/generator-jhipster,sohibegit/generator-jhipster,wmarques/generator-jhipster,gmarziou/generator-jhipster,ruddell/generator-jhipster,dynamicguy/generator-jhipster,mosoft521/generator-jhipster,sohibegit/generator-jhipster,hdurix/generator-jhipster,atomfrede/generator-jhipster,sohibegit/generator-jhipster,rifatdover/generator-jhipster,mraible/generator-jhipster,danielpetisme/generator-jhipster,jkutner/generator-jhipster,sohibegit/generator-jhipster,erikkemperman/generator-jhipster,eosimosu/generator-jhipster,pascalgrimaud/generator-jhipster,atomfrede/generator-jhipster,cbornet/generator-jhipster,erikkemperman/generator-jhipster,jhipster/generator-jhipster,jhipster/generator-jhipster,ctamisier/generator-jhipster,atomfrede/generator-jhipster,wmarques/generator-jhipster,cbornet/generator-jhipster,danielpetisme/generator-jhipster,cbornet/generator-jhipster,Tcharl/generator-jhipster,dynamicguy/generator-jhipster,ruddell/generator-jhipster,Tcharl/generator-jhipster,robertmilowski/generator-jhipster,Tcharl/generator-jhipster,eosimosu/generator-jhipster,ctamisier/generator-jhipster,erikkemperman/generator-jhipster,mraible/generator-jhipster,danielpetisme/generator-jhipster,gmarziou/generator-jhipster,mosoft521/generator-jhipster,Tcharl/generator-jhipster,pascalgrimaud/generator-jhipster,jhipster/generator-jhipster,dimeros/generator-jhipster,jhipster/generator-jhipster,gmarziou/generator-jhipster,sohibegit/generator-jhipster,ziogiugno/generator-jhipster,dynamicguy/generator-jhipster,liseri/generator-jhipster,wmarques/generator-jhipster,rifatdover/generator-jhipster,vivekmore/generator-jhipster,mraible/generator-jhipster,ruddell/generator-jhipster,hdurix/generator-jhipster,liseri/generator-jhipster,PierreBesson/generator-jhipster,sendilkumarn/generator-jhipster,PierreBesson/generator-jhipster,sendilkumarn/generator-jhipster,mosoft521/generator-jhipster,gmarziou/generator-jhipster,mraible/generator-jhipster,ziogiugno/generator-jhipster,Tcharl/generator-jhipster,sendilkumarn/generator-jhipster,mraible/generator-jhipster,ruddell/generator-jhipster,jkutner/generator-jhipster,dimeros/generator-jhipster,erikkemperman/generator-jhipster,wmarques/generator-jhipster,robertmilowski/generator-jhipster,ziogiugno/generator-jhipster,ctamisier/generator-jhipster,jkutner/generator-jhipster,sendilkumarn/generator-jhipster,ziogiugno/generator-jhipster,ctamisier/generator-jhipster,liseri/generator-jhipster,gmarziou/generator-jhipster,eosimosu/generator-jhipster,dimeros/generator-jhipster,pascalgrimaud/generator-jhipster,jkutner/generator-jhipster,cbornet/generator-jhipster,vivekmore/generator-jhipster,eosimosu/generator-jhipster,liseri/generator-jhipster,danielpetisme/generator-jhipster,duderoot/generator-jhipster,duderoot/generator-jhipster,mosoft521/generator-jhipster,hdurix/generator-jhipster,vivekmore/generator-jhipster,jhipster/generator-jhipster,mosoft521/generator-jhipster,cbornet/generator-jhipster,jkutner/generator-jhipster,pascalgrimaud/generator-jhipster,PierreBesson/generator-jhipster,atomfrede/generator-jhipster,rifatdover/generator-jhipster,wmarques/generator-jhipster,PierreBesson/generator-jhipster,sendilkumarn/generator-jhipster,ruddell/generator-jhipster | /**
* Copyright 2013-2018 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const _ = require('lodash');
const chalk = require('chalk');
const fs = require('fs');
const shelljs = require('shelljs');
const semver = require('semver');
const exec = require('child_process').exec;
const os = require('os');
const pluralize = require('pluralize');
const jhiCore = require('jhipster-core');
const packagejs = require('../package.json');
const jhipsterUtils = require('./utils');
const constants = require('./generator-constants');
const PrivateBase = require('./generator-base-private');
const JHIPSTER_CONFIG_DIR = '.jhipster';
const MODULES_HOOK_FILE = `${JHIPSTER_CONFIG_DIR}/modules/jhi-hooks.json`;
const GENERATOR_JHIPSTER = 'generator-jhipster';
const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
const CLIENT_WEBPACK_DIR = constants.CLIENT_WEBPACK_DIR;
const SERVER_MAIN_SRC_DIR = constants.SERVER_MAIN_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
/**
* This is the Generator base class.
* This provides all the public API methods exposed via the module system.
* The public API methods can be directly utilized as well using commonJS require.
*
* The method signatures in public API should not be changed without a major version change
*/
module.exports = class extends PrivateBase {
/**
* Get the JHipster configuration from the .yo-rc.json file.
*
* @param {string} namespace - namespace of the .yo-rc.json config file. By default: generator-jhipster
*/
getJhipsterAppConfig(namespace = 'generator-jhipster') {
const fromPath = '.yo-rc.json';
if (shelljs.test('-f', fromPath)) {
const fileData = this.fs.readJSON(fromPath);
if (fileData && fileData[namespace]) {
return fileData[namespace];
}
}
return false;
}
/**
* Add a new menu element, at the root of the menu.
*
* @param {string} routerName - The name of the Angular router that is added to the menu.
* @param {string} glyphiconName - The name of the Glyphicon (from Bootstrap) that will be displayed.
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addElementToMenu(routerName, glyphiconName, enableTranslation, clientFramework) {
let navbarPath;
try {
if (clientFramework === 'angularX') {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [`<li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
<a class="nav-link" routerLink="${routerName}" (click)="collapseNavbar()">
<i class="fa fa-${glyphiconName}"></i>
<span${enableTranslation ? ` jhiTranslate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>`
]
}, this);
} else {
// React
// TODO:
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + navbarPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add external resources to root file(index.html).
*
* @param {string} resources - Resources added to root file.
* @param {string} comment - comment to add before resources content.
*/
addExternalResourcesToRoot(resources, comment) {
const indexFilePath = `${CLIENT_MAIN_SRC_DIR}index.html`;
let resourcesBlock = '';
if (comment) {
resourcesBlock += `<!-- ${comment} -->\n`;
}
resourcesBlock += `${resources}\n`;
try {
jhipsterUtils.rewriteFile({
file: indexFilePath,
needle: 'jhipster-needle-add-resources-to-root',
splicable: [resourcesBlock]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + indexFilePath + chalk.yellow(' or missing required jhipster-needle. Resources are not added to JHipster app.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new menu element to the admin menu.
*
* @param {string} routerName - The name of the Angular router that is added to the admin menu.
* @param {string} glyphiconName - The name of the Glyphicon (from Bootstrap) that will be displayed.
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addElementToAdminMenu(routerName, glyphiconName, enableTranslation, clientFramework) {
let navbarAdminPath;
try {
if (clientFramework === 'angularX') {
navbarAdminPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: navbarAdminPath,
needle: 'jhipster-needle-add-element-to-admin-menu',
splicable: [`<li>
<a class="dropdown-item" routerLink="${routerName}" routerLinkActive="active" (click)="collapseNavbar()">
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span${enableTranslation ? ` jhiTranslate="global.menu.admin.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>`
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + navbarAdminPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + routerName} ${chalk.yellow('not added to admin menu.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new entity route path to webpacks config
*
* @param {string} microserviceName - The name of the microservice to put into the url
* @param {string} clientFramework - The name of the client framework
*/
addEntityToWebpack(microserviceName, clientFramework) {
const webpackDevPath = `${CLIENT_WEBPACK_DIR}/webpack.dev.js`;
jhipsterUtils.rewriteFile({
file: webpackDevPath,
needle: 'jhipster-needle-add-entity-to-webpack',
splicable: [`'/${microserviceName.toLowerCase()}',`]
}, this);
}
/**
* Add a new entity in the "entities" menu.
*
* @param {string} routerName - The name of the Angular router (which by default is the name of the entity).
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addEntityToMenu(routerName, enableTranslation, clientFramework, entityTranslationKeyMenu = _.camelCase(routerName)) {
let entityMenuPath;
try {
if (this.clientFramework === 'angularX') {
entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: entityMenuPath,
needle: 'jhipster-needle-add-entity-to-menu',
splicable: [
this.stripMargin(`|<li>
| <a class="dropdown-item" routerLink="${routerName}" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" (click)="collapseNavbar()">
| <i class="fa fa-fw fa-asterisk" aria-hidden="true"></i>
| <span${enableTranslation ? ` jhiTranslate="global.menu.entities.${entityTranslationKeyMenu}"` : ''}>${_.startCase(routerName)}</span>
| </a>
| </li>`)
]
}, this);
} else {
// React
entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/shared/layout/header/header.tsx`;
jhipsterUtils.rewriteFile({
file: entityMenuPath,
needle: 'jhipster-needle-add-entity-to-menu',
splicable: [
this.stripMargin(`|(
| <DropdownItem tag={Link} key="${routerName}" to="/${routerName}">
| <FaAsterisk />
| ${_.startCase(routerName)}
| </DropdownItem>
| ),`)
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + entityMenuPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new entity in the TS modules file.
*
* @param {string} entityInstance - Entity Instance
* @param {string} entityClass - Entity Class
* @param {string} entityAngularName - Entity Angular Name
* @param {string} entityFolderName - Entity Folder Name
* @param {string} entityFileName - Entity File Name
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addEntityToModule(entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName, enableTranslation, clientFramework, microServiceName) {
const entityModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/entity.module.ts`;
try {
if (clientFramework === 'angularX') {
const appName = this.getAngularXAppName();
let importName = `${appName}${entityAngularName}Module`;
if (microServiceName) {
importName = `${importName} as ${this.upperFirstCamelCase(microServiceName)}${entityAngularName}Module`;
}
let importStatement = `|import { ${importName} } from './${entityFolderName}/${entityFileName}.module';`;
if (importStatement.length > constants.LINE_LENGTH) {
importStatement =
`|// prettier-ignore
|import {
| ${importName}
|} from './${entityFolderName}/${entityFileName}.module';`;
}
jhipsterUtils.rewriteFile({
file: entityModulePath,
needle: 'jhipster-needle-add-entity-module-import',
splicable: [
this.stripMargin(importStatement)
]
}, this);
jhipsterUtils.rewriteFile({
file: entityModulePath,
needle: 'jhipster-needle-add-entity-module',
splicable: [
this.stripMargin(microServiceName ? `|${this.upperFirstCamelCase(microServiceName)}${entityAngularName}Module,` : `|${appName}${entityAngularName}Module,`)
]
}, this);
} else {
// React
const indexModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/index.tsx`;
jhipsterUtils.rewriteFile({
file: indexModulePath,
needle: 'jhipster-needle-add-route-import',
splicable: [
this.stripMargin(`|import ${entityAngularName} from './${entityFolderName}';`)
]
}, this);
jhipsterUtils.rewriteFile({
file: indexModulePath,
needle: 'jhipster-needle-add-route-path',
splicable: [
this.stripMargin(`|<Route path={'/${entityFileName}'} component={${entityAngularName}}/>`)
]
}, this);
const indexReducerPath = `${CLIENT_MAIN_SRC_DIR}app/shared/reducers/index.ts`;
jhipsterUtils.rewriteFile({
file: indexReducerPath,
needle: 'jhipster-needle-add-reducer-import',
splicable: [
this.stripMargin(`|import ${entityInstance} from 'app/entities/${entityFolderName}/${entityFileName}.reducer';`)
]
}, this);
jhipsterUtils.rewriteFile({
file: indexReducerPath,
needle: 'jhipster-needle-add-reducer-combine',
splicable: [
this.stripMargin(`${entityInstance},`)
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + entityModulePath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + entityInstance + entityClass + entityFolderName + entityFileName} ${chalk.yellow(`not added to ${entityModulePath}.\n`)}`);
this.debug('Error:', e);
}
}
/**
* Add a new admin in the TS modules file.
*
* @param {string} appName - Angular2 application name.
* @param {string} adminAngularName - The name of the new admin item.
* @param {string} adminFolderName - The name of the folder.
* @param {string} adminFileName - The name of the file.
* @param {boolean} enableTranslation - If translations are enabled or not.
* @param {string} clientFramework - The name of the client framework.
*/
addAdminToModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation, clientFramework) {
const adminModulePath = `${CLIENT_MAIN_SRC_DIR}app/admin/admin.module.ts`;
try {
let importStatement = `|import { ${appName}${adminAngularName}Module } from './${adminFolderName}/${adminFileName}.module';`;
if (importStatement.length > constants.LINE_LENGTH) {
importStatement =
`|import {
| ${appName}${adminAngularName}Module
|} from './${adminFolderName}/${adminFileName}.module';`;
}
jhipsterUtils.rewriteFile({
file: adminModulePath,
needle: 'jhipster-needle-add-admin-module-import',
splicable: [
this.stripMargin(importStatement)
]
}, this);
jhipsterUtils.rewriteFile({
file: adminModulePath,
needle: 'jhipster-needle-add-admin-module',
splicable: [
this.stripMargin(`|${appName}${adminAngularName}Module,`)
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + appName + chalk.yellow(' or missing required jhipster-needle. Reference to ') + adminAngularName + adminFolderName + adminFileName + enableTranslation + clientFramework} ${chalk.yellow(`not added to ${adminModulePath}.\n`)}`);
this.debug('Error:', e);
}
}
/**
* Add a new element in the "global.json" translations.
*
* @param {string} key - Key for the menu entry
* @param {string} value - Default translated value
* @param {string} language - The language to which this translation should be added
*/
addElementTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-menu-add-element',
splicable: [
`"${key}": "${_.startCase(value)}",`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + language + chalk.yellow(' not added as a new entity in the menu.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new element in the admin section of "global.json" translations.
*
* @param {string} key - Key for the menu entry
* @param {string} value - Default translated value
* @param {string} language - The language to which this translation should be added
*/
addAdminElementTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-menu-add-admin-element',
splicable: [
`"${key}": "${_.startCase(value)}",`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + language + chalk.yellow(' not added as a new entry in the admin menu.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new entity in the "global.json" translations.
*
* @param {string} key - Key for the entity name
* @param {string} value - Default translated value
* @param {string} language - The language to which this translation should be added
*/
addEntityTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-menu-add-entry',
splicable: [
`"${key}": "${_.startCase(value)}",`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + language + chalk.yellow(' not added as a new entity in the menu.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new entry as a root param in "global.json" translations.
*
* @param {string} key - Key for the entry
* @param {string} value - Default translated value or object with multiple key and translated value
* @param {string} language - The language to which this translation should be added
*/
addGlobalTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
jsonObj[key] = value;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}(key: ${key}, value:${value})${chalk.yellow(' not added to global translations.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a translation key to all installed languages
*
* @param {string} key - Key for the entity name
* @param {string} value - Default translated value
* @param {string} method - The method to be run with provided key and value from above
* @param {string} enableTranslation - specify if i18n is enabled
*/
addTranslationKeyToAllLanguages(key, value, method, enableTranslation) {
if (enableTranslation) {
this.getAllInstalledLanguages().forEach((language) => {
this[method](key, value, language);
});
}
}
/**
* get all the languages installed currently
*/
getAllInstalledLanguages() {
const languages = [];
this.getAllSupportedLanguages().forEach((language) => {
try {
const stats = fs.lstatSync(`${CLIENT_MAIN_SRC_DIR}i18n/${language}`);
if (stats.isDirectory()) {
languages.push(language);
}
} catch (e) {
this.debug('Error:', e);
// An exception is thrown if the folder doesn't exist
// do nothing as the language might not be installed
}
});
return languages;
}
/**
* get all the languages supported by JHipster
*/
getAllSupportedLanguages() {
return _.map(this.getAllSupportedLanguageOptions(), 'value');
}
/**
* check if a language is supported by JHipster
* @param {string} language - Key for the language
*/
isSupportedLanguage(language) {
return _.includes(this.getAllSupportedLanguages(), language);
}
/**
* check if Right-to-Left support is necesary for i18n
* @param {string[]} languages - languages array
*/
isI18nRTLSupportNecessary(languages) {
if (!languages) {
return false;
}
const rtlLanguages = this.getAllSupportedLanguageOptions().filter(langObj => langObj.rtl);
return languages.some(lang => !!rtlLanguages.find(langObj => langObj.value === lang));
}
/**
* return the localeId from the given language key (from constants.LANGUAGES)
* if no localeId is defined, return the language key (which is a localeId itself)
* @param {string} language - language key
*/
getLocaleId(language) {
const langObj = this.getAllSupportedLanguageOptions().find(langObj => langObj.value === language);
return langObj.localeId || language;
}
/**
* get all the languages options supported by JHipster
*/
getAllSupportedLanguageOptions() {
return constants.LANGUAGES;
}
/**
* Add a new dependency in the "bower.json".
*
* @param {string} name - dependency name
* @param {string} version - dependency version
*/
addBowerDependency(name, version) {
const fullPath = 'bower.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.dependencies === undefined) {
jsonObj.dependencies = {};
}
jsonObj.dependencies[name] = version;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}bower dependency (name: ${name}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new override configuration in the "bower.json".
*
* @param {string} bowerPackageName - Bower package name use in dependencies
* @param {array} main - You can specify which files should be selected
* @param {boolean} isIgnored - Default: false, Set to true if you want to ignore this package.
* @param {object} dependencies - You can override the dependencies of a package. Set to null to ignore the dependencies.
*
*/
addBowerOverride(bowerPackageName, main, isIgnored, dependencies) {
const fullPath = 'bower.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
const override = {};
if (main !== undefined && main.length > 0) {
override.main = main;
}
if (isIgnored) {
override.ignore = true;
}
if (dependencies) {
override.dependencies = dependencies;
}
if (jsonObj.overrides === undefined) {
jsonObj.overrides = {};
}
jsonObj.overrides[bowerPackageName] = override;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}bower override configuration (bowerPackageName: ${bowerPackageName}, main:${JSON.stringify(main)}, ignore:${isIgnored})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new parameter in the ".bowerrc".
*
* @param {string} key - name of the parameter
* @param {string | boolean | any} value - value of the parameter
*/
addBowerrcParameter(key, value) {
const fullPath = '.bowerrc';
try {
this.log(chalk.yellow(' update ') + fullPath);
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
jsonObj[key] = value;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}bowerrc parameter (key: ${key}, value:${value})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new dependency in the "package.json".
*
* @param {string} name - dependency name
* @param {string} version - dependency version
*/
addNpmDependency(name, version) {
const fullPath = 'package.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.dependencies === undefined) {
jsonObj.dependencies = {};
}
jsonObj.dependencies[name] = version;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}npm dependency (name: ${name}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new devDependency in the "package.json".
*
* @param {string} name - devDependency name
* @param {string} version - devDependency version
*/
addNpmDevDependency(name, version) {
const fullPath = 'package.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.devDependencies === undefined) {
jsonObj.devDependencies = {};
}
jsonObj.devDependencies[name] = version;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}npm devDependency (name: ${name}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new script in the "package.json".
*
* @param {string} name - script name
* @param {string} data - script version
*/
addNpmScript(name, data) {
const fullPath = 'package.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.scripts === undefined) {
jsonObj.scripts = {};
}
jsonObj.scripts[name] = data;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}npm script (name: ${name}, data:${data})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new module in the TS modules file.
*
* @param {string} appName - Angular2 application name.
* @param {string} angularName - The name of the new admin item.
* @param {string} folderName - The name of the folder.
* @param {string} fileName - The name of the file.
* @param {boolean} enableTranslation - If translations are enabled or not.
* @param {string} clientFramework - The name of the client framework.
*/
addAngularModule(appName, angularName, folderName, fileName, enableTranslation, clientFramework) {
const modulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
try {
let importStatement = `|import { ${appName}${angularName}Module } from './${folderName}/${fileName}.module';`;
if (importStatement.length > constants.LINE_LENGTH) {
importStatement =
`|import {
| ${appName}${angularName}Module
|} from './${folderName}/${fileName}.module';`;
}
jhipsterUtils.rewriteFile({
file: modulePath,
needle: 'jhipster-needle-angular-add-module-import',
splicable: [
this.stripMargin(importStatement)
]
}, this);
jhipsterUtils.rewriteFile({
file: modulePath,
needle: 'jhipster-needle-angular-add-module',
splicable: [
this.stripMargin(`|${appName}${angularName}Module,`)
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + appName + chalk.yellow(' or missing required jhipster-needle. Reference to ') + angularName + folderName + fileName + enableTranslation + clientFramework} ${chalk.yellow(`not added to ${modulePath}.\n`)}`);
this.debug('Error:', e);
}
}
/**
* Add a new http interceptor to the angular application in "blocks/config/http.config.js".
* The interceptor should be in its own .js file inside app/blocks/interceptor folder
* @param {string} interceptorName - angular name of the interceptor
*
*/
addAngularJsInterceptor(interceptorName) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}app/blocks/config/http.config.js`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-angularjs-add-interceptor',
splicable: [
`$httpProvider.interceptors.push('${interceptorName}');`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Interceptor not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new entity to Ehcache, for the 2nd level cache of an entity and its relationships.
*
* @param {string} entityClass - the entity to cache
* @param {array} relationships - the relationships of this entity
* @param {string} packageName - the Java package name
* @param {string} packageFolder - the Java package folder
*/
addEntityToEhcache(entityClass, relationships, packageName, packageFolder) {
this.addEntityToCache(entityClass, relationships, packageName, packageFolder, 'ehcache');
}
/**
* Add a new entry to Ehcache in CacheConfiguration.java
*
* @param {string} entry - the entry (including package name) to cache
* @param {string} packageFolder - the Java package folder
*/
addEntryToEhcache(entry, packageFolder) {
this.addEntryToCache(entry, packageFolder, 'ehcache');
}
/**
* Add a new entity to the chosen cache provider, for the 2nd level cache of an entity and its relationships.
*
* @param {string} entityClass - the entity to cache
* @param {array} relationships - the relationships of this entity
* @param {string} packageName - the Java package name
* @param {string} packageFolder - the Java package folder
* @param {string} cacheProvider - the cache provider
*/
addEntityToCache(entityClass, relationships, packageName, packageFolder, cacheProvider) {
// Add the entity to ehcache
this.addEntryToCache(`${packageName}.domain.${entityClass}.class.getName()`, packageFolder, cacheProvider);
// Add the collections linked to that entity to ehcache
relationships.forEach((relationship) => {
const relationshipType = relationship.relationshipType;
if (relationshipType === 'one-to-many' || relationshipType === 'many-to-many') {
this.addEntryToCache(`${packageName}.domain.${entityClass}.class.getName() + ".${relationship.relationshipFieldNamePlural}"`, packageFolder, cacheProvider);
}
});
}
/**
* Add a new entry to the chosen cache provider in CacheConfiguration.java
*
* @param {string} entry - the entry (including package name) to cache
* @param {string} packageFolder - the Java package folder
* @param {string} cacheProvider - the cache provider
*/
addEntryToCache(entry, packageFolder, cacheProvider) {
try {
const cachePath = `${SERVER_MAIN_SRC_DIR}${packageFolder}/config/CacheConfiguration.java`;
if (cacheProvider === 'ehcache') {
jhipsterUtils.rewriteFile({
file: cachePath,
needle: 'jhipster-needle-ehcache-add-entry',
splicable: [`cm.createCache(${entry}, jcacheConfiguration);`
]
}, this);
} else if (cacheProvider === 'infinispan') {
jhipsterUtils.rewriteFile({
file: cachePath,
needle: 'jhipster-needle-infinispan-add-entry',
splicable: [`registerPredefinedCache(${entry}, new JCache<Object, Object>(
cacheManager.getCache(${entry}).getAdvancedCache(), this,
ConfigurationAdapter.create()));`
]
}, this);
}
} catch (e) {
this.log(chalk.yellow(`\nUnable to add ${entry} to CacheConfiguration.java file.\n\t${e.message}`));
this.debug('Error:', e);
}
}
/**
* Add a new changelog to the Liquibase master.xml file.
*
* @param {string} changelogName - The name of the changelog (name of the file without .xml at the end).
*/
addChangelogToLiquibase(changelogName) {
this.addLiquibaseChangelogToMaster(changelogName, 'jhipster-needle-liquibase-add-changelog');
}
/**
* Add a new constraints changelog to the Liquibase master.xml file.
*
* @param {string} changelogName - The name of the changelog (name of the file without .xml at the end).
*/
addConstraintsChangelogToLiquibase(changelogName) {
this.addLiquibaseChangelogToMaster(changelogName, 'jhipster-needle-liquibase-add-constraints-changelog');
}
/**
* Add a new changelog to the Liquibase master.xml file.
*
* @param {string} changelogName - The name of the changelog (name of the file without .xml at the end).
* @param {string} needle - The needle at where it has to be added.
*/
addLiquibaseChangelogToMaster(changelogName, needle) {
const fullPath = `${SERVER_MAIN_RES_DIR}config/liquibase/master.xml`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle,
splicable: [
`<include file="config/liquibase/changelog/${changelogName}.xml" relativeToChangelogFile="false"/>`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + changelogName}.xml ${chalk.yellow('not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new column to a Liquibase changelog file for entity.
*
* @param {string} filePath - The full path of the changelog file.
* @param {string} content - The content to be added as column, can have multiple columns as well
*/
addColumnToLiquibaseEntityChangeset(filePath, content) {
try {
jhipsterUtils.rewriteFile({
file: filePath,
needle: 'jhipster-needle-liquibase-add-column',
splicable: [
content
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required jhipster-needle. Column not added.\n') + e);
this.debug('Error:', e);
}
}
/**
* Add a new changeset to a Liquibase changelog file for entity.
*
* @param {string} filePath - The full path of the changelog file.
* @param {string} content - The content to be added as changeset
*/
addChangesetToLiquibaseEntityChangelog(filePath, content) {
try {
jhipsterUtils.rewriteFile({
file: filePath,
needle: 'jhipster-needle-liquibase-add-changeset',
splicable: [
content
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required jhipster-needle. Changeset not added.\n') + e);
this.debug('Error:', e);
}
}
/**
* Add new css style to the angular application in "main.css".
*
* @param {boolean} isUseSass - flag indicating if sass should be used
* @param {string} style - css to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.jhipster {\n color: #baa186;\n}'
* comment = 'New JHipster color'
*
* * ==========================================================================
* New JHipster color
* ========================================================================== *
* .jhipster {
* color: #baa186;
* }
*
*/
addMainCSSStyle(isUseSass, style, comment) {
if (isUseSass) {
this.addMainSCSSStyle(style, comment);
}
const fullPath = `${CLIENT_MAIN_SRC_DIR}content/css/main.css`;
let styleBlock = '';
if (comment) {
styleBlock += '/* ==========================================================================\n';
styleBlock += `${comment}\n`;
styleBlock += '========================================================================== */\n';
}
styleBlock += `${style}\n`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-css-add-main',
splicable: [
styleBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Style not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add new scss style to the angular application in "main.scss".
*
* @param {string} style - scss to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.success {\n @extend .message;\n border-color: green;\n}'
* comment = 'Message'
*
* * ==========================================================================
* Message
* ========================================================================== *
* .success {
* @extend .message;
* border-color: green;
* }
*
*/
addMainSCSSStyle(style, comment) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}scss/main.scss`;
let styleBlock = '';
if (comment) {
styleBlock += '/* ==========================================================================\n';
styleBlock += `${comment}\n`;
styleBlock += '========================================================================== */\n';
}
styleBlock += `${style}\n`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-scss-add-main',
splicable: [
styleBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Style not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add new scss style to the angular application in "vendor.scss".
*
* @param {string} style - scss to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.success {\n @extend .message;\n border-color: green;\n}'
* comment = 'Message'
*
* * ==========================================================================
* Message
* ========================================================================== *
* .success {
* @extend .message;
* border-color: green;
* }
*
*/
addVendorSCSSStyle(style, comment) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}content/scss/vendor.scss`;
let styleBlock = '';
if (comment) {
styleBlock += '/* ==========================================================================\n';
styleBlock += `${comment}\n`;
styleBlock += '========================================================================== */\n';
}
styleBlock += `${style}\n`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-scss-add-vendor',
splicable: [
styleBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Style not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Copy third-party library resources path.
*
* @param {string} sourceFolder - third-party library resources source path
* @param {string} targetFolder - third-party library resources destination path
*/
copyExternalAssetsInWebpack(sourceFolder, targetFolder) {
const from = `${CLIENT_MAIN_SRC_DIR}content/${sourceFolder}/`;
const to = `content/${targetFolder}/`;
const webpackDevPath = `${CLIENT_WEBPACK_DIR}/webpack.common.js`;
let assetBlock = '';
if (sourceFolder && targetFolder) {
assetBlock = `{ from: './${from}', to: '${to}' },`;
}
try {
jhipsterUtils.rewriteFile({
file: webpackDevPath,
needle: 'jhipster-needle-add-assets-to-webpack',
splicable: [
assetBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + webpackDevPath + chalk.yellow(' or missing required jhipster-needle. Resource path not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add a Maven dependency Management.
*
* @param {string} groupId - dependency groupId
* @param {string} artifactId - dependency artifactId
* @param {string} version - (optional) explicit dependency version number
* @param {string} type - (optional) explicit type
* @param {string} scope - (optional) explicit scope
* @param {string} other - (optional) explicit other thing: exclusions...
*/
addMavenDependencyManagement(groupId, artifactId, version, type, scope, other) {
const fullPath = 'pom.xml';
try {
let dependency = `${'<dependency>\n' +
' <groupId>'}${groupId}</groupId>\n` +
` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
dependency += ` <version>${version}</version>\n`;
}
if (type) {
dependency += ` <type>${type}</type>\n`;
}
if (scope) {
dependency += ` <scope>${version}</scope>\n`;
}
if (other) {
dependency += `${other}\n`;
}
dependency += ' </dependency>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-add-dependency-management',
splicable: [
dependency
]
}, this);
} catch (e) {
this.log(e);
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven dependency (groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a remote Maven Repository to the Maven build.
*
* @param {string} id - id of the repository
* @param {string} url - url of the repository
*/
addMavenRepository(id, url) {
const fullPath = 'pom.xml';
try {
const repository = `${'<repository>\n' +
' <id>'}${id}</id>\n` +
` <url>${url}</url>\n` +
' </repository>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-repository',
splicable: [
repository
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven repository (id: ${id}, url:${url})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven property.
*
* @param {string} name - property name
* @param {string} value - property value
*/
addMavenProperty(name, value) {
const fullPath = 'pom.xml';
try {
const property = `<${name}>${value}</${name}>`;
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-property',
splicable: [
property
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven property (name: ${name}, value:${value})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven dependency.
*
* @param {string} groupId - dependency groupId
* @param {string} artifactId - dependency artifactId
* @param {string} version - (optional) explicit dependency version number
* @param {string} other - (optional) explicit other thing: scope, exclusions...
*/
addMavenDependency(groupId, artifactId, version, other) {
this.addMavenDependencyInDirectory('.', groupId, artifactId, version, other);
}
/**
* Add a new Maven dependency in a specific folder..
*
* @param {string} directory - the folder to add the dependency in
* @param {string} groupId - dependency groupId
* @param {string} artifactId - dependency artifactId
* @param {string} version - (optional) explicit dependency version number
* @param {string} other - (optional) explicit other thing: scope, exclusions...
*/
addMavenDependencyInDirectory(directory, groupId, artifactId, version, other) {
try {
let dependency = `${'<dependency>\n' +
' <groupId>'}${groupId}</groupId>\n` +
` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
dependency += ` <version>${version}</version>\n`;
}
if (other) {
dependency += `${other}\n`;
}
dependency += ' </dependency>';
jhipsterUtils.rewriteFile({
path: directory,
file: 'pom.xml',
needle: 'jhipster-needle-maven-add-dependency',
splicable: [
dependency
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + directory + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven dependency (groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven plugin.
*
* @param {string} groupId - plugin groupId
* @param {string} artifactId - plugin artifactId
* @param {string} version - explicit plugin version number
* @param {string} other - explicit other thing: executions, configuration...
*/
addMavenPlugin(groupId, artifactId, version, other) {
const fullPath = 'pom.xml';
try {
let plugin = `${'<plugin>\n' +
' <groupId>'}${groupId}</groupId>\n` +
` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
plugin += ` <version>${version}</version>\n`;
}
if (other) {
plugin += `${other}\n`;
}
plugin += ' </plugin>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-add-plugin',
splicable: [
plugin
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven plugin (groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven profile.
*
* @param {string} profileId - profile ID
* @param {string} other - explicit other thing: build, dependencies...
*/
addMavenProfile(profileId, other) {
const fullPath = 'pom.xml';
try {
let profile = '<profile>\n' +
` <id>${profileId}</id>\n`;
if (other) {
profile += `${other}\n`;
}
profile += ' </profile>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-add-profile',
splicable: [
profile
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven profile (id: ${profileId})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* A new Gradle plugin.
*
* @param {string} group - plugin GroupId
* @param {string} name - plugin name
* @param {string} version - explicit plugin version number
*/
addGradlePlugin(group, name, version) {
const fullPath = 'build.gradle';
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-buildscript-dependency',
splicable: [
`classpath '${group}:${name}:${version}'`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}classpath: ${group}:${name}:${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add Gradle plugin to the plugins block
*
* @param {string} id - plugin id
* @param {string} version - explicit plugin version number
*/
addGradlePluginToPluginsBlock(id, version) {
const fullPath = 'build.gradle';
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-plugins',
splicable: [
`id "${id}" version "${version}"`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}id ${id} version ${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* A new dependency to build.gradle file.
*
* @param {string} scope - scope of the new dependency, e.g. compile
* @param {string} group - maven GroupId
* @param {string} name - maven ArtifactId
* @param {string} version - (optional) explicit dependency version number
*/
addGradleDependencyManagement(scope, group, name, version) {
const fullPath = 'build.gradle';
let dependency = `${group}:${name}`;
if (version) {
dependency += `:${version}`;
}
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-dependency-management',
splicable: [
`${scope} "${dependency}"`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + group}:${name}:${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* A new dependency to build.gradle file.
*
* @param {string} scope - scope of the new dependency, e.g. compile
* @param {string} group - maven GroupId
* @param {string} name - maven ArtifactId
* @param {string} version - (optional) explicit dependency version number
*/
addGradleDependency(scope, group, name, version) {
this.addGradleDependencyInDirectory('.', scope, group, name, version);
}
/**
* A new dependency to build.gradle file in a specific folder.
*
* @param {string} scope - scope of the new dependency, e.g. compile
* @param {string} group - maven GroupId
* @param {string} name - maven ArtifactId
* @param {string} version - (optional) explicit dependency version number
*/
addGradleDependencyInDirectory(directory, scope, group, name, version) {
let dependency = `${group}:${name}`;
if (version) {
dependency += `:${version}`;
}
try {
jhipsterUtils.rewriteFile({
path: directory,
file: 'build.gradle',
needle: 'jhipster-needle-gradle-dependency',
splicable: [
`${scope} "${dependency}"`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + directory + chalk.yellow(' or missing required jhipster-needle. Reference to ') + group}:${name}:${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Apply from an external Gradle build script.
*
* @param {string} name - name of the file to apply from, must be 'fileName.gradle'
*/
applyFromGradleScript(name) {
const fullPath = 'build.gradle';
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-apply-from',
splicable: [
`apply from: '${name}.gradle'`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + name + chalk.yellow(' not added.\n'));
this.debug('Error:', e);
}
}
/**
* Add a remote Maven Repository to the Gradle build.
*
* @param {string} url - url of the repository
* @param {string} username - (optional) username of the repository credentials
* @param {string} password - (optional) password of the repository credentials
*/
addGradleMavenRepository(url, username, password) {
const fullPath = 'build.gradle';
try {
let repository = 'maven {\n';
if (url) {
repository += ` url "${url}"\n`;
}
if (username || password) {
repository += ' credentials {\n';
if (username) {
repository += ` username = "${username}"\n`;
}
if (password) {
repository += ` password = "${password}"\n`;
}
repository += ' }\n';
}
repository += ' }';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-repositories',
splicable: [
repository
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + url + chalk.yellow(' not added.\n'));
this.debug('Error:', e);
}
}
/**
* Generate a date to be used by Liquibase changelogs.
*/
dateFormatForLiquibase() {
const now = new Date();
const nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
const year = `${nowUTC.getFullYear()}`;
let month = `${nowUTC.getMonth() + 1}`;
if (month.length === 1) {
month = `0${month}`;
}
let day = `${nowUTC.getDate()}`;
if (day.length === 1) {
day = `0${day}`;
}
let hour = `${nowUTC.getHours()}`;
if (hour.length === 1) {
hour = `0${hour}`;
}
let minute = `${nowUTC.getMinutes()}`;
if (minute.length === 1) {
minute = `0${minute}`;
}
let second = `${nowUTC.getSeconds()}`;
if (second.length === 1) {
second = `0${second}`;
}
return `${year}${month}${day}${hour}${minute}${second}`;
}
/**
* Copy templates with all the custom logic applied according to the type.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {string} action - type of the action to be performed on the template file, i.e: stripHtml | stripJs | template | copy
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy method
*/
copyTemplate(source, dest, action, generator, opt = {}, template) {
const _this = generator || this;
let regex;
switch (action) {
case 'stripHtml':
regex = new RegExp([
/( (data-t|jhiT)ranslate="([a-zA-Z0-9 +{}'_](\.)?)+")/, // data-translate or jhiTranslate
/( translate(-v|V)alues="\{([a-zA-Z]|\d|:|\{|\}|\[|\]|-|'|\s|\.|_)*?\}")/, // translate-values or translateValues
/( translate-compile)/, // translate-compile
/( translate-value-max="[0-9{}()|]*")/, // translate-value-max
].map(r => r.source).join('|'), 'g');
jhipsterUtils.copyWebResource(source, dest, regex, 'html', _this, opt, template);
break;
case 'stripJs':
regex = new RegExp([
/(,[\s]*(resolve):[\s]*[{][\s]*(translatePartialLoader)['a-zA-Z0-9$,(){.<%=\->;\s:[\]]*(;[\s]*\}\][\s]*\}))/, // ng1 resolve block
/([\s]import\s\{\s?JhiLanguageService\s?\}\sfrom\s["|']ng-jhipster["|'];)/, // ng2 import jhiLanguageService
/(,?\s?JhiLanguageService,?\s?)/, // ng2 import jhiLanguageService
/(private\s[a-zA-Z0-9]*(L|l)anguageService\s?:\s?JhiLanguageService\s?,*[\s]*)/, // ng2 jhiLanguageService constructor argument
/(this\.[a-zA-Z0-9]*(L|l)anguageService\.setLocations\(\[['"a-zA-Z0-9\-_,\s]+\]\);[\s]*)/, // jhiLanguageService invocations
].map(r => r.source).join('|'), 'g');
jhipsterUtils.copyWebResource(source, dest, regex, 'js', _this, opt, template);
break;
case 'copy':
_this.copy(source, dest);
break;
default:
_this.template(source, dest, _this, opt);
}
}
/**
* Copy html templates after stripping translation keys when translation is disabled.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy
*/
processHtml(source, dest, generator, opt, template) {
this.copyTemplate(source, dest, 'stripHtml', generator, opt, template);
}
/**
* Copy Js templates after stripping translation keys when translation is disabled.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy
*/
processJs(source, dest, generator, opt, template) {
this.copyTemplate(source, dest, 'stripJs', generator, opt, template);
}
/**
* Copy JSX templates after stripping translation keys when translation is disabled.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy
*/
processJsx(source, dest, generator, opt, template) {
this.copyTemplate(source, dest, 'stripJs', generator, opt, template);
}
/**
* Rewrite the specified file with provided content at the needle location
*
* @param {string} filePath - path of the source file to rewrite
* @param {string} needle - needle to look for where content will be inserted
* @param {string} content - content to be written
*/
rewriteFile(filePath, needle, content) {
try {
jhipsterUtils.rewriteFile({
file: filePath,
needle,
splicable: [
content
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required needle. File rewrite failed.\n'));
this.debug('Error:', e);
}
}
/**
* Replace the pattern/regex with provided content
*
* @param {string} filePath - path of the source file to rewrite
* @param {string} pattern - pattern to look for where content will be replaced
* @param {string} content - content to be written
* @param {string} regex - true if pattern is regex
*/
replaceContent(filePath, pattern, content, regex) {
try {
jhipsterUtils.replaceContent({
file: filePath,
pattern,
content,
regex
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required pattern. File rewrite failed.\n') + e);
this.debug('Error:', e);
}
}
/**
* Register a module configuration to .jhipster/modules/jhi-hooks.json
*
* @param {string} npmPackageName - npm package name of the generator
* @param {string} hookFor - from which JHipster generator this should be hooked ( 'entity' or 'app')
* @param {string} hookType - where to hook this at the generator stage ( 'pre' or 'post')
* @param {string} callbackSubGenerator[optional] - sub generator to invoke, if this is not given the module's main generator will be called, i.e app
* @param {string} description[optional] - description of the generator
*/
registerModule(npmPackageName, hookFor, hookType, callbackSubGenerator, description) {
try {
let modules;
let error;
let duplicate;
const moduleName = _.startCase(npmPackageName.replace(`${GENERATOR_JHIPSTER}-`, ''));
const generatorName = npmPackageName.replace('generator-', '');
const generatorCallback = `${generatorName}:${callbackSubGenerator || 'app'}`;
const moduleConfig = {
name: `${moduleName} generator`,
npmPackageName,
description: description || `A JHipster module to generate ${moduleName}`,
hookFor,
hookType,
generatorCallback
};
try {
// if file is not present, we got an empty list, no exception
modules = this.fs.readJSON(MODULES_HOOK_FILE, []);
duplicate = _.findIndex(modules, moduleConfig) !== -1;
} catch (err) {
error = true;
this.log(chalk.red('The JHipster module configuration file could not be read!'));
this.debug('Error:', err);
}
if (!error && !duplicate) {
modules.push(moduleConfig);
this.fs.writeJSON(MODULES_HOOK_FILE, modules, null, 4);
}
} catch (err) {
this.log(`\n${chalk.bold.red('Could not add jhipster module configuration')}`);
this.debug('Error:', err);
}
}
/**
* Add configuration to Entity.json files
*
* @param {string} file - configuration file name for the entity
* @param {string} key - key to be added or updated
* @param {object} value - value to be added
*/
updateEntityConfig(file, key, value) {
try {
const entityJson = this.fs.readJSON(file);
entityJson[key] = value;
this.fs.writeJSON(file, entityJson, null, 4);
} catch (err) {
this.log(chalk.red('The JHipster entity configuration file could not be read!') + err);
this.debug('Error:', err);
}
}
/**
* get the module hooks config json
*/
getModuleHooks() {
let modulesConfig = [];
try {
if (shelljs.test('-f', MODULES_HOOK_FILE)) {
modulesConfig = this.fs.readJSON(MODULES_HOOK_FILE);
}
} catch (err) {
this.log(chalk.red('The module configuration file could not be read!'));
}
return modulesConfig;
}
/**
* Call all the module hooks with the given options.
* @param {string} hookFor - "app" or "entity"
* @param {string} hookType - "pre" or "post"
* @param {any} options - the options to pass to the hooks
* @param {function} cb - callback to trigger at the end
*/
callHooks(hookFor, hookType, options, cb) {
const modules = this.getModuleHooks();
// run through all module hooks, which matches the hookFor and hookType
modules.forEach((module) => {
this.debug('Composing module with config:', module);
if (module.hookFor === hookFor && module.hookType === hookType) {
// compose with the modules callback generator
const hook = module.generatorCallback.split(':')[1];
try {
this.composeExternalModule(module.npmPackageName, hook || 'app', options);
} catch (e) {
this.log(chalk.red('Could not compose module ') + chalk.bold.yellow(module.npmPackageName) +
chalk.red('. \nMake sure you have installed the module with ') + chalk.bold.yellow(`'npm install -g ${module.npmPackageName}'`));
this.debug('ERROR:', e);
}
}
});
this.debug('calling callback');
cb && cb();
}
/**
* Compose an external generator with Yeoman.
* @param {string} npmPackageName - package name
* @param {string} subGen - sub generator name
* @param {any} options - options to pass
*/
composeExternalModule(npmPackageName, subGen, options) {
let generatorTocall = path.join(process.cwd(), 'node_modules', npmPackageName, 'generators', subGen);
try {
if (!fs.existsSync(generatorTocall)) {
this.debug('using global module as local version could not be found in node_modules');
generatorTocall = path.join(npmPackageName, 'generators', subGen);
}
this.debug('Running yeoman compose with options: ', generatorTocall, options);
this.composeWith(require.resolve(generatorTocall), options);
} catch (err) {
this.debug('ERROR:', err);
const generatorName = npmPackageName.replace('generator-', '');
const generatorCallback = `${generatorName}:${subGen}`;
// Fallback for legacy modules
this.debug('Running yeoman legacy compose with options: ', generatorCallback, options);
this.composeWith(generatorCallback, options);
}
}
/**
* Get a name suitable for microservice
* @param {string} microserviceName
*/
getMicroserviceAppName(microserviceName) {
return _.camelCase(microserviceName) + (microserviceName.endsWith('App') ? '' : 'App');
}
/**
* Load an entity configuration file into context.
*/
loadEntityJson(fromPath = this.context.fromPath) {
const context = this.context;
try {
context.fileData = this.fs.readJSON(fromPath);
} catch (err) {
this.debug('Error:', err);
this.error(chalk.red('\nThe entity configuration file could not be read!\n'));
}
context.relationships = context.fileData.relationships || [];
context.fields = context.fileData.fields || [];
context.haveFieldWithJavadoc = false;
context.fields.forEach((field) => {
if (field.javadoc) {
context.haveFieldWithJavadoc = true;
}
});
context.changelogDate = context.fileData.changelogDate;
context.dto = context.fileData.dto;
context.service = context.fileData.service;
context.fluentMethods = context.fileData.fluentMethods;
context.clientRootFolder = context.fileData.clientRootFolder;
context.pagination = context.fileData.pagination;
context.searchEngine = context.fileData.searchEngine || context.searchEngine;
context.javadoc = context.fileData.javadoc;
context.entityTableName = context.fileData.entityTableName;
context.jhiPrefix = context.fileData.jhiPrefix || context.jhiPrefix;
context.skipCheckLengthOfIdentifier = context.fileData.skipCheckLengthOfIdentifier || context.skipCheckLengthOfIdentifier;
context.jhiTablePrefix = this.getTableName(context.jhiPrefix);
this.copyFilteringFlag(context.fileData, context, context);
if (_.isUndefined(context.entityTableName)) {
this.warning(`entityTableName is missing in .jhipster/${context.name}.json, using entity name as fallback`);
context.entityTableName = this.getTableName(context.name);
}
if (jhiCore.isReservedTableName(context.entityTableName, context.prodDatabaseType)) {
context.entityTableName = `${context.jhiTablePrefix}_${context.entityTableName}`;
}
context.fields.forEach((field) => {
context.fieldNamesUnderscored.push(_.snakeCase(field.fieldName));
context.fieldNameChoices.push({ name: field.fieldName, value: field.fieldName });
});
context.relationships.forEach((rel) => {
context.relNameChoices.push({ name: `${rel.relationshipName}:${rel.relationshipType}`, value: `${rel.relationshipName}:${rel.relationshipType}` });
});
if (context.fileData.angularJSSuffix !== undefined) {
context.entityAngularJSSuffix = context.fileData.angularJSSuffix;
}
context.useMicroserviceJson = context.useMicroserviceJson || !_.isUndefined(context.fileData.microserviceName);
if (context.applicationType === 'gateway' && context.useMicroserviceJson) {
context.microserviceName = context.fileData.microserviceName;
if (!context.microserviceName) {
this.error(chalk.red('Microservice name for the entity is not found. Entity cannot be generated!'));
}
context.microserviceAppName = this.getMicroserviceAppName(context.microserviceName);
context.skipServer = true;
}
}
/**
* get an entity from the configuration file
* @param {string} file - configuration file name for the entity
*/
getEntityJson(file) {
let entityJson = null;
try {
if (this.context.microservicePath) {
entityJson = this.fs.readJSON(path.join(this.context.microservicePath, JHIPSTER_CONFIG_DIR, `${_.upperFirst(file)}.json`));
} else {
entityJson = this.fs.readJSON(path.join(JHIPSTER_CONFIG_DIR, `${_.upperFirst(file)}.json`));
}
} catch (err) {
this.log(chalk.red(`The JHipster entity configuration file could not be read for file ${file}!`) + err);
this.debug('Error:', err);
}
return entityJson;
}
/**
* get sorted list of entities according to changelog date (i.e. the order in which they were added)
*/
getExistingEntities() {
const entities = [];
function isBefore(e1, e2) {
return e1.definition.changelogDate - e2.definition.changelogDate;
}
if (!shelljs.test('-d', JHIPSTER_CONFIG_DIR)) {
return entities;
}
return shelljs.ls(path.join(JHIPSTER_CONFIG_DIR, '*.json')).reduce((acc, file) => {
try {
const definition = jhiCore.readEntityJSON(file);
acc.push({ name: path.basename(file, '.json'), definition });
} catch (error) {
// not an entity file / malformed?
this.warning(`Unable to parse entity file ${file}`);
this.debug('Error:', error);
}
return acc;
}, entities).sort(isBefore);
}
/**
* Copy i18 files for given language
*
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {string} webappDir - webapp directory path
* @param {string} fileToCopy - file name to copy
* @param {string} lang - language for which file needs to be copied
*/
copyI18nFilesByName(generator, webappDir, fileToCopy, lang) {
const _this = generator || this;
_this.copy(`${webappDir}i18n/${lang}/${fileToCopy}`, `${webappDir}i18n/${lang}/${fileToCopy}`);
}
/**
* Check if the JHipster version used to generate an existing project is less than the passed version argument
*
* @param {string} version - A valid semver version string
*/
isJhipsterVersionLessThan(version) {
const jhipsterVersion = this.config.get('jhipsterVersion');
if (!jhipsterVersion) {
return true;
}
return semver.lt(jhipsterVersion, version);
}
/**
* executes a Git command using shellJS
* gitExec(args [, options ], callback)
*
* @param {string|array} args - can be an array of arguments or a string command
* @param {object} options[optional] - takes any of child process options
* @param {function} callback - a callback function to be called once process complete, The call back will receive code, stdout and stderr
*/
gitExec(args, options, callback) {
callback = arguments[arguments.length - 1]; // eslint-disable-line prefer-rest-params
if (arguments.length < 3) {
options = {};
}
if (options.async === undefined) options.async = true;
if (options.silent === undefined) options.silent = true;
if (options.trace === undefined) options.trace = true;
if (!Array.isArray(args)) {
args = [args];
}
const command = `git ${args.join(' ')}`;
if (options.trace) {
this.info(command);
}
shelljs.exec(command, options, callback);
}
/**
* get a table name in JHipster preferred style.
*
* @param {string} value - table name string
*/
getTableName(value) {
return this.hibernateSnakeCase(value);
}
/**
* get a table column name in JHipster preferred style.
*
* @param {string} value - table column name string
*/
getColumnName(value) {
return this.hibernateSnakeCase(value);
}
/**
* get a table column names plural form in JHipster preferred style.
*
* @param {string} value - table column name string
*/
getPluralColumnName(value) {
return this.getColumnName(pluralize(value));
}
/**
* get a table name for joined tables in JHipster preferred style.
*
* @param {string} entityName - name of the entity
* @param {string} relationshipName - name of the related entity
* @param {string} prodDatabaseType - database type
*/
getJoinTableName(entityName, relationshipName, prodDatabaseType) {
const joinTableName = `${this.getTableName(entityName)}_${this.getTableName(relationshipName)}`;
let limit = 0;
if (prodDatabaseType === 'oracle' && joinTableName.length > 30 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated join table "${joinTableName}" is too long for Oracle (which has a 30 characters limit). It will be truncated!`);
limit = 30;
} else if (prodDatabaseType === 'mysql' && joinTableName.length > 64 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated join table "${joinTableName}" is too long for MySQL (which has a 64 characters limit). It will be truncated!`);
limit = 64;
}
if (limit > 0) {
const halfLimit = Math.floor(limit / 2);
const entityTable = _.snakeCase(this.getTableName(entityName).substring(0, halfLimit));
const relationTable = _.snakeCase(this.getTableName(relationshipName).substring(0, halfLimit - 1));
return `${entityTable}_${relationTable}`;
}
return joinTableName;
}
/**
* get a constraint name for tables in JHipster preferred style.
*
* @param {string} entityName - name of the entity
* @param {string} relationshipName - name of the related entity
* @param {string} prodDatabaseType - database type
* @param {boolean} noSnakeCase - do not convert names to snakecase
*/
getConstraintName(entityName, relationshipName, prodDatabaseType, noSnakeCase) {
let constraintName;
if (noSnakeCase) {
constraintName = `fk_${entityName}_${relationshipName}_id`;
} else {
constraintName = `fk_${this.getTableName(entityName)}_${this.getTableName(relationshipName)}_id`;
}
let limit = 0;
if (prodDatabaseType === 'oracle' && constraintName.length > 30 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated constraint name "${constraintName}" is too long for Oracle (which has a 30 characters limit). It will be truncated!`);
limit = 28;
} else if (prodDatabaseType === 'mysql' && constraintName.length > 64 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated constraint name "${constraintName}" is too long for MySQL (which has a 64 characters limit). It will be truncated!`);
limit = 62;
}
if (limit > 0) {
const halfLimit = Math.floor(limit / 2);
const entityTable = noSnakeCase ? entityName.substring(0, halfLimit) : _.snakeCase(this.getTableName(entityName).substring(0, halfLimit));
const relationTable = noSnakeCase ? relationshipName.substring(0, halfLimit - 1) : _.snakeCase(this.getTableName(relationshipName).substring(0, halfLimit - 1));
return `${entityTable}_${relationTable}_id`;
}
return constraintName;
}
/**
* Print an error message.
*
* @param {string} msg - message to print
*/
error(msg) {
this.env.error(`${chalk.red.bold('ERROR!')} ${msg}`);
}
/**
* Print a warning message.
*
* @param {string} msg - message to print
*/
warning(msg) {
this.log(`${chalk.yellow.bold('WARNING!')} ${msg}`);
}
/**
* Print an info message.
*
* @param {string} msg - message to print
*/
info(msg) {
this.log.info(msg);
}
/**
* Print a success message.
*
* @param {string} msg - message to print
*/
success(msg) {
this.log.ok(msg);
}
/**
* Generate a KeyStore for uaa authorization server.
*/
generateKeyStore() {
const done = this.async();
const keyStoreFile = `${SERVER_MAIN_RES_DIR}keystore.jks`;
if (this.fs.exists(keyStoreFile)) {
this.log(chalk.cyan(`\nKeyStore '${keyStoreFile}' already exists. Leaving unchanged.\n`));
done();
} else {
shelljs.mkdir('-p', SERVER_MAIN_RES_DIR);
const javaHome = shelljs.env.JAVA_HOME;
let keytoolPath = '';
if (javaHome) {
keytoolPath = `${javaHome}/bin/`;
}
shelljs.exec(
`"${keytoolPath}keytool" -genkey -noprompt ` +
'-keyalg RSA ' +
'-alias selfsigned ' +
`-keystore ${keyStoreFile} ` +
'-storepass password ' +
'-keypass password ' +
'-keysize 2048 ' +
`-dname "CN=Java Hipster, OU=Development, O=${this.packageName}, L=, ST=, C="`
, (code) => {
if (code !== 0) {
this.error('\nFailed to create a KeyStore with \'keytool\'', code);
} else {
this.log(chalk.green(`\nKeyStore '${keyStoreFile}' generated successfully.\n`));
}
done();
}
);
}
}
/**
* Prints a JHipster logo.
*/
printJHipsterLogo() {
this.log('\n');
this.log(`${chalk.green(' ██╗')}${chalk.red(' ██╗ ██╗ ████████╗ ███████╗ ██████╗ ████████╗ ████████╗ ███████╗')}`);
this.log(`${chalk.green(' ██║')}${chalk.red(' ██║ ██║ ╚══██╔══╝ ██╔═══██╗ ██╔════╝ ╚══██╔══╝ ██╔═════╝ ██╔═══██╗')}`);
this.log(`${chalk.green(' ██║')}${chalk.red(' ████████║ ██║ ███████╔╝ ╚█████╗ ██║ ██████╗ ███████╔╝')}`);
this.log(`${chalk.green(' ██╗ ██║')}${chalk.red(' ██╔═══██║ ██║ ██╔════╝ ╚═══██╗ ██║ ██╔═══╝ ██╔══██║')}`);
this.log(`${chalk.green(' ╚██████╔╝')}${chalk.red(' ██║ ██║ ████████╗ ██║ ██████╔╝ ██║ ████████╗ ██║ ╚██╗')}`);
this.log(`${chalk.green(' ╚═════╝ ')}${chalk.red(' ╚═╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═╝')}\n`);
this.log(chalk.white.bold(' https://www.jhipster.tech\n'));
this.log(chalk.white('Welcome to the JHipster Generator ') + chalk.yellow(`v${packagejs.version}`));
this.log(chalk.green(' _______________________________________________________________________________________________________________\n'));
this.log(chalk.white(` If you find JHipster useful consider supporting our collective ${chalk.yellow('https://opencollective.com/generator-jhipster')}`));
this.log(chalk.white(` Documentation for creating an application: ${chalk.yellow('https://www.jhipster.tech/creating-an-app/')}`));
this.log(chalk.green(' _______________________________________________________________________________________________________________\n'));
this.log(chalk.white(`Application files will be generated in folder: ${chalk.yellow(process.cwd())}`));
}
/**
* Checks if there is a newer JHipster version available.
*/
checkForNewVersion() {
try {
const done = this.async();
shelljs.exec(`npm show ${GENERATOR_JHIPSTER} version`, { silent: true }, (code, stdout, stderr) => {
if (!stderr && semver.lt(packagejs.version, stdout)) {
this.log(`${chalk.yellow(' ______________________________________________________________________________\n\n') +
chalk.yellow(' JHipster update available: ') + chalk.green.bold(stdout.replace('\n', '')) + chalk.gray(` (current: ${packagejs.version})`)}\n`);
if (this.useYarn) {
this.log(chalk.yellow(` Run ${chalk.magenta(`yarn global upgrade ${GENERATOR_JHIPSTER}`)} to update.\n`));
} else {
this.log(chalk.yellow(` Run ${chalk.magenta(`npm install -g ${GENERATOR_JHIPSTER}`)} to update.\n`));
}
this.log(chalk.yellow(' ______________________________________________________________________________\n'));
}
done();
});
} catch (err) {
this.debug('Error:', err);
// fail silently as this function doesn't affect normal generator flow
}
}
/**
* get the Angular application name.
* @param {string} baseName of application
*/
getAngularAppName(baseName = this.baseName) {
const name = _.camelCase(baseName) + (baseName.endsWith('App') ? '' : 'App');
return name.match(/^\d/) ? 'App' : name;
}
/**
* get the Angular 2+ application name.
* @param {string} baseName of application
*/
getAngularXAppName(baseName = this.baseName) {
const name = this.upperFirstCamelCase(baseName);
return name.match(/^\d/) ? 'App' : name;
}
/**
* get the an upperFirst camelCase value.
* @param {string} value string to convert
*/
upperFirstCamelCase(value) {
return _.upperFirst(_.camelCase(value));
}
/**
* get the java main class name.
* @param {string} baseName of application
*/
getMainClassName(baseName = this.baseName) {
const main = _.upperFirst(this.getMicroserviceAppName(baseName));
const acceptableForJava = new RegExp('^[A-Z][a-zA-Z0-9_]*$');
return acceptableForJava.test(main) ? main : 'Application';
}
/**
* ask a prompt for apps name.
*
* @param {object} generator - generator instance to use
*/
askModuleName(generator) {
const done = generator.async();
const defaultAppBaseName = this.getDefaultAppName();
generator.prompt({
type: 'input',
name: 'baseName',
validate: (input) => {
if (!(/^([a-zA-Z0-9_]*)$/.test(input))) {
return 'Your application name cannot contain special characters or a blank space';
} else if (generator.applicationType === 'microservice' && /_/.test(input)) {
return 'Your microservice name cannot contain underscores as this does not meet the URI spec';
} else if (input === 'application') {
return 'Your application name cannot be named \'application\' as this is a reserved name for Spring Boot';
}
return true;
},
message: 'What is the base name of your application?',
default: defaultAppBaseName
}).then((prompt) => {
generator.baseName = prompt.baseName;
done();
});
}
/**
* ask a prompt for i18n option.
*
* @param {object} generator - generator instance to use
*/
aski18n(generator) {
const languageOptions = this.getAllSupportedLanguageOptions();
const done = generator.async();
const prompts = [
{
type: 'confirm',
name: 'enableTranslation',
message: 'Would you like to enable internationalization support?',
default: true
},
{
when: response => response.enableTranslation === true,
type: 'list',
name: 'nativeLanguage',
message: 'Please choose the native language of the application',
choices: languageOptions,
default: 'en',
store: true
},
{
when: response => response.enableTranslation === true,
type: 'checkbox',
name: 'languages',
message: 'Please choose additional languages to install',
choices: response => _.filter(languageOptions, o => o.value !== response.nativeLanguage)
}
];
generator.prompt(prompts).then((prompt) => {
generator.enableTranslation = prompt.enableTranslation;
generator.nativeLanguage = prompt.nativeLanguage;
generator.languages = [prompt.nativeLanguage].concat(prompt.languages);
done();
});
}
/**
* compose using the language sub generator.
*
* @param {object} generator - generator instance to use
* @param {object} configOptions - options to pass to the generator
* @param {String} type - server | client
*/
composeLanguagesSub(generator, configOptions, type) {
if (generator.enableTranslation) {
// skip server if app type is client
const skipServer = type && type === 'client';
// skip client if app type is server
const skipClient = type && type === 'server';
generator.composeWith(require.resolve('./languages'), {
configOptions,
'skip-install': true,
'skip-server': skipServer,
'skip-client': skipClient,
languages: generator.languages,
force: generator.options.force,
debug: generator.options.debug
});
}
}
/**
* @Deprecated
* Add numbering to a question
*
* @param {String} msg - question text
* @param {boolean} cond - increment question
*/
getNumberedQuestion(msg, cond) {
return msg;
}
/**
* build a generated application.
*
* @param {String} buildTool - maven | gradle
* @param {String} profile - dev | prod
* @param {Function} cb - callback when build is complete
*/
buildApplication(buildTool, profile, cb) {
let buildCmd = 'mvnw verify -DskipTests=true -B';
if (buildTool === 'gradle') {
buildCmd = 'gradlew bootWar -x test';
}
if (os.platform() !== 'win32') {
buildCmd = `./${buildCmd}`;
}
buildCmd += ` -P${profile}`;
const child = {};
child.stdout = exec(buildCmd, { maxBuffer: 1024 * 10000 }, cb).stdout;
child.buildCmd = buildCmd;
return child;
}
/**
* write the given files using provided config.
*
* @param {object} files - files to write
* @param {object} generator - the generator instance to use
* @param {boolean} returnFiles - weather to return the generated file list or to write them
* @param {string} prefix - pefix to add to path
*/
writeFilesToDisk(files, generator, returnFiles, prefix) {
const _this = generator || this;
const filesOut = [];
const startTime = new Date();
// using the fastest method for iterations
for (let i = 0, blocks = Object.keys(files); i < blocks.length; i++) {
for (let j = 0, blockTemplates = files[blocks[i]]; j < blockTemplates.length; j++) {
const blockTemplate = blockTemplates[j];
if (!blockTemplate.condition || blockTemplate.condition(_this)) {
const path = blockTemplate.path ? blockTemplate.path : '';
blockTemplate.templates.forEach((templateObj) => {
let templatePath = path;
let method = 'template';
let useTemplate = false;
let options = {};
let templatePathTo;
if (typeof templateObj === 'string') {
templatePath += templateObj;
} else {
templatePath += templateObj.file;
method = templateObj.method ? templateObj.method : method;
useTemplate = templateObj.template ? templateObj.template : useTemplate;
options = templateObj.options ? templateObj.options : options;
}
if (templateObj && templateObj.renameTo) {
templatePathTo = path + templateObj.renameTo(_this);
} else {
templatePathTo = templatePath.replace(/([/])_|^_/, '$1');
templatePathTo = templatePath.replace('.ejs', '');
}
filesOut.push(templatePathTo);
if (!returnFiles) {
let templatePathFrom = prefix ? `${prefix}/${templatePath}` : templatePath;
if (
!templateObj.noEjs && !templatePathFrom.endsWith('.png')
&& !templatePathFrom.endsWith('.jpg') && !templatePathFrom.endsWith('.gif')
&& !templatePathFrom.endsWith('.svg') && !templatePathFrom.endsWith('.ico')
) {
templatePathFrom = `${templatePathFrom}.ejs`;
}
// if (method === 'template')
_this[method](templatePathFrom, templatePathTo, _this, options, useTemplate);
}
});
}
}
}
this.debug(`Time taken to write files: ${new Date() - startTime}ms`);
return filesOut;
}
/**
* Setup client instance level options from context.
* @param {any} generator - generator instance
* @param {any} context - context to use default is generator instance
*/
setupClientOptions(generator, context = generator) {
generator.skipServer = context.configOptions.skipServer || context.config.get('skipServer');
generator.skipUserManagement = context.configOptions.skipUserManagement || context.options['skip-user-management'] || context.config.get('skipUserManagement');
generator.authenticationType = context.options.auth || context.configOptions.authenticationType || context.config.get('authenticationType');
if (generator.authenticationType === 'oauth2') {
generator.skipUserManagement = true;
}
const uaaBaseName = context.options.uaaBaseName || context.configOptions.uaaBaseName || context.options['uaa-base-name'] || context.config.get('uaaBaseName');
if (context.options.auth === 'uaa' && _.isNil(uaaBaseName)) {
generator.error('when using --auth uaa, a UAA basename must be provided with --uaa-base-name');
}
generator.uaaBaseName = uaaBaseName;
generator.buildTool = context.options.build;
generator.websocket = context.options.websocket;
generator.devDatabaseType = context.options.db || context.configOptions.devDatabaseType || context.config.get('devDatabaseType');
generator.prodDatabaseType = context.options.db || context.configOptions.prodDatabaseType || context.config.get('prodDatabaseType');
generator.databaseType = generator.getDBTypeFromDBValue(context.options.db) || context.configOptions.databaseType || context.config.get('databaseType');
generator.searchEngine = context.options['search-engine'] || context.config.get('searchEngine');
generator.cacheProvider = context.options['cache-provider'] || context.config.get('cacheProvider') || context.config.get('hibernateCache') || 'no';
generator.enableHibernateCache = context.options['hb-cache'] || context.config.get('enableHibernateCache') || (context.config.get('hibernateCache') !== undefined && context.config.get('hibernateCache') !== 'no');
generator.otherModules = context.configOptions.otherModules || [];
generator.jhiPrefix = context.configOptions.jhiPrefix || context.config.get('jhiPrefix') || context.options['jhi-prefix'];
generator.jhiPrefixCapitalized = _.upperFirst(generator.jhiPrefix);
generator.jhiPrefixDashed = _.kebabCase(generator.jhiPrefix);
generator.testFrameworks = [];
if (context.options.protractor) generator.testFrameworks.push('protractor');
generator.baseName = context.configOptions.baseName;
generator.logo = context.configOptions.logo;
generator.useYarn = context.configOptions.useYarn = !context.options.npm;
generator.clientPackageManager = context.configOptions.clientPackageManager;
generator.isDebugEnabled = context.configOptions.isDebugEnabled || context.options.debug;
generator.experimental = context.configOptions.experimental || context.options.experimental;
}
/**
* Setup Server instance level options from context.
* @param {any} generator - generator instance
* @param {any} context - context to use default is generator instance
*/
setupServerOptions(generator, context = generator) {
generator.skipClient = !context.options['client-hook'] || context.configOptions.skipClient || context.config.get('skipClient');
generator.skipUserManagement = context.configOptions.skipUserManagement || context.options['skip-user-management'] || context.config.get('skipUserManagement');
generator.enableTranslation = context.options.i18n || context.configOptions.enableTranslation || context.config.get('enableTranslation');
generator.testFrameworks = [];
if (context.options.gatling) generator.testFrameworks.push('gatling');
if (context.options.cucumber) generator.testFrameworks.push('cucumber');
generator.logo = context.configOptions.logo;
generator.baseName = context.configOptions.baseName;
generator.clientPackageManager = context.configOptions.clientPackageManager;
generator.isDebugEnabled = context.configOptions.isDebugEnabled || context.options.debug;
generator.experimental = context.configOptions.experimental || context.options.experimental;
}
/**
* Setup Entity instance level options from context.
* @param {any} generator - generator instance
* @param {any} context - context to use default is generator instance
* @param {any} dest - destination context to use default is generator instance
*/
setupEntityOptions(generator, context = generator, dest = generator) {
dest.name = context.options.name;
// remove extension if feeding json files
if (dest.name !== undefined) {
dest.name = dest.name.replace('.json', '');
}
dest.regenerate = context.options.regenerate;
dest.fluentMethods = context.options['fluent-methods'];
dest.skipCheckLengthOfIdentifier = context.options['skip-check-length-of-identifier'];
dest.entityTableName = generator.getTableName(context.options['table-name'] || dest.name);
dest.entityNameCapitalized = _.upperFirst(dest.name);
dest.entityAngularJSSuffix = context.options['angular-suffix'];
dest.clientRootFolder = context.options['skip-ui-grouping'] ? '' : context.options['client-root-folder'];
dest.isDebugEnabled = context.options.debug;
generator.experimental = context.options.experimental;
if (dest.entityAngularJSSuffix && !dest.entityAngularJSSuffix.startsWith('-')) {
dest.entityAngularJSSuffix = `-${dest.entityAngularJSSuffix}`;
}
dest.rootDir = generator.destinationRoot();
// enum-specific consts
dest.enums = [];
dest.existingEnum = false;
dest.fieldNamesUnderscored = ['id'];
// these variable hold field and relationship names for question options during update
dest.fieldNameChoices = [];
dest.relNameChoices = [];
}
};
| generators/generator-base.js | /**
* Copyright 2013-2018 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const _ = require('lodash');
const chalk = require('chalk');
const fs = require('fs');
const shelljs = require('shelljs');
const semver = require('semver');
const exec = require('child_process').exec;
const os = require('os');
const pluralize = require('pluralize');
const jhiCore = require('jhipster-core');
const packagejs = require('../package.json');
const jhipsterUtils = require('./utils');
const constants = require('./generator-constants');
const PrivateBase = require('./generator-base-private');
const JHIPSTER_CONFIG_DIR = '.jhipster';
const MODULES_HOOK_FILE = `${JHIPSTER_CONFIG_DIR}/modules/jhi-hooks.json`;
const GENERATOR_JHIPSTER = 'generator-jhipster';
const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
const CLIENT_WEBPACK_DIR = constants.CLIENT_WEBPACK_DIR;
const SERVER_MAIN_SRC_DIR = constants.SERVER_MAIN_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
/**
* This is the Generator base class.
* This provides all the public API methods exposed via the module system.
* The public API methods can be directly utilized as well using commonJS require.
*
* The method signatures in public API should not be changed without a major version change
*/
module.exports = class extends PrivateBase {
/**
* Get the JHipster configuration from the .yo-rc.json file.
*
* @param {string} namespace - namespace of the .yo-rc.json config file. By default: generator-jhipster
*/
getJhipsterAppConfig(namespace = 'generator-jhipster') {
const fromPath = '.yo-rc.json';
if (shelljs.test('-f', fromPath)) {
const fileData = this.fs.readJSON(fromPath);
if (fileData && fileData[namespace]) {
return fileData[namespace];
}
}
return false;
}
/**
* Add a new menu element, at the root of the menu.
*
* @param {string} routerName - The name of the Angular router that is added to the menu.
* @param {string} glyphiconName - The name of the Glyphicon (from Bootstrap) that will be displayed.
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addElementToMenu(routerName, glyphiconName, enableTranslation, clientFramework) {
let navbarPath;
try {
if (clientFramework === 'angularX') {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [`<li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
<a class="nav-link" routerLink="${routerName}" (click)="collapseNavbar()">
<i class="fa fa-${glyphiconName}"></i>
<span${enableTranslation ? ` jhiTranslate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>`
]
}, this);
} else {
// React
// TODO:
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + navbarPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add external resources to root file(index.html).
*
* @param {string} resources - Resources added to root file.
* @param {string} comment - comment to add before resources content.
*/
addExternalResourcesToRoot(resources, comment) {
const indexFilePath = `${CLIENT_MAIN_SRC_DIR}index.html`;
let resourcesBlock = '';
if (comment) {
resourcesBlock += `<!-- ${comment} -->\n`;
}
resourcesBlock += `${resources}\n`;
try {
jhipsterUtils.rewriteFile({
file: indexFilePath,
needle: 'jhipster-needle-add-resources-to-root',
splicable: [resourcesBlock]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + indexFilePath + chalk.yellow(' or missing required jhipster-needle. Resources are not added to JHipster app.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new menu element to the admin menu.
*
* @param {string} routerName - The name of the Angular router that is added to the admin menu.
* @param {string} glyphiconName - The name of the Glyphicon (from Bootstrap) that will be displayed.
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addElementToAdminMenu(routerName, glyphiconName, enableTranslation, clientFramework) {
let navbarAdminPath;
try {
if (clientFramework === 'angularX') {
navbarAdminPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: navbarAdminPath,
needle: 'jhipster-needle-add-element-to-admin-menu',
splicable: [`<li>
<a class="dropdown-item" routerLink="${routerName}" routerLinkActive="active" (click)="collapseNavbar()">
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span${enableTranslation ? ` jhiTranslate="global.menu.admin.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>`
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + navbarAdminPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + routerName} ${chalk.yellow('not added to admin menu.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new entity route path to webpacks config
*
* @param {string} microserviceName - The name of the microservice to put into the url
* @param {string} clientFramework - The name of the client framework
*/
addEntityToWebpack(microserviceName, clientFramework) {
const webpackDevPath = `${CLIENT_WEBPACK_DIR}/webpack.dev.js`;
jhipsterUtils.rewriteFile({
file: webpackDevPath,
needle: 'jhipster-needle-add-entity-to-webpack',
splicable: [`'/${microserviceName.toLowerCase()}',`]
}, this);
}
/**
* Add a new entity in the "entities" menu.
*
* @param {string} routerName - The name of the Angular router (which by default is the name of the entity).
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addEntityToMenu(routerName, enableTranslation, clientFramework, entityTranslationKeyMenu = _.camelCase(routerName)) {
let entityMenuPath;
try {
if (this.clientFramework === 'angularX') {
entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: entityMenuPath,
needle: 'jhipster-needle-add-entity-to-menu',
splicable: [
this.stripMargin(`|<li>
| <a class="dropdown-item" routerLink="${routerName}" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" (click)="collapseNavbar()">
| <i class="fa fa-fw fa-asterisk" aria-hidden="true"></i>
| <span${enableTranslation ? ` jhiTranslate="global.menu.entities.${entityTranslationKeyMenu}"` : ''}>${_.startCase(routerName)}</span>
| </a>
| </li>`)
]
}, this);
} else {
// React
entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/shared/layout/header/header.tsx`;
jhipsterUtils.rewriteFile({
file: entityMenuPath,
needle: 'jhipster-needle-add-entity-to-menu',
splicable: [
this.stripMargin(`|(
| <DropdownItem tag={Link} key="${routerName}" to="/${routerName}">
| <FaAsterisk />
| ${_.startCase(routerName)}
| </DropdownItem>
| ),`)
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + entityMenuPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new entity in the TS modules file.
*
* @param {string} entityInstance - Entity Instance
* @param {string} entityClass - Entity Class
* @param {string} entityAngularName - Entity Angular Name
* @param {string} entityFolderName - Entity Folder Name
* @param {string} entityFileName - Entity File Name
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
*/
addEntityToModule(entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName, enableTranslation, clientFramework, microServiceName) {
const entityModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/entity.module.ts`;
try {
if (clientFramework === 'angularX') {
const appName = this.getAngularXAppName();
let importName = `${appName}${entityAngularName}Module`;
if (microServiceName) {
importName = `${importName} as ${this.upperFirstCamelCase(microServiceName)}${entityAngularName}Module`;
}
let importStatement = `|import { ${importName} } from './${entityFolderName}/${entityFileName}.module';`;
if (importStatement.length > constants.LINE_LENGTH) {
importStatement =
`|// prettier-ignore
|import {
| ${importName}
|} from './${entityFolderName}/${entityFileName}.module';`;
}
jhipsterUtils.rewriteFile({
file: entityModulePath,
needle: 'jhipster-needle-add-entity-module-import',
splicable: [
this.stripMargin(importStatement)
]
}, this);
jhipsterUtils.rewriteFile({
file: entityModulePath,
needle: 'jhipster-needle-add-entity-module',
splicable: [
this.stripMargin(microServiceName ? `|${this.upperFirstCamelCase(microServiceName)}${entityAngularName}Module,` : `|${appName}${entityAngularName}Module,`)
]
}, this);
} else {
// React
const indexModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/index.tsx`;
jhipsterUtils.rewriteFile({
file: indexModulePath,
needle: 'jhipster-needle-add-route-import',
splicable: [
this.stripMargin(`|import ${entityAngularName} from './${entityFolderName}';`)
]
}, this);
jhipsterUtils.rewriteFile({
file: indexModulePath,
needle: 'jhipster-needle-add-route-path',
splicable: [
this.stripMargin(`|<Route path={'/${entityFileName}'} component={${entityAngularName}}/>`)
]
}, this);
const indexReducerPath = `${CLIENT_MAIN_SRC_DIR}app/shared/reducers/index.ts`;
jhipsterUtils.rewriteFile({
file: indexReducerPath,
needle: 'jhipster-needle-add-reducer-import',
splicable: [
this.stripMargin(`|import ${entityInstance} from 'app/entities/${entityFolderName}/${entityFileName}.reducer';`)
]
}, this);
jhipsterUtils.rewriteFile({
file: indexReducerPath,
needle: 'jhipster-needle-add-reducer-combine',
splicable: [
this.stripMargin(`${entityInstance},`)
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + entityModulePath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + entityInstance + entityClass + entityFolderName + entityFileName} ${chalk.yellow(`not added to ${entityModulePath}.\n`)}`);
this.debug('Error:', e);
}
}
/**
* Add a new admin in the TS modules file.
*
* @param {string} appName - Angular2 application name.
* @param {string} adminAngularName - The name of the new admin item.
* @param {string} adminFolderName - The name of the folder.
* @param {string} adminFileName - The name of the file.
* @param {boolean} enableTranslation - If translations are enabled or not.
* @param {string} clientFramework - The name of the client framework.
*/
addAdminToModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation, clientFramework) {
const adminModulePath = `${CLIENT_MAIN_SRC_DIR}app/admin/admin.module.ts`;
try {
let importStatement = `|import { ${appName}${adminAngularName}Module } from './${adminFolderName}/${adminFileName}.module';`;
if (importStatement.length > constants.LINE_LENGTH) {
importStatement =
`|import {
| ${appName}${adminAngularName}Module
|} from './${adminFolderName}/${adminFileName}.module';`;
}
jhipsterUtils.rewriteFile({
file: adminModulePath,
needle: 'jhipster-needle-add-admin-module-import',
splicable: [
this.stripMargin(importStatement)
]
}, this);
jhipsterUtils.rewriteFile({
file: adminModulePath,
needle: 'jhipster-needle-add-admin-module',
splicable: [
this.stripMargin(`|${appName}${adminAngularName}Module,`)
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + appName + chalk.yellow(' or missing required jhipster-needle. Reference to ') + adminAngularName + adminFolderName + adminFileName + enableTranslation + clientFramework} ${chalk.yellow(`not added to ${adminModulePath}.\n`)}`);
this.debug('Error:', e);
}
}
/**
* Add a new element in the "global.json" translations.
*
* @param {string} key - Key for the menu entry
* @param {string} value - Default translated value
* @param {string} language - The language to which this translation should be added
*/
addElementTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-menu-add-element',
splicable: [
`"${key}": "${_.startCase(value)}",`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + language + chalk.yellow(' not added as a new entity in the menu.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new element in the admin section of "global.json" translations.
*
* @param {string} key - Key for the menu entry
* @param {string} value - Default translated value
* @param {string} language - The language to which this translation should be added
*/
addAdminElementTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-menu-add-admin-element',
splicable: [
`"${key}": "${_.startCase(value)}",`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + language + chalk.yellow(' not added as a new entry in the admin menu.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new entity in the "global.json" translations.
*
* @param {string} key - Key for the entity name
* @param {string} value - Default translated value
* @param {string} language - The language to which this translation should be added
*/
addEntityTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-menu-add-entry',
splicable: [
`"${key}": "${_.startCase(value)}",`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + language + chalk.yellow(' not added as a new entity in the menu.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new entry as a root param in "global.json" translations.
*
* @param {string} key - Key for the entry
* @param {string} value - Default translated value or object with multiple key and translated value
* @param {string} language - The language to which this translation should be added
*/
addGlobalTranslationKey(key, value, language) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}i18n/${language}/global.json`;
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
jsonObj[key] = value;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}(key: ${key}, value:${value})${chalk.yellow(' not added to global translations.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a translation key to all installed languages
*
* @param {string} key - Key for the entity name
* @param {string} value - Default translated value
* @param {string} method - The method to be run with provided key and value from above
* @param {string} enableTranslation - specify if i18n is enabled
*/
addTranslationKeyToAllLanguages(key, value, method, enableTranslation) {
if (enableTranslation) {
this.getAllInstalledLanguages().forEach((language) => {
this[method](key, value, language);
});
}
}
/**
* get all the languages installed currently
*/
getAllInstalledLanguages() {
const languages = [];
this.getAllSupportedLanguages().forEach((language) => {
try {
const stats = fs.lstatSync(`${CLIENT_MAIN_SRC_DIR}i18n/${language}`);
if (stats.isDirectory()) {
languages.push(language);
}
} catch (e) {
this.debug('Error:', e);
// An exception is thrown if the folder doesn't exist
// do nothing as the language might not be installed
}
});
return languages;
}
/**
* get all the languages supported by JHipster
*/
getAllSupportedLanguages() {
return _.map(this.getAllSupportedLanguageOptions(), 'value');
}
/**
* check if a language is supported by JHipster
* @param {string} language - Key for the language
*/
isSupportedLanguage(language) {
return _.includes(this.getAllSupportedLanguages(), language);
}
/**
* check if Right-to-Left support is necesary for i18n
* @param {string[]} languages - languages array
*/
isI18nRTLSupportNecessary(languages) {
if (!languages) {
return false;
}
const rtlLanguages = this.getAllSupportedLanguageOptions().filter(langObj => langObj.rtl);
return languages.some(lang => !!rtlLanguages.find(langObj => langObj.value === lang));
}
/**
* return the localeId from the given language key (from constants.LANGUAGES)
* if no localeId is defined, return the language key (which is a localeId itself)
* @param {string} language - language key
*/
getLocaleId(language) {
const langObj = this.getAllSupportedLanguageOptions().find(langObj => langObj.value === language);
return langObj.localeId || language;
}
/**
* get all the languages options supported by JHipster
*/
getAllSupportedLanguageOptions() {
return constants.LANGUAGES;
}
/**
* Add a new dependency in the "bower.json".
*
* @param {string} name - dependency name
* @param {string} version - dependency version
*/
addBowerDependency(name, version) {
const fullPath = 'bower.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.dependencies === undefined) {
jsonObj.dependencies = {};
}
jsonObj.dependencies[name] = version;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}bower dependency (name: ${name}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new override configuration in the "bower.json".
*
* @param {string} bowerPackageName - Bower package name use in dependencies
* @param {array} main - You can specify which files should be selected
* @param {boolean} isIgnored - Default: false, Set to true if you want to ignore this package.
* @param {object} dependencies - You can override the dependencies of a package. Set to null to ignore the dependencies.
*
*/
addBowerOverride(bowerPackageName, main, isIgnored, dependencies) {
const fullPath = 'bower.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
const override = {};
if (main !== undefined && main.length > 0) {
override.main = main;
}
if (isIgnored) {
override.ignore = true;
}
if (dependencies) {
override.dependencies = dependencies;
}
if (jsonObj.overrides === undefined) {
jsonObj.overrides = {};
}
jsonObj.overrides[bowerPackageName] = override;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}bower override configuration (bowerPackageName: ${bowerPackageName}, main:${JSON.stringify(main)}, ignore:${isIgnored})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new parameter in the ".bowerrc".
*
* @param {string} key - name of the parameter
* @param {string | boolean | any} value - value of the parameter
*/
addBowerrcParameter(key, value) {
const fullPath = '.bowerrc';
try {
this.log(chalk.yellow(' update ') + fullPath);
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
jsonObj[key] = value;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}bowerrc parameter (key: ${key}, value:${value})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new dependency in the "package.json".
*
* @param {string} name - dependency name
* @param {string} version - dependency version
*/
addNpmDependency(name, version) {
const fullPath = 'package.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.dependencies === undefined) {
jsonObj.dependencies = {};
}
jsonObj.dependencies[name] = version;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}npm dependency (name: ${name}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new devDependency in the "package.json".
*
* @param {string} name - devDependency name
* @param {string} version - devDependency version
*/
addNpmDevDependency(name, version) {
const fullPath = 'package.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.devDependencies === undefined) {
jsonObj.devDependencies = {};
}
jsonObj.devDependencies[name] = version;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}npm devDependency (name: ${name}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new script in the "package.json".
*
* @param {string} name - script name
* @param {string} data - script version
*/
addNpmScript(name, data) {
const fullPath = 'package.json';
try {
jhipsterUtils.rewriteJSONFile(fullPath, (jsonObj) => {
if (jsonObj.scripts === undefined) {
jsonObj.scripts = {};
}
jsonObj.scripts[name] = data;
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow('. Reference to ')}npm script (name: ${name}, data:${data})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new module in the TS modules file.
*
* @param {string} appName - Angular2 application name.
* @param {string} angularName - The name of the new admin item.
* @param {string} folderName - The name of the folder.
* @param {string} fileName - The name of the file.
* @param {boolean} enableTranslation - If translations are enabled or not.
* @param {string} clientFramework - The name of the client framework.
*/
addAngularModule(appName, angularName, folderName, fileName, enableTranslation, clientFramework) {
const modulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
try {
let importStatement = `|import { ${appName}${angularName}Module } from './${folderName}/${fileName}.module';`;
if (importStatement.length > constants.LINE_LENGTH) {
importStatement =
`|import {
| ${appName}${angularName}Module
|} from './${folderName}/${fileName}.module';`;
}
jhipsterUtils.rewriteFile({
file: modulePath,
needle: 'jhipster-needle-angular-add-module-import',
splicable: [
this.stripMargin(importStatement)
]
}, this);
jhipsterUtils.rewriteFile({
file: modulePath,
needle: 'jhipster-needle-angular-add-module',
splicable: [
this.stripMargin(`|${appName}${angularName}Module,`)
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + appName + chalk.yellow(' or missing required jhipster-needle. Reference to ') + angularName + folderName + fileName + enableTranslation + clientFramework} ${chalk.yellow(`not added to ${modulePath}.\n`)}`);
this.debug('Error:', e);
}
}
/**
* Add a new http interceptor to the angular application in "blocks/config/http.config.js".
* The interceptor should be in its own .js file inside app/blocks/interceptor folder
* @param {string} interceptorName - angular name of the interceptor
*
*/
addAngularJsInterceptor(interceptorName) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}app/blocks/config/http.config.js`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-angularjs-add-interceptor',
splicable: [
`$httpProvider.interceptors.push('${interceptorName}');`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Interceptor not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add a new entity to Ehcache, for the 2nd level cache of an entity and its relationships.
*
* @param {string} entityClass - the entity to cache
* @param {array} relationships - the relationships of this entity
* @param {string} packageName - the Java package name
* @param {string} packageFolder - the Java package folder
*/
addEntityToEhcache(entityClass, relationships, packageName, packageFolder) {
this.addEntityToCache(entityClass, relationships, packageName, packageFolder, 'ehcache');
}
/**
* Add a new entry to Ehcache in CacheConfiguration.java
*
* @param {string} entry - the entry (including package name) to cache
* @param {string} packageFolder - the Java package folder
*/
addEntryToEhcache(entry, packageFolder) {
this.addEntryToCache(entry, packageFolder, 'ehcache');
}
/**
* Add a new entity to the chosen cache provider, for the 2nd level cache of an entity and its relationships.
*
* @param {string} entityClass - the entity to cache
* @param {array} relationships - the relationships of this entity
* @param {string} packageName - the Java package name
* @param {string} packageFolder - the Java package folder
* @param {string} cacheProvider - the cache provider
*/
addEntityToCache(entityClass, relationships, packageName, packageFolder, cacheProvider) {
// Add the entity to ehcache
this.addEntryToCache(`${packageName}.domain.${entityClass}.class.getName()`, packageFolder, cacheProvider);
// Add the collections linked to that entity to ehcache
relationships.forEach((relationship) => {
const relationshipType = relationship.relationshipType;
if (relationshipType === 'one-to-many' || relationshipType === 'many-to-many') {
this.addEntryToCache(`${packageName}.domain.${entityClass}.class.getName() + ".${relationship.relationshipFieldNamePlural}"`, packageFolder, cacheProvider);
}
});
}
/**
* Add a new entry to the chosen cache provider in CacheConfiguration.java
*
* @param {string} entry - the entry (including package name) to cache
* @param {string} packageFolder - the Java package folder
* @param {string} cacheProvider - the cache provider
*/
addEntryToCache(entry, packageFolder, cacheProvider) {
try {
const cachePath = `${SERVER_MAIN_SRC_DIR}${packageFolder}/config/CacheConfiguration.java`;
if (cacheProvider === 'ehcache') {
jhipsterUtils.rewriteFile({
file: cachePath,
needle: 'jhipster-needle-ehcache-add-entry',
splicable: [`cm.createCache(${entry}, jcacheConfiguration);`
]
}, this);
} else if (cacheProvider === 'infinispan') {
jhipsterUtils.rewriteFile({
file: cachePath,
needle: 'jhipster-needle-infinispan-add-entry',
splicable: [`registerPredefinedCache(${entry}, new JCache<Object, Object>(
cacheManager.getCache(${entry}).getAdvancedCache(), this,
ConfigurationAdapter.create()));`
]
}, this);
}
} catch (e) {
this.log(chalk.yellow(`\nUnable to add ${entry} to CacheConfiguration.java file.\n\t${e.message}`));
this.debug('Error:', e);
}
}
/**
* Add a new changelog to the Liquibase master.xml file.
*
* @param {string} changelogName - The name of the changelog (name of the file without .xml at the end).
*/
addChangelogToLiquibase(changelogName) {
this.addLiquibaseChangelogToMaster(changelogName, 'jhipster-needle-liquibase-add-changelog');
}
/**
* Add a new constraints changelog to the Liquibase master.xml file.
*
* @param {string} changelogName - The name of the changelog (name of the file without .xml at the end).
*/
addConstraintsChangelogToLiquibase(changelogName) {
this.addLiquibaseChangelogToMaster(changelogName, 'jhipster-needle-liquibase-add-constraints-changelog');
}
/**
* Add a new changelog to the Liquibase master.xml file.
*
* @param {string} changelogName - The name of the changelog (name of the file without .xml at the end).
* @param {string} needle - The needle at where it has to be added.
*/
addLiquibaseChangelogToMaster(changelogName, needle) {
const fullPath = `${SERVER_MAIN_RES_DIR}config/liquibase/master.xml`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle,
splicable: [
`<include file="config/liquibase/changelog/${changelogName}.xml" relativeToChangelogFile="false"/>`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + changelogName}.xml ${chalk.yellow('not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new column to a Liquibase changelog file for entity.
*
* @param {string} filePath - The full path of the changelog file.
* @param {string} content - The content to be added as column, can have multiple columns as well
*/
addColumnToLiquibaseEntityChangeset(filePath, content) {
try {
jhipsterUtils.rewriteFile({
file: filePath,
needle: 'jhipster-needle-liquibase-add-column',
splicable: [
content
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required jhipster-needle. Column not added.\n') + e);
this.debug('Error:', e);
}
}
/**
* Add a new changeset to a Liquibase changelog file for entity.
*
* @param {string} filePath - The full path of the changelog file.
* @param {string} content - The content to be added as changeset
*/
addChangesetToLiquibaseEntityChangelog(filePath, content) {
try {
jhipsterUtils.rewriteFile({
file: filePath,
needle: 'jhipster-needle-liquibase-add-changeset',
splicable: [
content
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required jhipster-needle. Changeset not added.\n') + e);
this.debug('Error:', e);
}
}
/**
* Add new css style to the angular application in "main.css".
*
* @param {boolean} isUseSass - flag indicating if sass should be used
* @param {string} style - css to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.jhipster {\n color: #baa186;\n}'
* comment = 'New JHipster color'
*
* * ==========================================================================
* New JHipster color
* ========================================================================== *
* .jhipster {
* color: #baa186;
* }
*
*/
addMainCSSStyle(isUseSass, style, comment) {
if (isUseSass) {
this.addMainSCSSStyle(style, comment);
}
const fullPath = `${CLIENT_MAIN_SRC_DIR}content/css/main.css`;
let styleBlock = '';
if (comment) {
styleBlock += '/* ==========================================================================\n';
styleBlock += `${comment}\n`;
styleBlock += '========================================================================== */\n';
}
styleBlock += `${style}\n`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-css-add-main',
splicable: [
styleBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Style not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add new scss style to the angular application in "main.scss".
*
* @param {string} style - scss to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.success {\n @extend .message;\n border-color: green;\n}'
* comment = 'Message'
*
* * ==========================================================================
* Message
* ========================================================================== *
* .success {
* @extend .message;
* border-color: green;
* }
*
*/
addMainSCSSStyle(style, comment) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}scss/main.scss`;
let styleBlock = '';
if (comment) {
styleBlock += '/* ==========================================================================\n';
styleBlock += `${comment}\n`;
styleBlock += '========================================================================== */\n';
}
styleBlock += `${style}\n`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-scss-add-main',
splicable: [
styleBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Style not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add new scss style to the angular application in "vendor.scss".
*
* @param {string} style - scss to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.success {\n @extend .message;\n border-color: green;\n}'
* comment = 'Message'
*
* * ==========================================================================
* Message
* ========================================================================== *
* .success {
* @extend .message;
* border-color: green;
* }
*
*/
addVendorSCSSStyle(style, comment) {
const fullPath = `${CLIENT_MAIN_SRC_DIR}content/scss/vendor.scss`;
let styleBlock = '';
if (comment) {
styleBlock += '/* ==========================================================================\n';
styleBlock += `${comment}\n`;
styleBlock += '========================================================================== */\n';
}
styleBlock += `${style}\n`;
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-scss-add-vendor',
splicable: [
styleBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Style not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Copy third-party library resources path.
*
* @param {string} sourceFolder - third-party library resources source path
* @param {string} targetFolder - third-party library resources destination path
*/
copyExternalAssetsInWebpack(sourceFolder, targetFolder) {
const from = `${CLIENT_MAIN_SRC_DIR}content/${sourceFolder}/`;
const to = `content/${targetFolder}/`;
const webpackDevPath = `${CLIENT_WEBPACK_DIR}/webpack.common.js`;
let assetBlock = '';
if (sourceFolder && targetFolder) {
assetBlock = `{ from: './${from}', to: '${to}' },`;
}
try {
jhipsterUtils.rewriteFile({
file: webpackDevPath,
needle: 'jhipster-needle-add-assets-to-webpack',
splicable: [
assetBlock
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + webpackDevPath + chalk.yellow(' or missing required jhipster-needle. Resource path not added to JHipster app.\n'));
this.debug('Error:', e);
}
}
/**
* Add a Maven dependency Management.
*
* @param {string} groupId - dependency groupId
* @param {string} artifactId - dependency artifactId
* @param {string} version - (optional) explicit dependency version number
* @param {string} type - (optional) explicit type
* @param {string} scope - (optional) explicit scope
* @param {string} other - (optional) explicit other thing: exclusions...
*/
addMavenDependencyManagement(groupId, artifactId, version, type, scope, other) {
const fullPath = 'pom.xml';
try {
let dependency = `${'<dependency>\n' +
' <groupId>'}${groupId}</groupId>\n` +
` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
dependency += ` <version>${version}</version>\n`;
}
if (type) {
dependency += ` <type>${type}</type>\n`;
}
if (scope) {
dependency += ` <scope>${version}</scope>\n`;
}
if (other) {
dependency += `${other}\n`;
}
dependency += ' </dependency>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-add-dependency-management',
splicable: [
dependency
]
}, this);
} catch (e) {
this.log(e);
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven dependency (groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a remote Maven Repository to the Maven build.
*
* @param {string} id - id of the repository
* @param {string} url - url of the repository
*/
addMavenRepository(id, url) {
const fullPath = 'pom.xml';
try {
const repository = `${'<repository>\n' +
' <id>'}${id}</id>\n` +
` <url>${url}</url>\n` +
' </repository>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-repository',
splicable: [
repository
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven repository (id: ${id}, url:${url})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven property.
*
* @param {string} name - property name
* @param {string} value - property value
*/
addMavenProperty(name, value) {
const fullPath = 'pom.xml';
try {
const property = `<${name}>${value}</${name}>`;
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-property',
splicable: [
property
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven property (name: ${name}, value:${value})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven dependency.
*
* @param {string} groupId - dependency groupId
* @param {string} artifactId - dependency artifactId
* @param {string} version - (optional) explicit dependency version number
* @param {string} other - (optional) explicit other thing: scope, exclusions...
*/
addMavenDependency(groupId, artifactId, version, other) {
this.addMavenDependencyInDirectory('.', groupId, artifactId, version, other);
}
/**
* Add a new Maven dependency in a specific folder..
*
* @param {string} directory - the folder to add the dependency in
* @param {string} groupId - dependency groupId
* @param {string} artifactId - dependency artifactId
* @param {string} version - (optional) explicit dependency version number
* @param {string} other - (optional) explicit other thing: scope, exclusions...
*/
addMavenDependencyInDirectory(directory, groupId, artifactId, version, other) {
try {
let dependency = `${'<dependency>\n' +
' <groupId>'}${groupId}</groupId>\n` +
` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
dependency += ` <version>${version}</version>\n`;
}
if (other) {
dependency += `${other}\n`;
}
dependency += ' </dependency>';
jhipsterUtils.rewriteFile({
path: directory,
file: 'pom.xml',
needle: 'jhipster-needle-maven-add-dependency',
splicable: [
dependency
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + directory + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven dependency (groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven plugin.
*
* @param {string} groupId - plugin groupId
* @param {string} artifactId - plugin artifactId
* @param {string} version - explicit plugin version number
* @param {string} other - explicit other thing: executions, configuration...
*/
addMavenPlugin(groupId, artifactId, version, other) {
const fullPath = 'pom.xml';
try {
let plugin = `${'<plugin>\n' +
' <groupId>'}${groupId}</groupId>\n` +
` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
plugin += ` <version>${version}</version>\n`;
}
if (other) {
plugin += `${other}\n`;
}
plugin += ' </plugin>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-add-plugin',
splicable: [
plugin
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven plugin (groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add a new Maven profile.
*
* @param {string} profileId - profile ID
* @param {string} other - explicit other thing: build, dependencies...
*/
addMavenProfile(profileId, other) {
const fullPath = 'pom.xml';
try {
let profile = '<profile>\n' +
` <id>${profileId}</id>\n`;
if (other) {
profile += `${other}\n`;
}
profile += ' </profile>';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-maven-add-profile',
splicable: [
profile
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}maven profile (id: ${profileId})${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* A new Gradle plugin.
*
* @param {string} group - plugin GroupId
* @param {string} name - plugin name
* @param {string} version - explicit plugin version number
*/
addGradlePlugin(group, name, version) {
const fullPath = 'build.gradle';
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-buildscript-dependency',
splicable: [
`classpath '${group}:${name}:${version}'`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}classpath: ${group}:${name}:${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Add Gradle plugin to the plugins block
*
* @param {string} id - plugin id
* @param {string} version - explicit plugin version number
*/
addGradlePluginToPluginsBlock(id, version) {
const fullPath = 'build.gradle';
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-plugins',
splicable: [
`id "${id}" version "${version}"`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ')}id ${id} version ${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* A new dependency to build.gradle file.
*
* @param {string} scope - scope of the new dependency, e.g. compile
* @param {string} group - maven GroupId
* @param {string} name - maven ArtifactId
* @param {string} version - (optional) explicit dependency version number
*/
addGradleDependencyManagement(scope, group, name, version) {
const fullPath = 'build.gradle';
let dependency = `${group}:${name}`;
if (version) {
dependency += `:${version}`;
}
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-dependency-management',
splicable: [
`${scope} "${dependency}"`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + group}:${name}:${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* A new dependency to build.gradle file.
*
* @param {string} scope - scope of the new dependency, e.g. compile
* @param {string} group - maven GroupId
* @param {string} name - maven ArtifactId
* @param {string} version - (optional) explicit dependency version number
*/
addGradleDependency(scope, group, name, version) {
this.addGradleDependencyInDirectory('.', scope, group, name, version);
}
/**
* A new dependency to build.gradle file in a specific folder.
*
* @param {string} scope - scope of the new dependency, e.g. compile
* @param {string} group - maven GroupId
* @param {string} name - maven ArtifactId
* @param {string} version - (optional) explicit dependency version number
*/
addGradleDependencyInDirectory(directory, scope, group, name, version) {
let dependency = `${group}:${name}`;
if (version) {
dependency += `:${version}`;
}
try {
jhipsterUtils.rewriteFile({
path: directory,
file: 'build.gradle',
needle: 'jhipster-needle-gradle-dependency',
splicable: [
`${scope} "${dependency}"`
]
}, this);
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + directory + chalk.yellow(' or missing required jhipster-needle. Reference to ') + group}:${name}:${version}${chalk.yellow(' not added.\n')}`);
this.debug('Error:', e);
}
}
/**
* Apply from an external Gradle build script.
*
* @param {string} name - name of the file to apply from, must be 'fileName.gradle'
*/
applyFromGradleScript(name) {
const fullPath = 'build.gradle';
try {
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-apply-from',
splicable: [
`apply from: '${name}.gradle'`
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + name + chalk.yellow(' not added.\n'));
this.debug('Error:', e);
}
}
/**
* Add a remote Maven Repository to the Gradle build.
*
* @param {string} url - url of the repository
* @param {string} username - (optional) username of the repository credentials
* @param {string} password - (optional) password of the repository credentials
*/
addGradleMavenRepository(url, username, password) {
const fullPath = 'build.gradle';
try {
let repository = 'maven {\n';
if (url) {
repository += ` url "${url}"\n`;
}
if (username || password) {
repository += ' credentials {\n';
if (username) {
repository += ` username = "${username}"\n`;
}
if (password) {
repository += ` password = "${password}"\n`;
}
repository += ' }\n';
}
repository += ' }';
jhipsterUtils.rewriteFile({
file: fullPath,
needle: 'jhipster-needle-gradle-repositories',
splicable: [
repository
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + url + chalk.yellow(' not added.\n'));
this.debug('Error:', e);
}
}
/**
* Generate a date to be used by Liquibase changelogs.
*/
dateFormatForLiquibase() {
const now = new Date();
const nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
const year = `${nowUTC.getFullYear()}`;
let month = `${nowUTC.getMonth() + 1}`;
if (month.length === 1) {
month = `0${month}`;
}
let day = `${nowUTC.getDate()}`;
if (day.length === 1) {
day = `0${day}`;
}
let hour = `${nowUTC.getHours()}`;
if (hour.length === 1) {
hour = `0${hour}`;
}
let minute = `${nowUTC.getMinutes()}`;
if (minute.length === 1) {
minute = `0${minute}`;
}
let second = `${nowUTC.getSeconds()}`;
if (second.length === 1) {
second = `0${second}`;
}
return `${year}${month}${day}${hour}${minute}${second}`;
}
/**
* Copy templates with all the custom logic applied according to the type.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {string} action - type of the action to be performed on the template file, i.e: stripHtml | stripJs | template | copy
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy method
*/
copyTemplate(source, dest, action, generator, opt = {}, template) {
const _this = generator || this;
let regex;
switch (action) {
case 'stripHtml':
regex = new RegExp([
/( (data-t|jhiT)ranslate="([a-zA-Z0-9 +{}'_](\.)?)+")/, // data-translate or jhiTranslate
/( translate(-v|V)alues="\{([a-zA-Z]|\d|:|\{|\}|\[|\]|-|'|\s|\.|_)*?\}")/, // translate-values or translateValues
/( translate-compile)/, // translate-compile
/( translate-value-max="[0-9{}()|]*")/, // translate-value-max
].map(r => r.source).join('|'), 'g');
jhipsterUtils.copyWebResource(source, dest, regex, 'html', _this, opt, template);
break;
case 'stripJs':
regex = new RegExp([
/(,[\s]*(resolve):[\s]*[{][\s]*(translatePartialLoader)['a-zA-Z0-9$,(){.<%=\->;\s:[\]]*(;[\s]*\}\][\s]*\}))/, // ng1 resolve block
/([\s]import\s\{\s?JhiLanguageService\s?\}\sfrom\s["|']ng-jhipster["|'];)/, // ng2 import jhiLanguageService
/(,?\s?JhiLanguageService,?\s?)/, // ng2 import jhiLanguageService
/(private\s[a-zA-Z0-9]*(L|l)anguageService\s?:\s?JhiLanguageService\s?,*[\s]*)/, // ng2 jhiLanguageService constructor argument
/(this\.[a-zA-Z0-9]*(L|l)anguageService\.setLocations\(\[['"a-zA-Z0-9\-_,\s]+\]\);[\s]*)/, // jhiLanguageService invocations
].map(r => r.source).join('|'), 'g');
jhipsterUtils.copyWebResource(source, dest, regex, 'js', _this, opt, template);
break;
case 'copy':
_this.copy(source, dest);
break;
default:
_this.template(source, dest, _this, opt);
}
}
/**
* Copy html templates after stripping translation keys when translation is disabled.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy
*/
processHtml(source, dest, generator, opt, template) {
this.copyTemplate(source, dest, 'stripHtml', generator, opt, template);
}
/**
* Copy Js templates after stripping translation keys when translation is disabled.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy
*/
processJs(source, dest, generator, opt, template) {
this.copyTemplate(source, dest, 'stripJs', generator, opt, template);
}
/**
* Copy JSX templates after stripping translation keys when translation is disabled.
*
* @param {string} source - path of the source file to copy from
* @param {string} dest - path of the destination file to copy to
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {object} opt - options that can be passed to template method
* @param {boolean} template - flag to use template method instead of copy
*/
processJsx(source, dest, generator, opt, template) {
this.copyTemplate(source, dest, 'stripJs', generator, opt, template);
}
/**
* Rewrite the specified file with provided content at the needle location
*
* @param {string} filePath - path of the source file to rewrite
* @param {string} needle - needle to look for where content will be inserted
* @param {string} content - content to be written
*/
rewriteFile(filePath, needle, content) {
try {
jhipsterUtils.rewriteFile({
file: filePath,
needle,
splicable: [
content
]
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required needle. File rewrite failed.\n'));
this.debug('Error:', e);
}
}
/**
* Replace the pattern/regex with provided content
*
* @param {string} filePath - path of the source file to rewrite
* @param {string} pattern - pattern to look for where content will be replaced
* @param {string} content - content to be written
* @param {string} regex - true if pattern is regex
*/
replaceContent(filePath, pattern, content, regex) {
try {
jhipsterUtils.replaceContent({
file: filePath,
pattern,
content,
regex
}, this);
} catch (e) {
this.log(chalk.yellow('\nUnable to find ') + filePath + chalk.yellow(' or missing required pattern. File rewrite failed.\n') + e);
this.debug('Error:', e);
}
}
/**
* Register a module configuration to .jhipster/modules/jhi-hooks.json
*
* @param {string} npmPackageName - npm package name of the generator
* @param {string} hookFor - from which JHipster generator this should be hooked ( 'entity' or 'app')
* @param {string} hookType - where to hook this at the generator stage ( 'pre' or 'post')
* @param {string} callbackSubGenerator[optional] - sub generator to invoke, if this is not given the module's main generator will be called, i.e app
* @param {string} description[optional] - description of the generator
*/
registerModule(npmPackageName, hookFor, hookType, callbackSubGenerator, description) {
try {
let modules;
let error;
let duplicate;
const moduleName = _.startCase(npmPackageName.replace(`${GENERATOR_JHIPSTER}-`, ''));
const generatorName = npmPackageName.replace('generator-', '');
const generatorCallback = `${generatorName}:${callbackSubGenerator || 'app'}`;
const moduleConfig = {
name: `${moduleName} generator`,
npmPackageName,
description: description || `A JHipster module to generate ${moduleName}`,
hookFor,
hookType,
generatorCallback
};
try {
// if file is not present, we got an empty list, no exception
modules = this.fs.readJSON(MODULES_HOOK_FILE, []);
duplicate = _.findIndex(modules, moduleConfig) !== -1;
} catch (err) {
error = true;
this.log(chalk.red('The JHipster module configuration file could not be read!'));
this.debug('Error:', err);
}
if (!error && !duplicate) {
modules.push(moduleConfig);
this.fs.writeJSON(MODULES_HOOK_FILE, modules, null, 4);
}
} catch (err) {
this.log(`\n${chalk.bold.red('Could not add jhipster module configuration')}`);
this.debug('Error:', err);
}
}
/**
* Add configuration to Entity.json files
*
* @param {string} file - configuration file name for the entity
* @param {string} key - key to be added or updated
* @param {object} value - value to be added
*/
updateEntityConfig(file, key, value) {
try {
const entityJson = this.fs.readJSON(file);
entityJson[key] = value;
this.fs.writeJSON(file, entityJson, null, 4);
} catch (err) {
this.log(chalk.red('The JHipster entity configuration file could not be read!') + err);
this.debug('Error:', err);
}
}
/**
* get the module hooks config json
*/
getModuleHooks() {
let modulesConfig = [];
try {
if (shelljs.test('-f', MODULES_HOOK_FILE)) {
modulesConfig = this.fs.readJSON(MODULES_HOOK_FILE);
}
} catch (err) {
this.log(chalk.red('The module configuration file could not be read!'));
}
return modulesConfig;
}
/**
* Call all the module hooks with the given options.
* @param {string} hookFor - "app" or "entity"
* @param {string} hookType - "pre" or "post"
* @param {any} options - the options to pass to the hooks
* @param {function} cb - callback to trigger at the end
*/
callHooks(hookFor, hookType, options, cb) {
const modules = this.getModuleHooks();
// run through all module hooks, which matches the hookFor and hookType
modules.forEach((module) => {
this.debug('Composing module with config:', module);
if (module.hookFor === hookFor && module.hookType === hookType) {
// compose with the modules callback generator
const hook = module.generatorCallback.split(':')[1];
try {
this.composeExternalModule(module.npmPackageName, hook || 'app', options);
} catch (e) {
this.log(chalk.red('Could not compose module ') + chalk.bold.yellow(module.npmPackageName) +
chalk.red('. \nMake sure you have installed the module with ') + chalk.bold.yellow(`'npm install -g ${module.npmPackageName}'`));
this.debug('ERROR:', e);
}
}
});
this.debug('calling callback');
cb && cb();
}
/**
* Compose an external generator with Yeoman.
* @param {string} npmPackageName - package name
* @param {string} subGen - sub generator name
* @param {any} options - options to pass
*/
composeExternalModule(npmPackageName, subGen, options) {
let generatorTocall = path.join(process.cwd(), 'node_modules', npmPackageName, 'generators', subGen);
try {
if (!fs.existsSync(generatorTocall)) {
this.debug('using global module as local version could not be found in node_modules');
generatorTocall = path.join(npmPackageName, 'generators', subGen);
}
this.debug('Running yeoman compose with options: ', generatorTocall, options);
this.composeWith(require.resolve(generatorTocall), options);
} catch (err) {
this.debug('ERROR:', err);
const generatorName = npmPackageName.replace('generator-', '');
const generatorCallback = `${generatorName}:${subGen}`;
// Fallback for legacy modules
this.debug('Running yeoman legacy compose with options: ', generatorCallback, options);
this.composeWith(generatorCallback, options);
}
}
/**
* Get a name suitable for microservice
* @param {string} microserviceName
*/
getMicroserviceAppName(microserviceName) {
return _.camelCase(microserviceName) + (microserviceName.endsWith('App') ? '' : 'App');
}
/**
* Load an entity configuration file into context.
*/
loadEntityJson(fromPath = this.context.fromPath) {
const context = this.context;
try {
context.fileData = this.fs.readJSON(fromPath);
} catch (err) {
this.debug('Error:', err);
this.error(chalk.red('\nThe entity configuration file could not be read!\n'));
}
context.relationships = context.fileData.relationships || [];
context.fields = context.fileData.fields || [];
context.haveFieldWithJavadoc = false;
context.fields.forEach((field) => {
if (field.javadoc) {
context.haveFieldWithJavadoc = true;
}
});
context.changelogDate = context.fileData.changelogDate;
context.dto = context.fileData.dto;
context.service = context.fileData.service;
context.fluentMethods = context.fileData.fluentMethods;
context.clientRootFolder = context.fileData.clientRootFolder;
context.pagination = context.fileData.pagination;
context.searchEngine = context.fileData.searchEngine || context.searchEngine;
context.javadoc = context.fileData.javadoc;
context.entityTableName = context.fileData.entityTableName;
context.jhiPrefix = context.fileData.jhiPrefix || context.jhiPrefix;
context.skipCheckLengthOfIdentifier = context.fileData.skipCheckLengthOfIdentifier || context.skipCheckLengthOfIdentifier;
context.jhiTablePrefix = this.getTableName(context.jhiPrefix);
this.copyFilteringFlag(context.fileData, context, context);
if (_.isUndefined(context.entityTableName)) {
this.warning(`entityTableName is missing in .jhipster/${context.name}.json, using entity name as fallback`);
context.entityTableName = this.getTableName(context.name);
}
if (jhiCore.isReservedTableName(context.entityTableName, context.prodDatabaseType)) {
context.entityTableName = `${context.jhiTablePrefix}_${context.entityTableName}`;
}
context.fields.forEach((field) => {
context.fieldNamesUnderscored.push(_.snakeCase(field.fieldName));
context.fieldNameChoices.push({ name: field.fieldName, value: field.fieldName });
});
context.relationships.forEach((rel) => {
context.relNameChoices.push({ name: `${rel.relationshipName}:${rel.relationshipType}`, value: `${rel.relationshipName}:${rel.relationshipType}` });
});
if (context.fileData.angularJSSuffix !== undefined) {
context.entityAngularJSSuffix = context.fileData.angularJSSuffix;
}
context.useMicroserviceJson = context.useMicroserviceJson || !_.isUndefined(context.fileData.microserviceName);
if (context.applicationType === 'gateway' && context.useMicroserviceJson) {
context.microserviceName = context.fileData.microserviceName;
if (!context.microserviceName) {
this.error(chalk.red('Microservice name for the entity is not found. Entity cannot be generated!'));
}
context.microserviceAppName = this.getMicroserviceAppName(context.microserviceName);
context.skipServer = true;
}
}
/**
* get an entity from the configuration file
* @param {string} file - configuration file name for the entity
*/
getEntityJson(file) {
let entityJson = null;
try {
if (this.context.microservicePath) {
entityJson = this.fs.readJSON(path.join(this.context.microservicePath, JHIPSTER_CONFIG_DIR, `${_.upperFirst(file)}.json`));
} else {
entityJson = this.fs.readJSON(path.join(JHIPSTER_CONFIG_DIR, `${_.upperFirst(file)}.json`));
}
} catch (err) {
this.log(chalk.red(`The JHipster entity configuration file could not be read for file ${file}!`) + err);
this.debug('Error:', err);
}
return entityJson;
}
/**
* get sorted list of entities according to changelog date (i.e. the order in which they were added)
*/
getExistingEntities() {
const entities = [];
function isBefore(e1, e2) {
return e1.definition.changelogDate - e2.definition.changelogDate;
}
if (!shelljs.test('-d', JHIPSTER_CONFIG_DIR)) {
return entities;
}
return shelljs.ls(path.join(JHIPSTER_CONFIG_DIR, '*.json')).reduce((acc, file) => {
try {
const definition = jhiCore.readEntityJSON(file);
acc.push({ name: path.basename(file, '.json'), definition });
} catch (error) {
// not an entity file / malformed?
this.warning(`Unable to parse entity file ${file}`);
this.debug('Error:', error);
}
return acc;
}, entities).sort(isBefore);
}
/**
* Copy i18 files for given language
*
* @param {object} generator - context that can be used as the generator instance or data to process template
* @param {string} webappDir - webapp directory path
* @param {string} fileToCopy - file name to copy
* @param {string} lang - language for which file needs to be copied
*/
copyI18nFilesByName(generator, webappDir, fileToCopy, lang) {
const _this = generator || this;
_this.copy(`${webappDir}i18n/${lang}/${fileToCopy}`, `${webappDir}i18n/${lang}/${fileToCopy}`);
}
/**
* Check if the JHipster version used to generate an existing project is less than the passed version argument
*
* @param {string} version - A valid semver version string
*/
isJhipsterVersionLessThan(version) {
const jhipsterVersion = this.config.get('jhipsterVersion');
if (!jhipsterVersion) {
return true;
}
return semver.lt(jhipsterVersion, version);
}
/**
* executes a Git command using shellJS
* gitExec(args [, options ], callback)
*
* @param {string|array} args - can be an array of arguments or a string command
* @param {object} options[optional] - takes any of child process options
* @param {function} callback - a callback function to be called once process complete, The call back will receive code, stdout and stderr
*/
gitExec(args, options, callback) {
callback = arguments[arguments.length - 1]; // eslint-disable-line prefer-rest-params
if (arguments.length < 3) {
options = {};
}
if (options.async === undefined) options.async = true;
if (options.silent === undefined) options.silent = true;
if (options.trace === undefined) options.trace = true;
if (!Array.isArray(args)) {
args = [args];
}
const command = `git ${args.join(' ')}`;
if (options.trace) {
this.info(command);
}
shelljs.exec(command, options, callback);
}
/**
* get a table name in JHipster preferred style.
*
* @param {string} value - table name string
*/
getTableName(value) {
return this.hibernateSnakeCase(value);
}
/**
* get a table column name in JHipster preferred style.
*
* @param {string} value - table column name string
*/
getColumnName(value) {
return this.hibernateSnakeCase(value);
}
/**
* get a table column names plural form in JHipster preferred style.
*
* @param {string} value - table column name string
*/
getPluralColumnName(value) {
return this.getColumnName(pluralize(value));
}
/**
* get a table name for joined tables in JHipster preferred style.
*
* @param {string} entityName - name of the entity
* @param {string} relationshipName - name of the related entity
* @param {string} prodDatabaseType - database type
*/
getJoinTableName(entityName, relationshipName, prodDatabaseType) {
const joinTableName = `${this.getTableName(entityName)}_${this.getTableName(relationshipName)}`;
let limit = 0;
if (prodDatabaseType === 'oracle' && joinTableName.length > 30 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated join table "${joinTableName}" is too long for Oracle (which has a 30 characters limit). It will be truncated!`);
limit = 30;
} else if (prodDatabaseType === 'mysql' && joinTableName.length > 64 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated join table "${joinTableName}" is too long for MySQL (which has a 64 characters limit). It will be truncated!`);
limit = 64;
}
if (limit > 0) {
const halfLimit = Math.floor(limit / 2);
const entityTable = _.snakeCase(this.getTableName(entityName).substring(0, halfLimit));
const relationTable = _.snakeCase(this.getTableName(relationshipName).substring(0, halfLimit - 1));
return `${entityTable}_${relationTable}`;
}
return joinTableName;
}
/**
* get a constraint name for tables in JHipster preferred style.
*
* @param {string} entityName - name of the entity
* @param {string} relationshipName - name of the related entity
* @param {string} prodDatabaseType - database type
* @param {boolean} noSnakeCase - do not convert names to snakecase
*/
getConstraintName(entityName, relationshipName, prodDatabaseType, noSnakeCase) {
let constraintName;
if (noSnakeCase) {
constraintName = `fk_${entityName}_${relationshipName}_id`;
} else {
constraintName = `fk_${this.getTableName(entityName)}_${this.getTableName(relationshipName)}_id`;
}
let limit = 0;
if (prodDatabaseType === 'oracle' && constraintName.length > 30 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated constraint name "${constraintName}" is too long for Oracle (which has a 30 characters limit). It will be truncated!`);
limit = 28;
} else if (prodDatabaseType === 'mysql' && constraintName.length > 64 && !this.skipCheckLengthOfIdentifier) {
this.warning(`The generated constraint name "${constraintName}" is too long for MySQL (which has a 64 characters limit). It will be truncated!`);
limit = 62;
}
if (limit > 0) {
const halfLimit = Math.floor(limit / 2);
const entityTable = noSnakeCase ? entityName.substring(0, halfLimit) : _.snakeCase(this.getTableName(entityName).substring(0, halfLimit));
const relationTable = noSnakeCase ? relationshipName.substring(0, halfLimit - 1) : _.snakeCase(this.getTableName(relationshipName).substring(0, halfLimit - 1));
return `${entityTable}_${relationTable}_id`;
}
return constraintName;
}
/**
* Print an error message.
*
* @param {string} msg - message to print
*/
error(msg) {
this.env.error(`${chalk.red.bold('ERROR!')} ${msg}`);
}
/**
* Print a warning message.
*
* @param {string} msg - message to print
*/
warning(msg) {
this.log(`${chalk.yellow.bold('WARNING!')} ${msg}`);
}
/**
* Print an info message.
*
* @param {string} msg - message to print
*/
info(msg) {
this.log.info(msg);
}
/**
* Print a success message.
*
* @param {string} msg - message to print
*/
success(msg) {
this.log.ok(msg);
}
/**
* Generate a KeyStore for uaa authorization server.
*/
generateKeyStore() {
const done = this.async();
const keyStoreFile = `${SERVER_MAIN_RES_DIR}keystore.jks`;
if (this.fs.exists(keyStoreFile)) {
this.log(chalk.cyan(`\nKeyStore '${keyStoreFile}' already exists. Leaving unchanged.\n`));
done();
} else {
shelljs.mkdir('-p', SERVER_MAIN_RES_DIR);
const javaHome = shelljs.env.JAVA_HOME;
let keytoolPath = '';
if (javaHome) {
keytoolPath = `${javaHome}/bin/`;
}
shelljs.exec(
`"${keytoolPath}keytool" -genkey -noprompt ` +
'-keyalg RSA ' +
'-alias selfsigned ' +
`-keystore ${keyStoreFile} ` +
'-storepass password ' +
'-keypass password ' +
'-keysize 2048 ' +
`-dname "CN=Java Hipster, OU=Development, O=${this.packageName}, L=, ST=, C="`
, (code) => {
if (code !== 0) {
this.error('\nFailed to create a KeyStore with \'keytool\'', code);
} else {
this.log(chalk.green(`\nKeyStore '${keyStoreFile}' generated successfully.\n`));
}
done();
}
);
}
}
/**
* Prints a JHipster logo.
*/
printJHipsterLogo() {
this.log('\n');
this.log(`${chalk.green(' ██╗')}${chalk.red(' ██╗ ██╗ ████████╗ ███████╗ ██████╗ ████████╗ ████████╗ ███████╗')}`);
this.log(`${chalk.green(' ██║')}${chalk.red(' ██║ ██║ ╚══██╔══╝ ██╔═══██╗ ██╔════╝ ╚══██╔══╝ ██╔═════╝ ██╔═══██╗')}`);
this.log(`${chalk.green(' ██║')}${chalk.red(' ████████║ ██║ ███████╔╝ ╚█████╗ ██║ ██████╗ ███████╔╝')}`);
this.log(`${chalk.green(' ██╗ ██║')}${chalk.red(' ██╔═══██║ ██║ ██╔════╝ ╚═══██╗ ██║ ██╔═══╝ ██╔══██║')}`);
this.log(`${chalk.green(' ╚██████╔╝')}${chalk.red(' ██║ ██║ ████████╗ ██║ ██████╔╝ ██║ ████████╗ ██║ ╚██╗')}`);
this.log(`${chalk.green(' ╚═════╝ ')}${chalk.red(' ╚═╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═╝')}\n`);
this.log(chalk.yellow.bold('\n\n Change in the generator \n\n'));
this.log(chalk.white.bold(' https://www.jhipster.tech\n'));
this.log(chalk.white('Welcome to the JHipster Generator ') + chalk.yellow(`v${packagejs.version}`));
this.log(chalk.green(' _______________________________________________________________________________________________________________\n'));
this.log(chalk.white(` If you find JHipster useful consider supporting our collective ${chalk.yellow('https://opencollective.com/generator-jhipster')}`));
this.log(chalk.white(` Documentation for creating an application: ${chalk.yellow('https://www.jhipster.tech/creating-an-app/')}`));
this.log(chalk.green(' _______________________________________________________________________________________________________________\n'));
this.log(chalk.white(`Application files will be generated in folder: ${chalk.yellow(process.cwd())}`));
}
/**
* Checks if there is a newer JHipster version available.
*/
checkForNewVersion() {
try {
const done = this.async();
shelljs.exec(`npm show ${GENERATOR_JHIPSTER} version`, { silent: true }, (code, stdout, stderr) => {
if (!stderr && semver.lt(packagejs.version, stdout)) {
this.log(`${chalk.yellow(' ______________________________________________________________________________\n\n') +
chalk.yellow(' JHipster update available: ') + chalk.green.bold(stdout.replace('\n', '')) + chalk.gray(` (current: ${packagejs.version})`)}\n`);
if (this.useYarn) {
this.log(chalk.yellow(` Run ${chalk.magenta(`yarn global upgrade ${GENERATOR_JHIPSTER}`)} to update.\n`));
} else {
this.log(chalk.yellow(` Run ${chalk.magenta(`npm install -g ${GENERATOR_JHIPSTER}`)} to update.\n`));
}
this.log(chalk.yellow(' ______________________________________________________________________________\n'));
}
done();
});
} catch (err) {
this.debug('Error:', err);
// fail silently as this function doesn't affect normal generator flow
}
}
/**
* get the Angular application name.
* @param {string} baseName of application
*/
getAngularAppName(baseName = this.baseName) {
const name = _.camelCase(baseName) + (baseName.endsWith('App') ? '' : 'App');
return name.match(/^\d/) ? 'App' : name;
}
/**
* get the Angular 2+ application name.
* @param {string} baseName of application
*/
getAngularXAppName(baseName = this.baseName) {
const name = this.upperFirstCamelCase(baseName);
return name.match(/^\d/) ? 'App' : name;
}
/**
* get the an upperFirst camelCase value.
* @param {string} value string to convert
*/
upperFirstCamelCase(value) {
return _.upperFirst(_.camelCase(value));
}
/**
* get the java main class name.
* @param {string} baseName of application
*/
getMainClassName(baseName = this.baseName) {
const main = _.upperFirst(this.getMicroserviceAppName(baseName));
const acceptableForJava = new RegExp('^[A-Z][a-zA-Z0-9_]*$');
return acceptableForJava.test(main) ? main : 'Application';
}
/**
* ask a prompt for apps name.
*
* @param {object} generator - generator instance to use
*/
askModuleName(generator) {
const done = generator.async();
const defaultAppBaseName = this.getDefaultAppName();
generator.prompt({
type: 'input',
name: 'baseName',
validate: (input) => {
if (!(/^([a-zA-Z0-9_]*)$/.test(input))) {
return 'Your application name cannot contain special characters or a blank space';
} else if (generator.applicationType === 'microservice' && /_/.test(input)) {
return 'Your microservice name cannot contain underscores as this does not meet the URI spec';
} else if (input === 'application') {
return 'Your application name cannot be named \'application\' as this is a reserved name for Spring Boot';
}
return true;
},
message: 'What is the base name of your application?',
default: defaultAppBaseName
}).then((prompt) => {
generator.baseName = prompt.baseName;
done();
});
}
/**
* ask a prompt for i18n option.
*
* @param {object} generator - generator instance to use
*/
aski18n(generator) {
const languageOptions = this.getAllSupportedLanguageOptions();
const done = generator.async();
const prompts = [
{
type: 'confirm',
name: 'enableTranslation',
message: 'Would you like to enable internationalization support?',
default: true
},
{
when: response => response.enableTranslation === true,
type: 'list',
name: 'nativeLanguage',
message: 'Please choose the native language of the application',
choices: languageOptions,
default: 'en',
store: true
},
{
when: response => response.enableTranslation === true,
type: 'checkbox',
name: 'languages',
message: 'Please choose additional languages to install',
choices: response => _.filter(languageOptions, o => o.value !== response.nativeLanguage)
}
];
generator.prompt(prompts).then((prompt) => {
generator.enableTranslation = prompt.enableTranslation;
generator.nativeLanguage = prompt.nativeLanguage;
generator.languages = [prompt.nativeLanguage].concat(prompt.languages);
done();
});
}
/**
* compose using the language sub generator.
*
* @param {object} generator - generator instance to use
* @param {object} configOptions - options to pass to the generator
* @param {String} type - server | client
*/
composeLanguagesSub(generator, configOptions, type) {
if (generator.enableTranslation) {
// skip server if app type is client
const skipServer = type && type === 'client';
// skip client if app type is server
const skipClient = type && type === 'server';
generator.composeWith(require.resolve('./languages'), {
configOptions,
'skip-install': true,
'skip-server': skipServer,
'skip-client': skipClient,
languages: generator.languages,
force: generator.options.force,
debug: generator.options.debug
});
}
}
/**
* @Deprecated
* Add numbering to a question
*
* @param {String} msg - question text
* @param {boolean} cond - increment question
*/
getNumberedQuestion(msg, cond) {
return msg;
}
/**
* build a generated application.
*
* @param {String} buildTool - maven | gradle
* @param {String} profile - dev | prod
* @param {Function} cb - callback when build is complete
*/
buildApplication(buildTool, profile, cb) {
let buildCmd = 'mvnw verify -DskipTests=true -B';
if (buildTool === 'gradle') {
buildCmd = 'gradlew bootWar -x test';
}
if (os.platform() !== 'win32') {
buildCmd = `./${buildCmd}`;
}
buildCmd += ` -P${profile}`;
const child = {};
child.stdout = exec(buildCmd, { maxBuffer: 1024 * 10000 }, cb).stdout;
child.buildCmd = buildCmd;
return child;
}
/**
* write the given files using provided config.
*
* @param {object} files - files to write
* @param {object} generator - the generator instance to use
* @param {boolean} returnFiles - weather to return the generated file list or to write them
* @param {string} prefix - pefix to add to path
*/
writeFilesToDisk(files, generator, returnFiles, prefix) {
const _this = generator || this;
const filesOut = [];
const startTime = new Date();
// using the fastest method for iterations
for (let i = 0, blocks = Object.keys(files); i < blocks.length; i++) {
for (let j = 0, blockTemplates = files[blocks[i]]; j < blockTemplates.length; j++) {
const blockTemplate = blockTemplates[j];
if (!blockTemplate.condition || blockTemplate.condition(_this)) {
const path = blockTemplate.path ? blockTemplate.path : '';
blockTemplate.templates.forEach((templateObj) => {
let templatePath = path;
let method = 'template';
let useTemplate = false;
let options = {};
let templatePathTo;
if (typeof templateObj === 'string') {
templatePath += templateObj;
} else {
templatePath += templateObj.file;
method = templateObj.method ? templateObj.method : method;
useTemplate = templateObj.template ? templateObj.template : useTemplate;
options = templateObj.options ? templateObj.options : options;
}
if (templateObj && templateObj.renameTo) {
templatePathTo = path + templateObj.renameTo(_this);
} else {
templatePathTo = templatePath.replace(/([/])_|^_/, '$1');
templatePathTo = templatePath.replace('.ejs', '');
}
filesOut.push(templatePathTo);
if (!returnFiles) {
let templatePathFrom = prefix ? `${prefix}/${templatePath}` : templatePath;
if (
!templateObj.noEjs && !templatePathFrom.endsWith('.png')
&& !templatePathFrom.endsWith('.jpg') && !templatePathFrom.endsWith('.gif')
&& !templatePathFrom.endsWith('.svg') && !templatePathFrom.endsWith('.ico')
) {
templatePathFrom = `${templatePathFrom}.ejs`;
}
// if (method === 'template')
_this[method](templatePathFrom, templatePathTo, _this, options, useTemplate);
}
});
}
}
}
this.debug(`Time taken to write files: ${new Date() - startTime}ms`);
return filesOut;
}
/**
* Setup client instance level options from context.
* @param {any} generator - generator instance
* @param {any} context - context to use default is generator instance
*/
setupClientOptions(generator, context = generator) {
generator.skipServer = context.configOptions.skipServer || context.config.get('skipServer');
generator.skipUserManagement = context.configOptions.skipUserManagement || context.options['skip-user-management'] || context.config.get('skipUserManagement');
generator.authenticationType = context.options.auth || context.configOptions.authenticationType || context.config.get('authenticationType');
if (generator.authenticationType === 'oauth2') {
generator.skipUserManagement = true;
}
const uaaBaseName = context.options.uaaBaseName || context.configOptions.uaaBaseName || context.options['uaa-base-name'] || context.config.get('uaaBaseName');
if (context.options.auth === 'uaa' && _.isNil(uaaBaseName)) {
generator.error('when using --auth uaa, a UAA basename must be provided with --uaa-base-name');
}
generator.uaaBaseName = uaaBaseName;
generator.buildTool = context.options.build;
generator.websocket = context.options.websocket;
generator.devDatabaseType = context.options.db || context.configOptions.devDatabaseType || context.config.get('devDatabaseType');
generator.prodDatabaseType = context.options.db || context.configOptions.prodDatabaseType || context.config.get('prodDatabaseType');
generator.databaseType = generator.getDBTypeFromDBValue(context.options.db) || context.configOptions.databaseType || context.config.get('databaseType');
generator.searchEngine = context.options['search-engine'] || context.config.get('searchEngine');
generator.cacheProvider = context.options['cache-provider'] || context.config.get('cacheProvider') || context.config.get('hibernateCache') || 'no';
generator.enableHibernateCache = context.options['hb-cache'] || context.config.get('enableHibernateCache') || (context.config.get('hibernateCache') !== undefined && context.config.get('hibernateCache') !== 'no');
generator.otherModules = context.configOptions.otherModules || [];
generator.jhiPrefix = context.configOptions.jhiPrefix || context.config.get('jhiPrefix') || context.options['jhi-prefix'];
generator.jhiPrefixCapitalized = _.upperFirst(generator.jhiPrefix);
generator.jhiPrefixDashed = _.kebabCase(generator.jhiPrefix);
generator.testFrameworks = [];
if (context.options.protractor) generator.testFrameworks.push('protractor');
generator.baseName = context.configOptions.baseName;
generator.logo = context.configOptions.logo;
generator.useYarn = context.configOptions.useYarn = !context.options.npm;
generator.clientPackageManager = context.configOptions.clientPackageManager;
generator.isDebugEnabled = context.configOptions.isDebugEnabled || context.options.debug;
generator.experimental = context.configOptions.experimental || context.options.experimental;
}
/**
* Setup Server instance level options from context.
* @param {any} generator - generator instance
* @param {any} context - context to use default is generator instance
*/
setupServerOptions(generator, context = generator) {
generator.skipClient = !context.options['client-hook'] || context.configOptions.skipClient || context.config.get('skipClient');
generator.skipUserManagement = context.configOptions.skipUserManagement || context.options['skip-user-management'] || context.config.get('skipUserManagement');
generator.enableTranslation = context.options.i18n || context.configOptions.enableTranslation || context.config.get('enableTranslation');
generator.testFrameworks = [];
if (context.options.gatling) generator.testFrameworks.push('gatling');
if (context.options.cucumber) generator.testFrameworks.push('cucumber');
generator.logo = context.configOptions.logo;
generator.baseName = context.configOptions.baseName;
generator.clientPackageManager = context.configOptions.clientPackageManager;
generator.isDebugEnabled = context.configOptions.isDebugEnabled || context.options.debug;
generator.experimental = context.configOptions.experimental || context.options.experimental;
}
/**
* Setup Entity instance level options from context.
* @param {any} generator - generator instance
* @param {any} context - context to use default is generator instance
* @param {any} dest - destination context to use default is generator instance
*/
setupEntityOptions(generator, context = generator, dest = generator) {
dest.name = context.options.name;
// remove extension if feeding json files
if (dest.name !== undefined) {
dest.name = dest.name.replace('.json', '');
}
dest.regenerate = context.options.regenerate;
dest.fluentMethods = context.options['fluent-methods'];
dest.skipCheckLengthOfIdentifier = context.options['skip-check-length-of-identifier'];
dest.entityTableName = generator.getTableName(context.options['table-name'] || dest.name);
dest.entityNameCapitalized = _.upperFirst(dest.name);
dest.entityAngularJSSuffix = context.options['angular-suffix'];
dest.clientRootFolder = context.options['skip-ui-grouping'] ? '' : context.options['client-root-folder'];
dest.isDebugEnabled = context.options.debug;
generator.experimental = context.options.experimental;
if (dest.entityAngularJSSuffix && !dest.entityAngularJSSuffix.startsWith('-')) {
dest.entityAngularJSSuffix = `-${dest.entityAngularJSSuffix}`;
}
dest.rootDir = generator.destinationRoot();
// enum-specific consts
dest.enums = [];
dest.existingEnum = false;
dest.fieldNamesUnderscored = ['id'];
// these variable hold field and relationship names for question options during update
dest.fieldNameChoices = [];
dest.relNameChoices = [];
}
};
| remove log statement
| generators/generator-base.js | remove log statement | <ide><path>enerators/generator-base.js
<ide> this.log(`${chalk.green(' ██║')}${chalk.red(' ████████║ ██║ ███████╔╝ ╚█████╗ ██║ ██████╗ ███████╔╝')}`);
<ide> this.log(`${chalk.green(' ██╗ ██║')}${chalk.red(' ██╔═══██║ ██║ ██╔════╝ ╚═══██╗ ██║ ██╔═══╝ ██╔══██║')}`);
<ide> this.log(`${chalk.green(' ╚██████╔╝')}${chalk.red(' ██║ ██║ ████████╗ ██║ ██████╔╝ ██║ ████████╗ ██║ ╚██╗')}`);
<del> this.log(`${chalk.green(' ╚═════╝ ')}${chalk.red(' ╚═╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═╝')}\n`);
<del>
<del> this.log(chalk.yellow.bold('\n\n Change in the generator \n\n'));
<del>
<add> this.log(`${chalk.green(' ╚═════╝ ')}${chalk.red(' ╚═╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═╝')}\n`);
<ide> this.log(chalk.white.bold(' https://www.jhipster.tech\n'));
<ide> this.log(chalk.white('Welcome to the JHipster Generator ') + chalk.yellow(`v${packagejs.version}`));
<ide> this.log(chalk.green(' _______________________________________________________________________________________________________________\n')); |
|
Java | mit | 36be58f775f2eb8764cb5bbd8d1f764af711eece | 0 | Matsv/ViaBackwards | /*
* Copyright (c) 2016 Matsv
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package nl.matsv.viabackwards.protocol.protocol1_12to1_11_1.data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import net.md_5.bungee.api.ChatColor;
import nl.matsv.viabackwards.ViaBackwards;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.data.StoredObject;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.protocols.protocol1_12to1_11_1.Protocol1_12To1_11_1;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;
@Getter
@Setter
@ToString
public class ShoulderTracker extends StoredObject {
private int entityId;
private String leftShoulder;
private String rightShoulder;
public ShoulderTracker(UserConnection user) {
super(user);
}
public void update() {
PacketWrapper wrapper = new PacketWrapper(0x0F, null, getUser());
wrapper.write(Type.STRING, Protocol1_9TO1_8.fixJson(generateString()));
wrapper.write(Type.BYTE, (byte) 2);
try {
wrapper.send(Protocol1_12To1_11_1.class);
} catch (Exception e) {
ViaBackwards.getPlatform().getLogger().severe("Failed to send the shoulder indication");
e.printStackTrace();
}
}
// Does actionbar not support json colors? :(
private String generateString() {
StringBuilder builder = new StringBuilder();
// Empty spaces because the non-json formatting is weird
builder.append(" ");
if (leftShoulder == null)
builder.append(ChatColor.RED).append(ChatColor.BOLD).append("Nothing");
else
builder.append(ChatColor.DARK_GREEN).append(ChatColor.BOLD).append(getName(leftShoulder));
builder.append(ChatColor.DARK_GRAY).append(ChatColor.BOLD).append(" <- ")
.append(ChatColor.GRAY).append(ChatColor.BOLD).append("Shoulders")
.append(ChatColor.DARK_GRAY).append(ChatColor.BOLD).append(" -> ");
if (rightShoulder == null)
builder.append(ChatColor.RED).append(ChatColor.BOLD).append("Nothing");
else
builder.append(ChatColor.DARK_GREEN).append(ChatColor.BOLD).append(getName(rightShoulder));
return builder.toString();
}
private String getName(String current) {
if (current.startsWith("minecraft:"))
current = current.substring(10);
String[] array = current.split("_");
StringBuilder builder = new StringBuilder();
for (String s : array) {
builder.append(s.substring(0, 1).toUpperCase())
.append(s.substring(1))
.append(" ");
}
return builder.toString();
}
}
| core/src/main/java/nl/matsv/viabackwards/protocol/protocol1_12to1_11_1/data/ShoulderTracker.java | /*
* Copyright (c) 2016 Matsv
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package nl.matsv.viabackwards.protocol.protocol1_12to1_11_1.data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import net.md_5.bungee.api.ChatColor;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.data.StoredObject;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.protocols.protocol1_12to1_11_1.Protocol1_12To1_11_1;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;
@Getter
@Setter
@ToString
public class ShoulderTracker extends StoredObject {
private int entityId;
private String leftShoulder;
private String rightShoulder;
public ShoulderTracker(UserConnection user) {
super(user);
}
public void update() {
PacketWrapper wrapper = new PacketWrapper(0x0F, null, getUser());
wrapper.write(Type.STRING, Protocol1_9TO1_8.fixJson(generateString()));
wrapper.write(Type.BYTE, (byte) 2);
try {
wrapper.send(Protocol1_12To1_11_1.class);
} catch (Exception e) {
System.out.println("Failed to send the shoulder indication");
e.printStackTrace();
}
}
// Does actionbar not support json colors? :(
private String generateString() {
StringBuilder builder = new StringBuilder();
// Empty spaces because the non-json formatting is weird
builder.append(" ");
if (leftShoulder == null)
builder.append(ChatColor.RED).append(ChatColor.BOLD).append("Nothing");
else
builder.append(ChatColor.DARK_GREEN).append(ChatColor.BOLD).append(getName(leftShoulder));
builder.append(ChatColor.DARK_GRAY).append(ChatColor.BOLD).append(" <- ")
.append(ChatColor.GRAY).append(ChatColor.BOLD).append("Shoulders")
.append(ChatColor.DARK_GRAY).append(ChatColor.BOLD).append(" -> ");
if (rightShoulder == null)
builder.append(ChatColor.RED).append(ChatColor.BOLD).append("Nothing");
else
builder.append(ChatColor.DARK_GREEN).append(ChatColor.BOLD).append(getName(rightShoulder));
return builder.toString();
}
private String getName(String current) {
if (current.startsWith("minecraft:"))
current = current.substring(10);
String[] array = current.split("_");
StringBuilder builder = new StringBuilder();
for (String s : array) {
builder.append(s.substring(0, 1).toUpperCase())
.append(s.substring(1))
.append(" ");
}
return builder.toString();
}
}
| Change sout to logger
| core/src/main/java/nl/matsv/viabackwards/protocol/protocol1_12to1_11_1/data/ShoulderTracker.java | Change sout to logger | <ide><path>ore/src/main/java/nl/matsv/viabackwards/protocol/protocol1_12to1_11_1/data/ShoulderTracker.java
<ide> import lombok.Setter;
<ide> import lombok.ToString;
<ide> import net.md_5.bungee.api.ChatColor;
<add>import nl.matsv.viabackwards.ViaBackwards;
<ide> import us.myles.ViaVersion.api.PacketWrapper;
<ide> import us.myles.ViaVersion.api.data.StoredObject;
<ide> import us.myles.ViaVersion.api.data.UserConnection;
<ide> try {
<ide> wrapper.send(Protocol1_12To1_11_1.class);
<ide> } catch (Exception e) {
<del> System.out.println("Failed to send the shoulder indication");
<add> ViaBackwards.getPlatform().getLogger().severe("Failed to send the shoulder indication");
<ide> e.printStackTrace();
<ide> }
<ide> } |
|
Java | apache-2.0 | 99b2ecec9e3c317a2570b7d67cd4d5c1281ee5a2 | 0 | safarmer/bazel,ulfjack/bazel,ButterflyNetwork/bazel,werkt/bazel,dropbox/bazel,ButterflyNetwork/bazel,meteorcloudy/bazel,dropbox/bazel,katre/bazel,bazelbuild/bazel,twitter-forks/bazel,bazelbuild/bazel,dslomov/bazel,snnn/bazel,variac/bazel,ulfjack/bazel,dslomov/bazel-windows,dropbox/bazel,dslomov/bazel-windows,damienmg/bazel,bazelbuild/bazel,dslomov/bazel,twitter-forks/bazel,spxtr/bazel,werkt/bazel,damienmg/bazel,dropbox/bazel,damienmg/bazel,spxtr/bazel,variac/bazel,meteorcloudy/bazel,dslomov/bazel,variac/bazel,akira-baruah/bazel,snnn/bazel,dslomov/bazel-windows,cushon/bazel,dslomov/bazel,davidzchen/bazel,ulfjack/bazel,davidzchen/bazel,snnn/bazel,dslomov/bazel,ButterflyNetwork/bazel,damienmg/bazel,spxtr/bazel,spxtr/bazel,snnn/bazel,aehlig/bazel,meteorcloudy/bazel,perezd/bazel,werkt/bazel,dslomov/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,safarmer/bazel,safarmer/bazel,aehlig/bazel,variac/bazel,ulfjack/bazel,twitter-forks/bazel,variac/bazel,dslomov/bazel-windows,aehlig/bazel,variac/bazel,perezd/bazel,dslomov/bazel-windows,cushon/bazel,spxtr/bazel,meteorcloudy/bazel,dslomov/bazel,spxtr/bazel,katre/bazel,bazelbuild/bazel,werkt/bazel,werkt/bazel,katre/bazel,davidzchen/bazel,ulfjack/bazel,aehlig/bazel,perezd/bazel,ButterflyNetwork/bazel,werkt/bazel,dropbox/bazel,damienmg/bazel,perezd/bazel,perezd/bazel,katre/bazel,akira-baruah/bazel,twitter-forks/bazel,aehlig/bazel,davidzchen/bazel,bazelbuild/bazel,katre/bazel,spxtr/bazel,safarmer/bazel,akira-baruah/bazel,snnn/bazel,meteorcloudy/bazel,bazelbuild/bazel,cushon/bazel,snnn/bazel,katre/bazel,davidzchen/bazel,akira-baruah/bazel,twitter-forks/bazel,davidzchen/bazel,variac/bazel,aehlig/bazel,cushon/bazel,snnn/bazel,dropbox/bazel,cushon/bazel,damienmg/bazel,davidzchen/bazel,safarmer/bazel,dslomov/bazel-windows,akira-baruah/bazel,safarmer/bazel,damienmg/bazel,twitter-forks/bazel,akira-baruah/bazel,ulfjack/bazel,perezd/bazel,ButterflyNetwork/bazel,perezd/bazel,meteorcloudy/bazel,ulfjack/bazel,cushon/bazel,meteorcloudy/bazel,aehlig/bazel | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.syntax.BaseFunction;
import com.google.devtools.build.lib.syntax.Environment;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.FuncallExpression;
import com.google.devtools.build.lib.syntax.FunctionSignature;
import com.google.devtools.build.lib.syntax.SkylarkType;
import javax.annotation.Nullable;
/**
* Declared Provider (a constructor for {@link SkylarkClassObject}).
*
* <p>Declared providers can be declared either natively ({@link NativeClassObjectConstructor} or in
* Skylark {@link SkylarkClassObjectConstructor}.
*
* <p>{@link ClassObjectConstructor} serves both as "type identifier" for declared provider
* instances and as a function that can be called to construct a provider.
*
* <p>Prefer to use {@link Key} as a serializable identifier of {@link ClassObjectConstructor}. In
* particular, {@link Key} should be used in all data structures exposed to Skyframe.
*/
@SkylarkModule(
name = "Provider",
doc =
"A constructor for simple value objects, known as provider instances."
+ "<br>"
+ "This value has a dual purpose:"
+ " <ul>"
+ " <li>It is a function that can be called to construct 'struct'-like values:"
+ "<pre class=\"language-python\">DataInfo = provider()\n"
+ "d = DataInfo(x = 2, y = 3)\n"
+ "print(d.x + d.y) # prints 5</pre>"
+ " Note: Some providers, defined internally, do not allow instance creation"
+ " </li>"
+ " <li>It is a <i>key</i> to access a provider instance on a"
+ " <a href=\"lib/Target.html\">Target</a>"
+ "<pre class=\"language-python\">DataInfo = provider()\n"
+ "def _rule_impl(ctx)\n"
+ " ... ctx.attr.dep[DataInfo]</pre>"
+ " </li>"
+ " </ul>"
+ "Create a new <code>Provider</code> using the "
+ "<a href=\"globals.html#provider\">provider</a> function."
)
@Immutable
public abstract class ClassObjectConstructor extends BaseFunction {
protected ClassObjectConstructor(String name,
FunctionSignature.WithValues<Object, SkylarkType> signature,
Location location) {
super(name, signature, location);
}
/**
* Has this {@link ClassObjectConstructor} been exported?
* All native constructors are always exported. Skylark constructors are exported
* if they are assigned to top-level name in a Skylark module.
*/
public abstract boolean isExported();
/**
* Returns a serializable representation of this constructor.
*/
public abstract Key getKey();
/**
* Returns a name of this constructor that should be used in error messages.
*/
public abstract String getPrintableName();
/**
* Returns an error message format for instances.
*
* Must contain one '%s' placeholder for field name.
*/
public abstract String getErrorMessageFormatForInstances();
public SkylarkProviderIdentifier id() {
return SkylarkProviderIdentifier.forKey(getKey());
}
@Override
protected Object call(Object[] args, @Nullable FuncallExpression ast, @Nullable Environment env)
throws EvalException, InterruptedException {
Location loc = ast != null ? ast.getLocation() : Location.BUILTIN;
return createInstanceFromSkylark(args, loc);
}
/**
* Override this method to provide logic that is used to instantiate a declared provider
* from Skylark.
*
* This is a method that is called when a constructor {@code c} is invoked as<br>
* {@code c(arg1 = val1, arg2 = val2, ...)}.
*
* @param args an array of argument values sorted as per the signature
* ({@see BaseFunction#call})
*/
protected abstract SkylarkClassObject createInstanceFromSkylark(Object[] args, Location loc)
throws EvalException;
/**
* A serializable representation of {@link ClassObjectConstructor}.
*/
// todo(vladmos,dslomov): when we allow declared providers in `requiredProviders`,
// we will need to serialize this somehow.
public abstract static class Key {}
}
| src/main/java/com/google/devtools/build/lib/packages/ClassObjectConstructor.java | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.syntax.BaseFunction;
import com.google.devtools.build.lib.syntax.Environment;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.FuncallExpression;
import com.google.devtools.build.lib.syntax.FunctionSignature;
import com.google.devtools.build.lib.syntax.SkylarkType;
import javax.annotation.Nullable;
/**
* Declared Provider (a constructor for {@link SkylarkClassObject}).
*
* <p>Declared providers can be declared either natively ({@link NativeClassObjectConstructor} or in
* Skylark {@link SkylarkClassObjectConstructor}.
*
* <p>{@link ClassObjectConstructor} serves both as "type identifier" for declared provider
* instances and as a function that can be called to construct a provider.
*
* <p>Prefer to use {@link Key} as a serializable identifier of {@link ClassObjectConstructor}. In
* particular, {@link Key} should be used in all data structures exposed to Skyframe.
*/
@SkylarkModule(
name = "Provider",
doc =
"A constructor for simple value objects, known as provider instances."
+ "<br>"
+ "This value has a dual purpose:"
+ " <ul>"
+ " <li>It is a function that can be called to construct 'struct'-like values:"
+ "<pre class=\"language-python\">DataInfo = provider()\n"
+ "d = DataInfo(x = 2, y = 3)\n"
+ "print(d.x + d.y) # prints 5</pre>"
+ " <i>Some providers, defined internally, do not allow instance creation</i>"
+ " </li>"
+ " <li>It is a <i>key</i> to access a provider instance on a"
+ " <a href=\"lib/Target.html\">Target</a>"
+ "<pre class=\"language-python\">DataInfo = provider()\n"
+ "def _rule_impl(ctx)\n"
+ " ... ctx.attr.dep[DataInfo]</pre>"
+ " </li>"
+ " </ul>"
+ "Create a new <code>Provider</code> using the "
+ "<a href=\"globals.html#provider\">provider</a> function."
)
@Immutable
public abstract class ClassObjectConstructor extends BaseFunction {
protected ClassObjectConstructor(String name,
FunctionSignature.WithValues<Object, SkylarkType> signature,
Location location) {
super(name, signature, location);
}
/**
* Has this {@link ClassObjectConstructor} been exported?
* All native constructors are always exported. Skylark constructors are exported
* if they are assigned to top-level name in a Skylark module.
*/
public abstract boolean isExported();
/**
* Returns a serializable representation of this constructor.
*/
public abstract Key getKey();
/**
* Returns a name of this constructor that should be used in error messages.
*/
public abstract String getPrintableName();
/**
* Returns an error message format for instances.
*
* Must contain one '%s' placeholder for field name.
*/
public abstract String getErrorMessageFormatForInstances();
public SkylarkProviderIdentifier id() {
return SkylarkProviderIdentifier.forKey(getKey());
}
@Override
protected Object call(Object[] args, @Nullable FuncallExpression ast, @Nullable Environment env)
throws EvalException, InterruptedException {
Location loc = ast != null ? ast.getLocation() : Location.BUILTIN;
return createInstanceFromSkylark(args, loc);
}
/**
* Override this method to provide logic that is used to instantiate a declared provider
* from Skylark.
*
* This is a method that is called when a constructor {@code c} is invoked as<br>
* {@code c(arg1 = val1, arg2 = val2, ...)}.
*
* @param args an array of argument values sorted as per the signature
* ({@see BaseFunction#call})
*/
protected abstract SkylarkClassObject createInstanceFromSkylark(Object[] args, Location loc)
throws EvalException;
/**
* A serializable representation of {@link ClassObjectConstructor}.
*/
// todo(vladmos,dslomov): when we allow declared providers in `requiredProviders`,
// we will need to serialize this somehow.
public abstract static class Key {}
}
| De-emphasize the note on internal providers.
Fixes #3354.
Change-Id: I1525b5fc6e44cce335744b1d5883be71812003ed
PiperOrigin-RevId: 162672218
| src/main/java/com/google/devtools/build/lib/packages/ClassObjectConstructor.java | De-emphasize the note on internal providers. | <ide><path>rc/main/java/com/google/devtools/build/lib/packages/ClassObjectConstructor.java
<ide> + "<pre class=\"language-python\">DataInfo = provider()\n"
<ide> + "d = DataInfo(x = 2, y = 3)\n"
<ide> + "print(d.x + d.y) # prints 5</pre>"
<del> + " <i>Some providers, defined internally, do not allow instance creation</i>"
<add> + " Note: Some providers, defined internally, do not allow instance creation"
<ide> + " </li>"
<ide> + " <li>It is a <i>key</i> to access a provider instance on a"
<ide> + " <a href=\"lib/Target.html\">Target</a>" |
|
Java | bsd-2-clause | 9f5f0650f742d46447e529979e19e8a3f2ee3762 | 0 | scenerygraphics/SciView,scenerygraphics/SciView | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2018 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Future;
import graphics.scenery.Mesh;
import graphics.scenery.Node;
import graphics.scenery.volumes.Volume;
import org.scijava.display.Display;
import org.scijava.display.DisplayService;
import org.scijava.event.EventService;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.script.ScriptService;
import org.scijava.service.AbstractService;
import org.scijava.service.Service;
import org.scijava.thread.ThreadService;
import sc.iview.display.SciViewDisplay;
/**
* Default service for rendering inside Scenery.
*
* @author Kyle Harrington
*/
@Plugin(type = Service.class, name="sciViewService")
public class DefaultSciViewService extends AbstractService implements SciViewService {
/* Parameters */
@Parameter
private DisplayService displayService;
@Parameter
private EventService eventService;
@Parameter
private ScriptService scriptService;
@Parameter
private ThreadService threadService;
@Parameter
private LogService logService;
/* Instance variables */
private List<SciView> sceneryViewers = new LinkedList<>();
/* Methods */
@Override
public SciView getActiveSciView() {
SciViewDisplay d = displayService.getActiveDisplay( SciViewDisplay.class );
if( d != null ) {
// We also have to check if the Viewer has been initialized
// and we're doing it the bad way by polling. Replace if you want
SciView sv = d.get( 0 );
while( !sv.isInitialized() ) {
try {
Thread.sleep( 20 );
} catch( InterruptedException e ) {
logService.trace( e );
}
}
return sv;
}
return null;
}
@Override
public SciView getSciView( String name ) {
for( final SciView sceneryViewer : sceneryViewers ) {
if( name.equalsIgnoreCase( sceneryViewer.getName() ) ) {
return sceneryViewer;
}
}
return null;
}
public SciView makeSciView() throws Exception {
SciView sv = new SciView( getContext() );
Future<?> svThread = threadService.run(() -> sv.main());
while( !sv.isInitialized() &&
!svThread.isDone() &&
!svThread.isCancelled() ) {
try {
Thread.sleep( 20 );
} catch( InterruptedException e ) {
logService.trace( e );
}
}
if( svThread.isCancelled() || svThread.isDone() ){
svThread.get();// Trigger an exception from the Future if possible
throw new Exception("SciView thread is done or had an error");
}
Display<?> display = displayService.createDisplay( sv );
displayService.setActiveDisplay( display );
sv.setDisplay( display );
return sv;
}
@Override
public void createSciView() throws Exception {
SciView v = makeSciView();
sceneryViewers.add( v );
}
@Override
public int numSciView() {
return sceneryViewers.size();
}
@Override
public void close(SciView sciView) {
sceneryViewers.remove(sciView);
SciViewDisplay d = displayService.getActiveDisplay( SciViewDisplay.class );
if( d != null ) {
d.close();
}
}
@Override
public void initialize() {
scriptService.addAlias(SciView.class);
scriptService.addAlias("Mesh", Mesh.class);
scriptService.addAlias("Node", Node.class);
scriptService.addAlias("Volume", Volume.class);
}
/* Event Handlers */
@Override
public SciView getOrCreateActiveSciView() throws Exception {
SciView sv = getActiveSciView();
if( sv == null ) {
// Make one
sv = makeSciView();
sceneryViewers.add( sv );
}
return sv;
// Might need to change to return a SciViewDisplay instead, if downstream code needs it
}
}
| src/main/java/sc/iview/DefaultSciViewService.java | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2018 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Future;
import graphics.scenery.Mesh;
import graphics.scenery.Node;
import graphics.scenery.volumes.Volume;
import org.scijava.display.Display;
import org.scijava.display.DisplayService;
import org.scijava.event.EventService;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.script.ScriptService;
import org.scijava.service.AbstractService;
import org.scijava.service.Service;
import org.scijava.thread.ThreadService;
import sc.iview.display.SciViewDisplay;
/**
* Default service for rendering inside Scenery.
*
* @author Kyle Harrington
*/
@Plugin(type = Service.class, name="sciViewService")
public class DefaultSciViewService extends AbstractService implements SciViewService {
/* Parameters */
@Parameter
private DisplayService displayService;
@Parameter
private EventService eventService;
@Parameter
private ScriptService scriptService;
@Parameter
private ThreadService threadService;
@Parameter
private LogService logService;
/* Instance variables */
private List<SciView> sceneryViewers = new LinkedList<>();
/* Methods */
@Override
public SciView getActiveSciView() {
SciViewDisplay d = displayService.getActiveDisplay( SciViewDisplay.class );
if( d != null ) {
// We also have to check if the Viewer has been initialized
// and we're doing it the bad way by polling. Replace if you want
SciView sv = d.get( 0 );
while( !sv.isInitialized() ) {
try {
Thread.sleep( 20 );
} catch( InterruptedException e ) {
logService.trace( e );
}
}
return sv;
}
return null;
}
@Override
public SciView getSciView( String name ) {
for( final SciView sceneryViewer : sceneryViewers ) {
if( name.equalsIgnoreCase( sceneryViewer.getName() ) ) {
return sceneryViewer;
}
}
return null;
}
public SciView makeSciView() throws Exception {
SciView sv = new SciView( getContext() );
Future<?> svThread = threadService.run(() -> sv.main());
while( !sv.isInitialized() &&
!svThread.isDone() &&
!svThread.isCancelled() ) {
try {
Thread.sleep( 20 );
} catch( InterruptedException e ) {
logService.trace( e );
}
}
if( svThread.isCancelled() || svThread.isDone() ){
svThread.get();// Trigger an exception from the Future if possible
throw new Exception("SciView thread is done or had an error");
}
Display<?> display = displayService.createDisplay( sv );
displayService.setActiveDisplay( display );
sv.setDisplay( display );
return sv;
}
@Override
public void createSciView() throws Exception {
SciView v = makeSciView();
sceneryViewers.add( v );
}
@Override
public int numSciView() {
return sceneryViewers.size();
}
@Override
public void close(SciView sciView) {
sceneryViewers.remove(sciView);
SciViewDisplay d = displayService.getActiveDisplay( SciViewDisplay.class );
if( d != null ) {
d.close();
}
}
@Override
public void initialize() {
scriptService.addAlias(SciView.class);
scriptService.addAlias("Mesh", Mesh.class);
scriptService.addAlias("Node", Node.class);
scriptService.addAlias("Volume", Volume.class);
}
/* Event Handlers */
@Override
public SciView getOrCreateActiveSciView() throws Exception {
SciView sv = getActiveSciView();
if( sv == null ) {
// Make one
sv = makeSciView();
}
return sv;
// Might need to change to return a SciViewDisplay instead, if downstream code needs it
}
}
| Track sciViews correctly with DefaultSciViewService
| src/main/java/sc/iview/DefaultSciViewService.java | Track sciViews correctly with DefaultSciViewService | <ide><path>rc/main/java/sc/iview/DefaultSciViewService.java
<ide> if( sv == null ) {
<ide> // Make one
<ide> sv = makeSciView();
<add>
<add> sceneryViewers.add( sv );
<ide> }
<ide>
<ide> return sv; |
|
Java | apache-2.0 | 3c928aa8d73f86107e446bd2c36d168369109730 | 0 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | /*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.os.Build.VERSION_CODES.JELLY_BEAN;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static com.facebook.litho.CommonUtils.addOrCreateList;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentsLogger.LogLevel.WARNING;
import static com.facebook.yoga.YogaEdge.ALL;
import static com.facebook.yoga.YogaEdge.BOTTOM;
import static com.facebook.yoga.YogaEdge.END;
import static com.facebook.yoga.YogaEdge.HORIZONTAL;
import static com.facebook.yoga.YogaEdge.LEFT;
import static com.facebook.yoga.YogaEdge.RIGHT;
import static com.facebook.yoga.YogaEdge.START;
import static com.facebook.yoga.YogaEdge.TOP;
import static com.facebook.yoga.YogaEdge.VERTICAL;
import android.animation.StateListAnimator;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.Px;
import androidx.core.view.ViewCompat;
import com.facebook.infer.annotation.OkToExtend;
import com.facebook.infer.annotation.ReturnsOwnership;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.drawable.ComparableColorDrawable;
import com.facebook.litho.drawable.ComparableDrawable;
import com.facebook.litho.drawable.ComparableResDrawable;
import com.facebook.litho.drawable.DefaultComparableDrawable;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/** Default implementation of {@link InternalNode}. */
@OkToExtend
@ThreadConfined(ThreadConfined.ANY)
public class DefaultInternalNode implements InternalNode, Cloneable {
// Used to check whether or not the framework can use style IDs for
// paddingStart/paddingEnd due to a bug in some Android devices.
private static final boolean SUPPORTS_RTL = (SDK_INT >= JELLY_BEAN_MR1);
// Flags used to indicate that a certain attribute was explicitly set on the node.
private static final long PFLAG_LAYOUT_DIRECTION_IS_SET = 1L << 0;
private static final long PFLAG_ALIGN_SELF_IS_SET = 1L << 1;
private static final long PFLAG_POSITION_TYPE_IS_SET = 1L << 2;
private static final long PFLAG_FLEX_IS_SET = 1L << 3;
private static final long PFLAG_FLEX_GROW_IS_SET = 1L << 4;
private static final long PFLAG_FLEX_SHRINK_IS_SET = 1L << 5;
private static final long PFLAG_FLEX_BASIS_IS_SET = 1L << 6;
private static final long PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET = 1L << 7;
private static final long PFLAG_DUPLICATE_PARENT_STATE_IS_SET = 1L << 8;
private static final long PFLAG_MARGIN_IS_SET = 1L << 9;
private static final long PFLAG_PADDING_IS_SET = 1L << 10;
private static final long PFLAG_POSITION_IS_SET = 1L << 11;
private static final long PFLAG_WIDTH_IS_SET = 1L << 12;
private static final long PFLAG_MIN_WIDTH_IS_SET = 1L << 13;
private static final long PFLAG_MAX_WIDTH_IS_SET = 1L << 14;
private static final long PFLAG_HEIGHT_IS_SET = 1L << 15;
private static final long PFLAG_MIN_HEIGHT_IS_SET = 1L << 16;
private static final long PFLAG_MAX_HEIGHT_IS_SET = 1L << 17;
private static final long PFLAG_BACKGROUND_IS_SET = 1L << 18;
private static final long PFLAG_FOREGROUND_IS_SET = 1L << 19;
private static final long PFLAG_VISIBLE_HANDLER_IS_SET = 1L << 20;
private static final long PFLAG_FOCUSED_HANDLER_IS_SET = 1L << 21;
private static final long PFLAG_FULL_IMPRESSION_HANDLER_IS_SET = 1L << 22;
private static final long PFLAG_INVISIBLE_HANDLER_IS_SET = 1L << 23;
private static final long PFLAG_UNFOCUSED_HANDLER_IS_SET = 1L << 24;
private static final long PFLAG_TOUCH_EXPANSION_IS_SET = 1L << 25;
private static final long PFLAG_ASPECT_RATIO_IS_SET = 1L << 26;
private static final long PFLAG_TRANSITION_KEY_IS_SET = 1L << 27;
private static final long PFLAG_BORDER_IS_SET = 1L << 28;
private static final long PFLAG_STATE_LIST_ANIMATOR_SET = 1L << 29;
private static final long PFLAG_STATE_LIST_ANIMATOR_RES_SET = 1L << 30;
private static final long PFLAG_VISIBLE_RECT_CHANGED_HANDLER_IS_SET = 1L << 31;
private static final long PFLAG_TRANSITION_KEY_TYPE_IS_SET = 1L << 32;
private YogaNode mYogaNode;
private final ComponentContext mComponentContext;
@ThreadConfined(ThreadConfined.ANY)
private final List<Component> mComponents = new ArrayList<>(1);
private final int[] mBorderColors = new int[Border.EDGE_COUNT];
private final float[] mBorderRadius = new float[Border.RADIUS_COUNT];
private @Nullable DiffNode mDiffNode;
private @Nullable NodeInfo mNodeInfo;
private @Nullable NestedTreeProps mNestedTreeProps;
private @Nullable EventHandler<VisibleEvent> mVisibleHandler;
private @Nullable EventHandler<FocusedVisibleEvent> mFocusedHandler;
private @Nullable EventHandler<UnfocusedVisibleEvent> mUnfocusedHandler;
private @Nullable EventHandler<FullImpressionVisibleEvent> mFullImpressionHandler;
private @Nullable EventHandler<InvisibleEvent> mInvisibleHandler;
private @Nullable EventHandler<VisibilityChangedEvent> mVisibilityChangedHandler;
private @Nullable ComparableDrawable mBackground;
private @Nullable ComparableDrawable mForeground;
private @Nullable PathEffect mBorderPathEffect;
private @Nullable StateListAnimator mStateListAnimator;
private @Nullable boolean[] mIsPaddingPercent;
private @Nullable Edges mTouchExpansion;
private @Nullable String mTransitionKey;
private @Nullable Transition.TransitionKeyType mTransitionKeyType;
private @Nullable ArrayList<Transition> mTransitions;
private @Nullable ArrayList<Component> mComponentsNeedingPreviousRenderData;
private @Nullable ArrayList<WorkingRangeContainer.Registration> mWorkingRangeRegistrations;
private @Nullable String mTestKey;
private @Nullable Set<DebugComponent> mDebugComponents = null;
private boolean mDuplicateParentState;
private boolean mForceViewWrapping;
private boolean mCachedMeasuresValid;
private int mImportantForAccessibility = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
private @DrawableRes int mStateListAnimatorRes;
private float mVisibleHeightRatio;
private float mVisibleWidthRatio;
private float mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
private float mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
private float mResolvedX = YogaConstants.UNDEFINED;
private float mResolvedY = YogaConstants.UNDEFINED;
private float mResolvedWidth = YogaConstants.UNDEFINED;
private float mResolvedHeight = YogaConstants.UNDEFINED;
private int mLastWidthSpec = DiffNode.UNSPECIFIED;
private int mLastHeightSpec = DiffNode.UNSPECIFIED;
private float mLastMeasuredWidth = DiffNode.UNSPECIFIED;
private float mLastMeasuredHeight = DiffNode.UNSPECIFIED;
private long mPrivateFlags;
protected DefaultInternalNode(ComponentContext componentContext) {
this(componentContext, createYogaNode(componentContext), true);
}
protected DefaultInternalNode(ComponentContext componentContext, YogaNode yogaNode) {
this(componentContext, yogaNode, true);
}
protected DefaultInternalNode(
ComponentContext componentContext, boolean createDebugComponentsInCtor) {
this(componentContext, createYogaNode(componentContext), createDebugComponentsInCtor);
}
protected DefaultInternalNode(
ComponentContext componentContext, YogaNode yogaNode, boolean createDebugComponentsInCtor) {
if (createDebugComponentsInCtor) {
mDebugComponents = new HashSet<>();
}
if (yogaNode != null) {
yogaNode.setData(this);
}
mYogaNode = yogaNode;
mComponentContext = componentContext;
}
@Override
public void addChildAt(InternalNode child, int index) {
mYogaNode.addChildAt(child.getYogaNode(), index);
}
@Override
public void addComponentNeedingPreviousRenderData(Component component) {
if (mComponentsNeedingPreviousRenderData == null) {
mComponentsNeedingPreviousRenderData = new ArrayList<>(1);
}
mComponentsNeedingPreviousRenderData.add(component);
}
@Override
public void addTransition(Transition transition) {
if (mTransitions == null) {
mTransitions = new ArrayList<>(1);
}
mTransitions.add(transition);
}
@Override
public void addWorkingRanges(List<WorkingRangeContainer.Registration> registrations) {
if (mWorkingRangeRegistrations == null) {
mWorkingRangeRegistrations = new ArrayList<>(registrations.size());
}
mWorkingRangeRegistrations.addAll(registrations);
}
@Override
public InternalNode alignContent(YogaAlign alignContent) {
mYogaNode.setAlignContent(alignContent);
return this;
}
@Override
public InternalNode alignItems(YogaAlign alignItems) {
mYogaNode.setAlignItems(alignItems);
return this;
}
@Override
public void alignSelf(YogaAlign alignSelf) {
mPrivateFlags |= PFLAG_ALIGN_SELF_IS_SET;
mYogaNode.setAlignSelf(alignSelf);
}
@Override
public void appendComponent(Component component) {
mComponents.add(component);
}
@Override
public boolean areCachedMeasuresValid() {
return mCachedMeasuresValid;
}
@Override
public void aspectRatio(float aspectRatio) {
mPrivateFlags |= PFLAG_ASPECT_RATIO_IS_SET;
mYogaNode.setAspectRatio(aspectRatio);
}
@Override
public InternalNode background(@Nullable ComparableDrawable background) {
mPrivateFlags |= PFLAG_BACKGROUND_IS_SET;
mBackground = background;
setPaddingFromBackground(background);
return this;
}
/**
* @deprecated use {@link #background(ComparableDrawable)} more efficient diffing of drawables.
*/
@Deprecated
@Override
public InternalNode background(@Nullable Drawable background) {
if (background instanceof ComparableDrawable) {
return background((ComparableDrawable) background);
}
return background(background != null ? DefaultComparableDrawable.create(background) : null);
}
@Override
public InternalNode backgroundColor(@ColorInt int backgroundColor) {
return background(ComparableColorDrawable.create(backgroundColor));
}
@Override
public InternalNode backgroundRes(@DrawableRes int resId) {
if (resId == 0) {
return background(null);
}
return background(ComparableResDrawable.create(mComponentContext.getAndroidContext(), resId));
}
@Override
public InternalNode border(Border border) {
mPrivateFlags |= PFLAG_BORDER_IS_SET;
for (int i = 0, length = border.mEdgeWidths.length; i < length; ++i) {
setBorderWidth(Border.edgeFromIndex(i), border.mEdgeWidths[i]);
}
System.arraycopy(border.mEdgeColors, 0, mBorderColors, 0, mBorderColors.length);
System.arraycopy(border.mRadius, 0, mBorderRadius, 0, mBorderRadius.length);
mBorderPathEffect = border.mPathEffect;
return this;
}
@Override
public void border(Edges width, int[] colors, float[] radii) {
mPrivateFlags |= PFLAG_BORDER_IS_SET;
mYogaNode.setBorder(LEFT, width.getRaw(YogaEdge.LEFT));
mYogaNode.setBorder(TOP, width.getRaw(YogaEdge.TOP));
mYogaNode.setBorder(RIGHT, width.getRaw(YogaEdge.RIGHT));
mYogaNode.setBorder(BOTTOM, width.getRaw(YogaEdge.BOTTOM));
mYogaNode.setBorder(VERTICAL, width.getRaw(YogaEdge.VERTICAL));
mYogaNode.setBorder(HORIZONTAL, width.getRaw(YogaEdge.HORIZONTAL));
mYogaNode.setBorder(START, width.getRaw(YogaEdge.START));
mYogaNode.setBorder(END, width.getRaw(YogaEdge.END));
mYogaNode.setBorder(ALL, width.getRaw(YogaEdge.ALL));
System.arraycopy(colors, 0, mBorderColors, 0, colors.length);
System.arraycopy(radii, 0, mBorderRadius, 0, radii.length);
}
@Override
public void calculateLayout(float width, float height) {
applyOverridesRecursive(this);
mYogaNode.calculateLayout(width, height);
}
@Override
public void calculateLayout() {
calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
}
@Override
public InternalNode child(Component child) {
if (child != null) {
return child(Layout.create(mComponentContext, child));
}
return this;
}
@Override
public InternalNode child(Component.Builder<?> child) {
if (child != null) {
child(child.build());
}
return this;
}
@Override
public InternalNode child(InternalNode child) {
if (child != null && child != NULL_LAYOUT) {
addChildAt(child, mYogaNode.getChildCount());
}
return this;
}
@Override
public InternalNode duplicateParentState(boolean duplicateParentState) {
mPrivateFlags |= PFLAG_DUPLICATE_PARENT_STATE_IS_SET;
mDuplicateParentState = duplicateParentState;
return this;
}
@Override
public void flex(float flex) {
mPrivateFlags |= PFLAG_FLEX_IS_SET;
mYogaNode.setFlex(flex);
}
// Used by stetho to re-set auto value
@Override
public InternalNode flexBasisAuto() {
mYogaNode.setFlexBasisAuto();
return this;
}
@Override
public void flexBasisPercent(float percent) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasisPercent(percent);
}
@Override
public void flexBasisPx(@Px int flexBasis) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasis(flexBasis);
}
@Override
public InternalNode flexDirection(YogaFlexDirection direction) {
mYogaNode.setFlexDirection(direction);
return this;
}
@Override
public void flexGrow(float flexGrow) {
mPrivateFlags |= PFLAG_FLEX_GROW_IS_SET;
mYogaNode.setFlexGrow(flexGrow);
}
@Override
public void flexShrink(float flexShrink) {
mPrivateFlags |= PFLAG_FLEX_SHRINK_IS_SET;
mYogaNode.setFlexShrink(flexShrink);
}
@Override
public InternalNode focusedHandler(@Nullable EventHandler<FocusedVisibleEvent> focusedHandler) {
mPrivateFlags |= PFLAG_FOCUSED_HANDLER_IS_SET;
mFocusedHandler = addVisibilityHandler(mFocusedHandler, focusedHandler);
return this;
}
/**
* @deprecated use {@link #foreground(ComparableDrawable)} more efficient diffing of drawables.
*/
@Deprecated
@Override
public InternalNode foreground(@Nullable Drawable foreground) {
return foreground(foreground != null ? DefaultComparableDrawable.create(foreground) : null);
}
@Override
public InternalNode foreground(@Nullable ComparableDrawable foreground) {
mPrivateFlags |= PFLAG_FOREGROUND_IS_SET;
mForeground = foreground;
return this;
}
@Override
public InternalNode foregroundColor(@ColorInt int foregroundColor) {
return foreground(ComparableColorDrawable.create(foregroundColor));
}
@Override
public InternalNode foregroundRes(@DrawableRes int resId) {
if (resId == 0) {
return foreground(null);
}
return foreground(ComparableResDrawable.create(mComponentContext.getAndroidContext(), resId));
}
@Override
public InternalNode fullImpressionHandler(
@Nullable EventHandler<FullImpressionVisibleEvent> fullImpressionHandler) {
mPrivateFlags |= PFLAG_FULL_IMPRESSION_HANDLER_IS_SET;
mFullImpressionHandler = addVisibilityHandler(mFullImpressionHandler, fullImpressionHandler);
return this;
}
@Override
public int[] getBorderColors() {
return mBorderColors;
}
@Override
public @Nullable PathEffect getBorderPathEffect() {
return mBorderPathEffect;
}
@Override
public float[] getBorderRadius() {
return mBorderRadius;
}
@Override
public @Nullable InternalNode getChildAt(int index) {
if (mYogaNode.getChildAt(index) == null) {
return null;
}
return (InternalNode) mYogaNode.getChildAt(index).getData();
}
@Override
public int getChildCount() {
return mYogaNode.getChildCount();
}
@Override
public int getChildIndex(InternalNode child) {
for (int i = 0, count = mYogaNode.getChildCount(); i < count; i++) {
if (mYogaNode.getChildAt(i) == child.getYogaNode()) {
return i;
}
}
return -1;
}
/**
* Return the list of components contributing to this InternalNode. We have no need for this in
* production but it is useful information to have while debugging. Therefor this list will only
* contain the root component if running in production mode.
*/
@Override
public List<Component> getComponents() {
return mComponents;
}
@Override
public @Nullable ArrayList<Component> getComponentsNeedingPreviousRenderData() {
return mComponentsNeedingPreviousRenderData;
}
@Override
public ComponentContext getContext() {
return mComponentContext;
}
@Override
public @Nullable DiffNode getDiffNode() {
return mDiffNode;
}
@Override
public void setDiffNode(@Nullable DiffNode diffNode) {
mDiffNode = diffNode;
}
@Override
public @Nullable EventHandler<FocusedVisibleEvent> getFocusedHandler() {
return mFocusedHandler;
}
@Override
public @Nullable ComparableDrawable getForeground() {
return mForeground;
}
@Override
public @Nullable EventHandler<FullImpressionVisibleEvent> getFullImpressionHandler() {
return mFullImpressionHandler;
}
@Override
public int getImportantForAccessibility() {
return mImportantForAccessibility;
}
@Nullable
@Override
public EventHandler<InvisibleEvent> getInvisibleHandler() {
return mInvisibleHandler;
}
@Override
public int getLastHeightSpec() {
return mLastHeightSpec;
}
@Override
public void setLastHeightSpec(int heightSpec) {
mLastHeightSpec = heightSpec;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned for the
* height. This is used together with {@link InternalNode#getLastHeightSpec()} to implement
* measure caching.
*/
@Override
public float getLastMeasuredHeight() {
return mLastMeasuredHeight;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the height.
*/
@Override
public void setLastMeasuredHeight(float lastMeasuredHeight) {
mLastMeasuredHeight = lastMeasuredHeight;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned for the
* width. This is used together with {@link InternalNode#getLastWidthSpec()} to implement measure
* caching.
*/
@Override
public float getLastMeasuredWidth() {
return mLastMeasuredWidth;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the width.
*/
@Override
public void setLastMeasuredWidth(float lastMeasuredWidth) {
mLastMeasuredWidth = lastMeasuredWidth;
}
@Override
public int getLastWidthSpec() {
return mLastWidthSpec;
}
@Override
public void setLastWidthSpec(int widthSpec) {
mLastWidthSpec = widthSpec;
}
@Override
public int getLayoutBorder(YogaEdge edge) {
return FastMath.round(mYogaNode.getLayoutBorder(edge));
}
@Override
public float getMaxHeight() {
return mYogaNode.getMaxHeight().value;
}
@Override
public float getMaxWidth() {
return mYogaNode.getMaxWidth().value;
}
@Override
public float getMinHeight() {
return mYogaNode.getMinHeight().value;
}
@Override
public float getMinWidth() {
return mYogaNode.getMinWidth().value;
}
@Override
public @Nullable InternalNode getNestedTree() {
return mNestedTreeProps != null ? mNestedTreeProps.mNestedTree : null;
}
/**
* Set the nested tree before measuring it in order to transfer over important information such as
* layout direction needed during measurement.
*/
@Override
public void setNestedTree(InternalNode nestedTree) {
if (nestedTree != NULL_LAYOUT) {
nestedTree.getOrCreateNestedTreeProps().mNestedTreeHolder = this;
}
getOrCreateNestedTreeProps().mNestedTree = nestedTree;
}
@Override
public @Nullable InternalNode getNestedTreeHolder() {
return mNestedTreeProps != null ? mNestedTreeProps.mNestedTreeHolder : null;
}
@Override
public @Nullable NodeInfo getNodeInfo() {
return mNodeInfo;
}
@Override
public void setNodeInfo(NodeInfo nodeInfo) {
mNodeInfo = nodeInfo;
}
@Override
public NestedTreeProps getOrCreateNestedTreeProps() {
if (mNestedTreeProps == null) {
mNestedTreeProps = new NestedTreeProps();
}
return mNestedTreeProps;
}
@Override
public NodeInfo getOrCreateNodeInfo() {
if (mNodeInfo == null) {
if (ComponentsConfiguration.isSparseNodeInfoIsEnabled) {
mNodeInfo = new SparseNodeInfo();
} else {
mNodeInfo = new DefaultNodeInfo();
}
}
return mNodeInfo;
}
@Override
public @Nullable InternalNode getParent() {
if (mYogaNode == null || mYogaNode.getOwner() == null) {
return null;
}
return (InternalNode) mYogaNode.getOwner().getData();
}
@Override
public @Nullable TreeProps getPendingTreeProps() {
return mNestedTreeProps != null ? mNestedTreeProps.mPendingTreeProps : null;
}
@Override
public @Nullable Component getRootComponent() {
return mComponents.isEmpty() ? null : mComponents.get(0);
}
@Override
public void setRootComponent(Component component) {
mComponents.clear();
mComponents.add(component);
}
@Override
public @Nullable StateListAnimator getStateListAnimator() {
return mStateListAnimator;
}
@Override
public @DrawableRes int getStateListAnimatorRes() {
return mStateListAnimatorRes;
}
@Override
public YogaDirection getStyleDirection() {
return mYogaNode.getStyleDirection();
}
@Override
public float getStyleHeight() {
return mYogaNode.getHeight().value;
}
@Override
public float getStyleWidth() {
return mYogaNode.getWidth().value;
}
/**
* A unique identifier which may be set for retrieving a component and its bounds when testing.
*/
@Override
public @Nullable String getTestKey() {
return mTestKey;
}
@Override
public @Nullable Edges getTouchExpansion() {
return mTouchExpansion;
}
@Override
public int getTouchExpansionBottom() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(YogaEdge.BOTTOM));
}
@Override
public int getTouchExpansionLeft() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionLeft)) {
mResolvedTouchExpansionLeft = resolveHorizontalEdges(mTouchExpansion, YogaEdge.LEFT);
}
return FastMath.round(mResolvedTouchExpansionLeft);
}
@Override
public int getTouchExpansionRight() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionRight)) {
mResolvedTouchExpansionRight = resolveHorizontalEdges(mTouchExpansion, YogaEdge.RIGHT);
}
return FastMath.round(mResolvedTouchExpansionRight);
}
@Override
public int getTouchExpansionTop() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(YogaEdge.TOP));
}
@Override
public @Nullable String getTransitionKey() {
return mTransitionKey;
}
@Override
public @Nullable Transition.TransitionKeyType getTransitionKeyType() {
return mTransitionKeyType;
}
@Override
public @Nullable ArrayList<Transition> getTransitions() {
return mTransitions;
}
@Override
public @Nullable EventHandler<UnfocusedVisibleEvent> getUnfocusedHandler() {
return mUnfocusedHandler;
}
@Override
public @Nullable EventHandler<VisibilityChangedEvent> getVisibilityChangedHandler() {
return mVisibilityChangedHandler;
}
@Override
public @Nullable EventHandler<VisibleEvent> getVisibleHandler() {
return mVisibleHandler;
}
@Override
public float getVisibleHeightRatio() {
return mVisibleHeightRatio;
}
@Override
public float getVisibleWidthRatio() {
return mVisibleWidthRatio;
}
@Override
public @Nullable ArrayList<WorkingRangeContainer.Registration> getWorkingRangeRegistrations() {
return mWorkingRangeRegistrations;
}
@Override
public YogaNode getYogaNode() {
return mYogaNode;
}
@Override
public boolean hasBorderColor() {
for (int color : mBorderColors) {
if (color != Color.TRANSPARENT) {
return true;
}
}
return false;
}
@Override
public boolean hasNestedTree() {
return mNestedTreeProps != null && mNestedTreeProps.mNestedTree != null;
}
@Override
public boolean hasNewLayout() {
return mYogaNode.hasNewLayout();
}
@Override
public boolean hasStateListAnimatorResSet() {
return (mPrivateFlags & PFLAG_STATE_LIST_ANIMATOR_RES_SET) != 0;
}
@Override
public boolean hasTouchExpansion() {
return ((mPrivateFlags & PFLAG_TOUCH_EXPANSION_IS_SET) != 0L);
}
@Override
public boolean hasTransitionKey() {
return !TextUtils.isEmpty(mTransitionKey);
}
@Override
public boolean hasVisibilityHandlers() {
return mVisibleHandler != null
|| mFocusedHandler != null
|| mUnfocusedHandler != null
|| mFullImpressionHandler != null
|| mInvisibleHandler != null
|| mVisibilityChangedHandler != null;
}
// Used by stetho to re-set auto value
@Override
public InternalNode heightAuto() {
mYogaNode.setHeightAuto();
return this;
}
@Override
public void heightPercent(float percent) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeightPercent(percent);
}
@Override
public void heightPx(@Px int height) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeight(height);
}
@Override
public InternalNode importantForAccessibility(int importantForAccessibility) {
mPrivateFlags |= PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET;
mImportantForAccessibility = importantForAccessibility;
return this;
}
@Override
public InternalNode invisibleHandler(@Nullable EventHandler<InvisibleEvent> invisibleHandler) {
mPrivateFlags |= PFLAG_INVISIBLE_HANDLER_IS_SET;
mInvisibleHandler = addVisibilityHandler(mInvisibleHandler, invisibleHandler);
return this;
}
@Override
public boolean isDuplicateParentStateEnabled() {
return mDuplicateParentState;
}
@Override
public boolean isForceViewWrapping() {
return mForceViewWrapping;
}
@Override
public boolean isImportantForAccessibilityIsSet() {
return (mPrivateFlags & PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET) == 0L
|| mImportantForAccessibility == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
}
/**
* For testing and debugging purposes only where initialization may have not occurred. For any
* production use, this should never be necessary.
*/
@Override
public boolean isInitialized() {
return mYogaNode != null && mComponentContext != null;
}
@Override
public boolean isLayoutDirectionInherit() {
return (mPrivateFlags & PFLAG_LAYOUT_DIRECTION_IS_SET) == 0L
|| getResolvedLayoutDirection() == YogaDirection.INHERIT;
}
/**
* @return Whether this node is holding a nested tree or not. The decision was made during tree
* creation {@link ComponentLifecycle#createLayout(ComponentContext, boolean)}.
*/
@Override
public boolean isNestedTreeHolder() {
return mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder;
}
@Override
public void isReferenceBaseline(boolean isReferenceBaseline) {
mYogaNode.setIsReferenceBaseline(isReferenceBaseline);
}
@Override
public InternalNode justifyContent(YogaJustify justifyContent) {
mYogaNode.setJustifyContent(justifyContent);
return this;
}
@Override
public void layoutDirection(YogaDirection direction) {
mPrivateFlags |= PFLAG_LAYOUT_DIRECTION_IS_SET;
mYogaNode.setDirection(direction);
}
@Override
public void marginAuto(YogaEdge edge) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginAuto(edge);
}
@Override
public void marginPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginPercent(edge, percent);
}
@Override
public void marginPx(YogaEdge edge, @Px int margin) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMargin(edge, margin);
}
/** Mark this node as a nested tree root holder. */
@Override
public void markIsNestedTreeHolder(TreeProps currentTreeProps) {
getOrCreateNestedTreeProps().mIsNestedTreeHolder = true;
getOrCreateNestedTreeProps().mPendingTreeProps = TreeProps.copy(currentTreeProps);
}
@Override
public void markLayoutSeen() {
mYogaNode.markLayoutSeen();
}
@Override
public void maxHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeightPercent(percent);
}
@Override
public void maxHeightPx(@Px int maxHeight) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeight(maxHeight);
}
@Override
public void maxWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidthPercent(percent);
}
@Override
public void maxWidthPx(@Px int maxWidth) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidth(maxWidth);
}
@Override
public void minHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeightPercent(percent);
}
@Override
public void minHeightPx(@Px int minHeight) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeight(minHeight);
}
@Override
public void minWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidthPercent(percent);
}
@Override
public void minWidthPx(@Px int minWidth) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidth(minWidth);
}
@Override
public void paddingPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder) {
getNestedTreePadding().set(edge, percent);
setIsPaddingPercent(edge, true);
} else {
mYogaNode.setPaddingPercent(edge, percent);
}
}
@Override
public void paddingPx(YogaEdge edge, @Px int padding) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder) {
getNestedTreePadding().set(edge, padding);
setIsPaddingPercent(edge, false);
} else {
mYogaNode.setPadding(edge, padding);
}
}
@Override
public void positionPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPositionPercent(edge, percent);
}
@Override
public void positionPx(YogaEdge edge, @Px int position) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPosition(edge, position);
}
@Override
public void positionType(@Nullable YogaPositionType positionType) {
mPrivateFlags |= PFLAG_POSITION_TYPE_IS_SET;
mYogaNode.setPositionType(positionType);
}
/** Continually walks the node hierarchy until a node returns a non inherited layout direction */
@Override
public YogaDirection recursivelyResolveLayoutDirection() {
YogaNode yogaNode = mYogaNode;
while (yogaNode != null && yogaNode.getLayoutDirection() == YogaDirection.INHERIT) {
yogaNode = yogaNode.getOwner();
}
return yogaNode == null ? YogaDirection.INHERIT : yogaNode.getLayoutDirection();
}
@Override
public void registerDebugComponent(DebugComponent debugComponent) {
if (mDebugComponents == null) {
mDebugComponents = new HashSet<>();
}
mDebugComponents.add(debugComponent);
}
@Override
public InternalNode removeChildAt(int index) {
return (InternalNode) mYogaNode.removeChildAt(index).getData();
}
/** This method marks all resolved layout property values to undefined. */
@Override
public void resetResolvedLayoutProperties() {
mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
mResolvedX = YogaConstants.UNDEFINED;
mResolvedY = YogaConstants.UNDEFINED;
mResolvedWidth = YogaConstants.UNDEFINED;
mResolvedHeight = YogaConstants.UNDEFINED;
}
@Override
public void setBorderWidth(YogaEdge edge, @Px int borderWidth) {
if (mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder) {
NestedTreeProps props = getOrCreateNestedTreeProps();
if (props.mNestedTreeBorderWidth == null) {
props.mNestedTreeBorderWidth = new Edges();
}
props.mNestedTreeBorderWidth.set(edge, borderWidth);
} else {
mYogaNode.setBorder(edge, borderWidth);
}
}
@Override
public void setCachedMeasuresValid(boolean valid) {
mCachedMeasuresValid = valid;
}
@Override
public void setMeasureFunction(YogaMeasureFunction measureFunction) {
mYogaNode.setMeasureFunction(measureFunction);
}
@Override
public void setStyleHeightFromSpec(int heightSpec) {
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.UNSPECIFIED:
mYogaNode.setHeight(YogaConstants.UNDEFINED);
break;
case SizeSpec.AT_MOST:
mYogaNode.setMaxHeight(SizeSpec.getSize(heightSpec));
break;
case SizeSpec.EXACTLY:
mYogaNode.setHeight(SizeSpec.getSize(heightSpec));
break;
}
}
@Override
public void setStyleWidthFromSpec(int widthSpec) {
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.UNSPECIFIED:
mYogaNode.setWidth(YogaConstants.UNDEFINED);
break;
case SizeSpec.AT_MOST:
mYogaNode.setMaxWidth(SizeSpec.getSize(widthSpec));
break;
case SizeSpec.EXACTLY:
mYogaNode.setWidth(SizeSpec.getSize(widthSpec));
break;
}
}
@Override
public boolean shouldDrawBorders() {
return hasBorderColor()
&& (mYogaNode.getLayoutBorder(LEFT) != 0
|| mYogaNode.getLayoutBorder(TOP) != 0
|| mYogaNode.getLayoutBorder(RIGHT) != 0
|| mYogaNode.getLayoutBorder(BOTTOM) != 0);
}
@Override
public InternalNode stateListAnimator(@Nullable StateListAnimator stateListAnimator) {
mPrivateFlags |= PFLAG_STATE_LIST_ANIMATOR_SET;
mStateListAnimator = stateListAnimator;
wrapInView();
return this;
}
@Override
public InternalNode stateListAnimatorRes(@DrawableRes int resId) {
mPrivateFlags |= PFLAG_STATE_LIST_ANIMATOR_RES_SET;
mStateListAnimatorRes = resId;
wrapInView();
return this;
}
@Override
public InternalNode testKey(@Nullable String testKey) {
mTestKey = testKey;
return this;
}
@Override
public InternalNode touchExpansionPx(YogaEdge edge, @Px int touchExpansion) {
if (mTouchExpansion == null) {
mTouchExpansion = new Edges();
}
mPrivateFlags |= PFLAG_TOUCH_EXPANSION_IS_SET;
mTouchExpansion.set(edge, touchExpansion);
return this;
}
@Override
public InternalNode transitionKey(@Nullable String key) {
if (SDK_INT >= ICE_CREAM_SANDWICH && !TextUtils.isEmpty(key)) {
mPrivateFlags |= PFLAG_TRANSITION_KEY_IS_SET;
mTransitionKey = key;
}
return this;
}
@Override
public InternalNode transitionKeyType(@Nullable Transition.TransitionKeyType type) {
mPrivateFlags |= PFLAG_TRANSITION_KEY_TYPE_IS_SET;
mTransitionKeyType = type;
return this;
}
@Override
public InternalNode unfocusedHandler(
@Nullable EventHandler<UnfocusedVisibleEvent> unfocusedHandler) {
mPrivateFlags |= PFLAG_UNFOCUSED_HANDLER_IS_SET;
mUnfocusedHandler = addVisibilityHandler(mUnfocusedHandler, unfocusedHandler);
return this;
}
@Override
public void useHeightAsBaseline(boolean useHeightAsBaselineFunction) {
if (useHeightAsBaselineFunction) {
mYogaNode.setBaselineFunction(
new YogaBaselineFunction() {
@Override
public float baseline(YogaNode yogaNode, float width, float height) {
return height;
}
});
}
}
@Override
public InternalNode visibilityChangedHandler(
@Nullable EventHandler<VisibilityChangedEvent> visibilityChangedHandler) {
mPrivateFlags |= PFLAG_VISIBLE_RECT_CHANGED_HANDLER_IS_SET;
mVisibilityChangedHandler =
addVisibilityHandler(mVisibilityChangedHandler, visibilityChangedHandler);
return this;
}
@Override
public InternalNode visibleHandler(@Nullable EventHandler<VisibleEvent> visibleHandler) {
mPrivateFlags |= PFLAG_VISIBLE_HANDLER_IS_SET;
mVisibleHandler = addVisibilityHandler(mVisibleHandler, visibleHandler);
return this;
}
@Override
public InternalNode visibleHeightRatio(float visibleHeightRatio) {
mVisibleHeightRatio = visibleHeightRatio;
return this;
}
@Override
public InternalNode visibleWidthRatio(float visibleWidthRatio) {
mVisibleWidthRatio = visibleWidthRatio;
return this;
}
@Override
public InternalNode widthAuto() {
mYogaNode.setWidthAuto();
return this;
}
@Override
public void widthPercent(float percent) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidthPercent(percent);
}
@Override
public void widthPx(@Px int width) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidth(width);
}
@Override
public InternalNode wrap(YogaWrap wrap) {
mYogaNode.setWrap(wrap);
return this;
}
@Override
public InternalNode wrapInView() {
mForceViewWrapping = true;
return this;
}
@Px
@Override
public int getX() {
if (YogaConstants.isUndefined(mResolvedX)) {
mResolvedX = mYogaNode.getLayoutX();
}
return (int) mResolvedX;
}
@Px
@Override
public int getY() {
if (YogaConstants.isUndefined(mResolvedY)) {
mResolvedY = mYogaNode.getLayoutY();
}
return (int) mResolvedY;
}
@Px
@Override
public int getWidth() {
if (YogaConstants.isUndefined(mResolvedWidth)) {
mResolvedWidth = mYogaNode.getLayoutWidth();
}
return (int) mResolvedWidth;
}
@Px
@Override
public int getHeight() {
if (YogaConstants.isUndefined(mResolvedHeight)) {
mResolvedHeight = mYogaNode.getLayoutHeight();
}
return (int) mResolvedHeight;
}
@Px
@Override
public int getPaddingTop() {
return FastMath.round(mYogaNode.getLayoutPadding(TOP));
}
@Px
@Override
public int getPaddingRight() {
return FastMath.round(mYogaNode.getLayoutPadding(RIGHT));
}
@Px
@Override
public int getPaddingBottom() {
return FastMath.round(mYogaNode.getLayoutPadding(BOTTOM));
}
@Px
@Override
public int getPaddingLeft() {
return FastMath.round(mYogaNode.getLayoutPadding(LEFT));
}
@Override
public boolean isPaddingSet() {
return (mPrivateFlags & PFLAG_PADDING_IS_SET) != 0L;
}
@Override
public @Nullable ComparableDrawable getBackground() {
return mBackground;
}
@Override
public YogaDirection getResolvedLayoutDirection() {
return mYogaNode.getLayoutDirection();
}
@Override
public void copyInto(InternalNode target) {
if (target == NULL_LAYOUT) {
return;
}
if (mNodeInfo != null) {
if (target.getNodeInfo() == null) {
target.setNodeInfo(mNodeInfo);
} else {
mNodeInfo.copyInto(target.getOrCreateNodeInfo());
}
}
if (target.isLayoutDirectionInherit()) {
target.layoutDirection(getResolvedLayoutDirection());
}
if (target.isImportantForAccessibilityIsSet()) {
target.importantForAccessibility(mImportantForAccessibility);
}
if ((mPrivateFlags & PFLAG_DUPLICATE_PARENT_STATE_IS_SET) != 0L) {
target.duplicateParentState(mDuplicateParentState);
}
if ((mPrivateFlags & PFLAG_BACKGROUND_IS_SET) != 0L) {
target.background(mBackground);
}
if ((mPrivateFlags & PFLAG_FOREGROUND_IS_SET) != 0L) {
target.foreground(mForeground);
}
if (mForceViewWrapping) {
target.wrapInView();
}
if ((mPrivateFlags & PFLAG_VISIBLE_HANDLER_IS_SET) != 0L) {
target.visibleHandler(mVisibleHandler);
}
if ((mPrivateFlags & PFLAG_FOCUSED_HANDLER_IS_SET) != 0L) {
target.focusedHandler(mFocusedHandler);
}
if ((mPrivateFlags & PFLAG_FULL_IMPRESSION_HANDLER_IS_SET) != 0L) {
target.fullImpressionHandler(mFullImpressionHandler);
}
if ((mPrivateFlags & PFLAG_INVISIBLE_HANDLER_IS_SET) != 0L) {
target.invisibleHandler(mInvisibleHandler);
}
if ((mPrivateFlags & PFLAG_UNFOCUSED_HANDLER_IS_SET) != 0L) {
target.unfocusedHandler(mUnfocusedHandler);
}
if ((mPrivateFlags & PFLAG_VISIBLE_RECT_CHANGED_HANDLER_IS_SET) != 0L) {
target.visibilityChangedHandler(mVisibilityChangedHandler);
}
if (mTestKey != null) {
target.testKey(mTestKey);
}
if ((mPrivateFlags & PFLAG_PADDING_IS_SET) != 0L) {
if (mNestedTreeProps == null || mNestedTreeProps.mNestedTreePadding == null) {
throw new IllegalStateException(
"copyInto() must be used when resolving a nestedTree. If padding was set on the holder node, we must have a mNestedTreePadding instance");
}
for (int i = 0; i < Edges.EDGES_LENGTH; i++) {
float value = mNestedTreeProps.mNestedTreePadding.getRaw(i);
if (!YogaConstants.isUndefined(value)) {
final YogaEdge edge = YogaEdge.fromInt(i);
if (isPaddingPercent(edge)) {
target.paddingPercent(edge, value);
} else {
target.paddingPx(edge, (int) value);
}
}
}
}
if ((mPrivateFlags & PFLAG_BORDER_IS_SET) != 0L) {
if (mNestedTreeProps == null || mNestedTreeProps.mNestedTreeBorderWidth == null) {
throw new IllegalStateException(
"copyInto() must be used when resolving a nestedTree.If border width was set on the holder node, we must have a mNestedTreeBorderWidth instance");
}
target.border(mNestedTreeProps.mNestedTreeBorderWidth, mBorderColors, mBorderRadius);
}
if ((mPrivateFlags & PFLAG_TRANSITION_KEY_IS_SET) != 0L) {
target.transitionKey(mTransitionKey);
}
if ((mPrivateFlags & PFLAG_TRANSITION_KEY_TYPE_IS_SET) != 0L) {
target.transitionKeyType(mTransitionKeyType);
}
if (mVisibleHeightRatio != 0) {
target.visibleHeightRatio(mVisibleHeightRatio);
}
if (mVisibleWidthRatio != 0) {
target.visibleWidthRatio(mVisibleWidthRatio);
}
if ((mPrivateFlags & PFLAG_STATE_LIST_ANIMATOR_SET) != 0L) {
target.stateListAnimator(mStateListAnimator);
}
if ((mPrivateFlags & PFLAG_STATE_LIST_ANIMATOR_RES_SET) != 0L) {
target.stateListAnimatorRes(mStateListAnimatorRes);
}
}
@Override
public void applyAttributes(TypedArray a) {
for (int i = 0, size = a.getIndexCount(); i < size; i++) {
final int attr = a.getIndex(i);
if (attr == R.styleable.ComponentLayout_android_layout_width) {
int width = a.getLayoutDimension(attr, -1);
// We don't support WRAP_CONTENT or MATCH_PARENT so no-op for them
if (width >= 0) {
widthPx(width);
}
} else if (attr == R.styleable.ComponentLayout_android_layout_height) {
int height = a.getLayoutDimension(attr, -1);
// We don't support WRAP_CONTENT or MATCH_PARENT so no-op for them
if (height >= 0) {
heightPx(height);
}
} else if (attr == R.styleable.ComponentLayout_android_minHeight) {
minHeightPx(a.getDimensionPixelSize(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_minWidth) {
minWidthPx(a.getDimensionPixelSize(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingLeft) {
paddingPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingTop) {
paddingPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingRight) {
paddingPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingBottom) {
paddingPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingStart && SUPPORTS_RTL) {
paddingPx(START, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingEnd && SUPPORTS_RTL) {
paddingPx(END, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_padding) {
paddingPx(ALL, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginLeft) {
marginPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginTop) {
marginPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginRight) {
marginPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginBottom) {
marginPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginStart && SUPPORTS_RTL) {
marginPx(START, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginEnd && SUPPORTS_RTL) {
marginPx(END, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_margin) {
marginPx(ALL, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_importantForAccessibility
&& SDK_INT >= JELLY_BEAN) {
importantForAccessibility(a.getInt(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_duplicateParentState) {
duplicateParentState(a.getBoolean(attr, false));
} else if (attr == R.styleable.ComponentLayout_android_background) {
if (TypedArrayUtils.isColorAttribute(a, R.styleable.ComponentLayout_android_background)) {
backgroundColor(a.getColor(attr, 0));
} else {
backgroundRes(a.getResourceId(attr, -1));
}
} else if (attr == R.styleable.ComponentLayout_android_foreground) {
if (TypedArrayUtils.isColorAttribute(a, R.styleable.ComponentLayout_android_foreground)) {
foregroundColor(a.getColor(attr, 0));
} else {
foregroundRes(a.getResourceId(attr, -1));
}
} else if (attr == R.styleable.ComponentLayout_android_contentDescription) {
getOrCreateNodeInfo().setContentDescription(a.getString(attr));
} else if (attr == R.styleable.ComponentLayout_flex_direction) {
flexDirection(YogaFlexDirection.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_wrap) {
wrap(YogaWrap.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_justifyContent) {
justifyContent(YogaJustify.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_alignItems) {
alignItems(YogaAlign.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_alignSelf) {
alignSelf(YogaAlign.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_positionType) {
positionType(YogaPositionType.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex) {
final float flex = a.getFloat(attr, -1);
if (flex >= 0f) {
flex(flex);
}
} else if (attr == R.styleable.ComponentLayout_flex_left) {
positionPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_top) {
positionPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_right) {
positionPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_bottom) {
positionPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_layoutDirection) {
final int layoutDirection = a.getInteger(attr, -1);
layoutDirection(YogaDirection.fromInt(layoutDirection));
}
}
}
/** Crash if the given node has context specific style set. */
@Override
public void assertContextSpecificStyleNotSet() {
List<CharSequence> errorTypes = null;
if ((mPrivateFlags & PFLAG_ALIGN_SELF_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "alignSelf");
}
if ((mPrivateFlags & PFLAG_POSITION_TYPE_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "positionType");
}
if ((mPrivateFlags & PFLAG_FLEX_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "flex");
}
if ((mPrivateFlags & PFLAG_FLEX_GROW_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "flexGrow");
}
if ((mPrivateFlags & PFLAG_MARGIN_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "margin");
}
if (errorTypes != null) {
final CharSequence errorStr = TextUtils.join(", ", errorTypes);
final ComponentsLogger logger = getContext().getLogger();
if (logger != null) {
logger.emitMessage(
WARNING,
"You should not set "
+ errorStr
+ " to a root layout in "
+ getRootComponent().getClass().getSimpleName());
}
}
}
@Override
public DefaultInternalNode deepClone() {
// 1. Return the null layout.
if (this == NULL_LAYOUT) {
return this;
}
// 2. Clone this layout.
final DefaultInternalNode copy = clone();
// 3. Clone the YogaNode of this layout and set it on the cloned layout.
YogaNode node = mYogaNode.cloneWithoutChildren();
copy.mYogaNode = node;
node.setData(copy);
// 4. Deep clone all children and add it to the cloned YogaNode
final int count = getChildCount();
for (int i = 0; i < count; i++) {
copy.addChildAt(getChildAt(i).deepClone(), i);
}
copy.resetResolvedLayoutProperties();
return copy;
}
@Override
public String getSimpleName() {
return mComponents.isEmpty() ? "<null>" : mComponents.get(0).getSimpleName();
}
protected DefaultInternalNode clone() {
try {
return (DefaultInternalNode) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private boolean isPaddingPercent(YogaEdge edge) {
return mIsPaddingPercent != null && mIsPaddingPercent[edge.intValue()];
}
private void applyOverridesRecursive(@Nullable InternalNode node) {
if (ComponentsConfiguration.isDebugModeEnabled && node != null) {
DebugComponent.applyOverrides(mComponentContext, node);
for (int i = 0, count = node.getChildCount(); i < count; i++) {
applyOverridesRecursive(node.getChildAt(i));
}
if (node.hasNestedTree()) {
applyOverridesRecursive(node.getNestedTree());
}
}
}
@ReturnsOwnership
private Edges getNestedTreePadding() {
NestedTreeProps props = getOrCreateNestedTreeProps();
if (props.mNestedTreePadding == null) {
props.mNestedTreePadding = new Edges();
}
return props.mNestedTreePadding;
}
private float resolveHorizontalEdges(Edges spacing, YogaEdge edge) {
final boolean isRtl = (mYogaNode.getLayoutDirection() == YogaDirection.RTL);
final YogaEdge resolvedEdge;
switch (edge) {
case LEFT:
resolvedEdge = (isRtl ? YogaEdge.END : YogaEdge.START);
break;
case RIGHT:
resolvedEdge = (isRtl ? YogaEdge.START : YogaEdge.END);
break;
default:
throw new IllegalArgumentException("Not an horizontal padding edge: " + edge);
}
float result = spacing.getRaw(resolvedEdge);
if (YogaConstants.isUndefined(result)) {
result = spacing.get(edge);
}
return result;
}
private void setIsPaddingPercent(YogaEdge edge, boolean isPaddingPercent) {
if (mIsPaddingPercent == null && isPaddingPercent) {
mIsPaddingPercent = new boolean[YogaEdge.ALL.intValue() + 1];
}
if (mIsPaddingPercent != null) {
mIsPaddingPercent[edge.intValue()] = isPaddingPercent;
}
}
private void setPaddingFromBackground(Drawable drawable) {
if (drawable != null) {
final Rect backgroundPadding = new Rect();
if (getDrawablePadding(drawable, backgroundPadding)) {
paddingPx(LEFT, backgroundPadding.left);
paddingPx(TOP, backgroundPadding.top);
paddingPx(RIGHT, backgroundPadding.right);
paddingPx(BOTTOM, backgroundPadding.bottom);
}
}
}
private boolean shouldApplyTouchExpansion() {
return mTouchExpansion != null && mNodeInfo != null && mNodeInfo.hasTouchEventHandlers();
}
static YogaNode createYogaNode(ComponentContext componentContext) {
return componentContext.mYogaNodeFactory != null
? componentContext.mYogaNodeFactory.create()
: NodeConfig.createYogaNode();
}
private @Nullable static <T> EventHandler<T> addVisibilityHandler(
@Nullable EventHandler<T> currentHandler, @Nullable EventHandler<T> newHandler) {
if (currentHandler == null) {
return newHandler;
}
if (newHandler == null) {
return currentHandler;
}
return new DelegatingEventHandler<>(currentHandler, newHandler);
}
/**
* This is a wrapper on top of built in {@link Drawable#getPadding(Rect)} which overrides default
* return value. The reason why we need this - is because on pre-L devices LayerDrawable always
* returns "true" even if drawable doesn't have padding (see https://goo.gl/gExcMQ). Since we
* heavily rely on correctness of this information, we need to check padding manually
*/
private static boolean getDrawablePadding(Drawable drawable, Rect outRect) {
drawable.getPadding(outRect);
return outRect.bottom != 0 || outRect.top != 0 || outRect.left != 0 || outRect.right != 0;
}
}
| litho-core/src/main/java/com/facebook/litho/DefaultInternalNode.java | /*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.os.Build.VERSION_CODES.JELLY_BEAN;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static com.facebook.litho.CommonUtils.addOrCreateList;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentsLogger.LogLevel.WARNING;
import static com.facebook.yoga.YogaEdge.ALL;
import static com.facebook.yoga.YogaEdge.BOTTOM;
import static com.facebook.yoga.YogaEdge.END;
import static com.facebook.yoga.YogaEdge.HORIZONTAL;
import static com.facebook.yoga.YogaEdge.LEFT;
import static com.facebook.yoga.YogaEdge.RIGHT;
import static com.facebook.yoga.YogaEdge.START;
import static com.facebook.yoga.YogaEdge.TOP;
import static com.facebook.yoga.YogaEdge.VERTICAL;
import android.animation.StateListAnimator;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.Px;
import androidx.core.view.ViewCompat;
import com.facebook.infer.annotation.OkToExtend;
import com.facebook.infer.annotation.ReturnsOwnership;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.drawable.ComparableColorDrawable;
import com.facebook.litho.drawable.ComparableDrawable;
import com.facebook.litho.drawable.ComparableResDrawable;
import com.facebook.litho.drawable.DefaultComparableDrawable;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/** Default implementation of {@link InternalNode}. */
@OkToExtend
@ThreadConfined(ThreadConfined.ANY)
public class DefaultInternalNode implements InternalNode, Cloneable {
// Used to check whether or not the framework can use style IDs for
// paddingStart/paddingEnd due to a bug in some Android devices.
private static final boolean SUPPORTS_RTL = (SDK_INT >= JELLY_BEAN_MR1);
// Flags used to indicate that a certain attribute was explicitly set on the node.
private static final long PFLAG_LAYOUT_DIRECTION_IS_SET = 1L << 0;
private static final long PFLAG_ALIGN_SELF_IS_SET = 1L << 1;
private static final long PFLAG_POSITION_TYPE_IS_SET = 1L << 2;
private static final long PFLAG_FLEX_IS_SET = 1L << 3;
private static final long PFLAG_FLEX_GROW_IS_SET = 1L << 4;
private static final long PFLAG_FLEX_SHRINK_IS_SET = 1L << 5;
private static final long PFLAG_FLEX_BASIS_IS_SET = 1L << 6;
private static final long PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET = 1L << 7;
private static final long PFLAG_DUPLICATE_PARENT_STATE_IS_SET = 1L << 8;
private static final long PFLAG_MARGIN_IS_SET = 1L << 9;
private static final long PFLAG_PADDING_IS_SET = 1L << 10;
private static final long PFLAG_POSITION_IS_SET = 1L << 11;
private static final long PFLAG_WIDTH_IS_SET = 1L << 12;
private static final long PFLAG_MIN_WIDTH_IS_SET = 1L << 13;
private static final long PFLAG_MAX_WIDTH_IS_SET = 1L << 14;
private static final long PFLAG_HEIGHT_IS_SET = 1L << 15;
private static final long PFLAG_MIN_HEIGHT_IS_SET = 1L << 16;
private static final long PFLAG_MAX_HEIGHT_IS_SET = 1L << 17;
private static final long PFLAG_BACKGROUND_IS_SET = 1L << 18;
private static final long PFLAG_FOREGROUND_IS_SET = 1L << 19;
private static final long PFLAG_VISIBLE_HANDLER_IS_SET = 1L << 20;
private static final long PFLAG_FOCUSED_HANDLER_IS_SET = 1L << 21;
private static final long PFLAG_FULL_IMPRESSION_HANDLER_IS_SET = 1L << 22;
private static final long PFLAG_INVISIBLE_HANDLER_IS_SET = 1L << 23;
private static final long PFLAG_UNFOCUSED_HANDLER_IS_SET = 1L << 24;
private static final long PFLAG_TOUCH_EXPANSION_IS_SET = 1L << 25;
private static final long PFLAG_ASPECT_RATIO_IS_SET = 1L << 26;
private static final long PFLAG_TRANSITION_KEY_IS_SET = 1L << 27;
private static final long PFLAG_BORDER_IS_SET = 1L << 28;
private static final long PFLAG_STATE_LIST_ANIMATOR_SET = 1L << 29;
private static final long PFLAG_STATE_LIST_ANIMATOR_RES_SET = 1L << 30;
private static final long PFLAG_VISIBLE_RECT_CHANGED_HANDLER_IS_SET = 1L << 31;
private static final long PFLAG_TRANSITION_KEY_TYPE_IS_SET = 1L << 32;
private YogaNode mYogaNode;
private final ComponentContext mComponentContext;
@ThreadConfined(ThreadConfined.ANY)
private final List<Component> mComponents = new ArrayList<>(1);
private final int[] mBorderColors = new int[Border.EDGE_COUNT];
private final float[] mBorderRadius = new float[Border.RADIUS_COUNT];
private @Nullable DiffNode mDiffNode;
private @Nullable NodeInfo mNodeInfo;
private @Nullable NestedTreeProps mNestedTreeProps;
private @Nullable EventHandler<VisibleEvent> mVisibleHandler;
private @Nullable EventHandler<FocusedVisibleEvent> mFocusedHandler;
private @Nullable EventHandler<UnfocusedVisibleEvent> mUnfocusedHandler;
private @Nullable EventHandler<FullImpressionVisibleEvent> mFullImpressionHandler;
private @Nullable EventHandler<InvisibleEvent> mInvisibleHandler;
private @Nullable EventHandler<VisibilityChangedEvent> mVisibilityChangedHandler;
private @Nullable ComparableDrawable mBackground;
private @Nullable ComparableDrawable mForeground;
private @Nullable PathEffect mBorderPathEffect;
private @Nullable StateListAnimator mStateListAnimator;
private @Nullable boolean[] mIsPaddingPercent;
private @Nullable Edges mTouchExpansion;
private @Nullable String mTransitionKey;
private @Nullable Transition.TransitionKeyType mTransitionKeyType;
private @Nullable ArrayList<Transition> mTransitions;
private @Nullable ArrayList<Component> mComponentsNeedingPreviousRenderData;
private @Nullable ArrayList<WorkingRangeContainer.Registration> mWorkingRangeRegistrations;
private @Nullable String mTestKey;
private @Nullable Set<DebugComponent> mDebugComponents = null;
private boolean mDuplicateParentState;
private boolean mForceViewWrapping;
private boolean mCachedMeasuresValid;
private int mImportantForAccessibility = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
private @DrawableRes int mStateListAnimatorRes;
private float mVisibleHeightRatio;
private float mVisibleWidthRatio;
private float mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
private float mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
private float mResolvedX = YogaConstants.UNDEFINED;
private float mResolvedY = YogaConstants.UNDEFINED;
private float mResolvedWidth = YogaConstants.UNDEFINED;
private float mResolvedHeight = YogaConstants.UNDEFINED;
private int mLastWidthSpec = DiffNode.UNSPECIFIED;
private int mLastHeightSpec = DiffNode.UNSPECIFIED;
private float mLastMeasuredWidth = DiffNode.UNSPECIFIED;
private float mLastMeasuredHeight = DiffNode.UNSPECIFIED;
private long mPrivateFlags;
protected DefaultInternalNode(ComponentContext componentContext) {
this(componentContext, createYogaNode(componentContext), true);
}
protected DefaultInternalNode(ComponentContext componentContext, YogaNode yogaNode) {
this(componentContext, yogaNode, true);
}
protected DefaultInternalNode(
ComponentContext componentContext, boolean createDebugComponentsInCtor) {
this(componentContext, createYogaNode(componentContext), createDebugComponentsInCtor);
}
protected DefaultInternalNode(
ComponentContext componentContext, YogaNode yogaNode, boolean createDebugComponentsInCtor) {
if (createDebugComponentsInCtor) {
mDebugComponents = new HashSet<>();
}
if (yogaNode != null) {
yogaNode.setData(this);
}
mYogaNode = yogaNode;
mComponentContext = componentContext;
}
@Override
public void addChildAt(InternalNode child, int index) {
mYogaNode.addChildAt(child.getYogaNode(), index);
}
@Override
public void addComponentNeedingPreviousRenderData(Component component) {
if (mComponentsNeedingPreviousRenderData == null) {
mComponentsNeedingPreviousRenderData = new ArrayList<>(1);
}
mComponentsNeedingPreviousRenderData.add(component);
}
@Override
public void addTransition(Transition transition) {
if (mTransitions == null) {
mTransitions = new ArrayList<>(1);
}
mTransitions.add(transition);
}
@Override
public void addWorkingRanges(List<WorkingRangeContainer.Registration> registrations) {
if (mWorkingRangeRegistrations == null) {
mWorkingRangeRegistrations = new ArrayList<>(registrations.size());
}
mWorkingRangeRegistrations.addAll(registrations);
}
@Override
public InternalNode alignContent(YogaAlign alignContent) {
mYogaNode.setAlignContent(alignContent);
return this;
}
@Override
public InternalNode alignItems(YogaAlign alignItems) {
mYogaNode.setAlignItems(alignItems);
return this;
}
@Override
public void alignSelf(YogaAlign alignSelf) {
mPrivateFlags |= PFLAG_ALIGN_SELF_IS_SET;
mYogaNode.setAlignSelf(alignSelf);
}
@Override
public void appendComponent(Component component) {
mComponents.add(component);
}
@Override
public boolean areCachedMeasuresValid() {
return mCachedMeasuresValid;
}
@Override
public void aspectRatio(float aspectRatio) {
mPrivateFlags |= PFLAG_ASPECT_RATIO_IS_SET;
mYogaNode.setAspectRatio(aspectRatio);
}
@Override
public InternalNode background(@Nullable ComparableDrawable background) {
mPrivateFlags |= PFLAG_BACKGROUND_IS_SET;
mBackground = background;
setPaddingFromBackground(background);
return this;
}
/**
* @deprecated use {@link #background(ComparableDrawable)} more efficient diffing of drawables.
*/
@Deprecated
@Override
public InternalNode background(@Nullable Drawable background) {
if (background instanceof ComparableDrawable) {
return background((ComparableDrawable) background);
}
return background(background != null ? DefaultComparableDrawable.create(background) : null);
}
@Override
public InternalNode backgroundColor(@ColorInt int backgroundColor) {
return background(ComparableColorDrawable.create(backgroundColor));
}
@Override
public InternalNode backgroundRes(@DrawableRes int resId) {
if (resId == 0) {
return background(null);
}
return background(ComparableResDrawable.create(mComponentContext.getAndroidContext(), resId));
}
@Override
public InternalNode border(Border border) {
mPrivateFlags |= PFLAG_BORDER_IS_SET;
for (int i = 0, length = border.mEdgeWidths.length; i < length; ++i) {
setBorderWidth(Border.edgeFromIndex(i), border.mEdgeWidths[i]);
}
System.arraycopy(border.mEdgeColors, 0, mBorderColors, 0, mBorderColors.length);
System.arraycopy(border.mRadius, 0, mBorderRadius, 0, mBorderRadius.length);
mBorderPathEffect = border.mPathEffect;
return this;
}
@Override
public void border(Edges width, int[] colors, float[] radii) {
mPrivateFlags |= PFLAG_BORDER_IS_SET;
mYogaNode.setBorder(LEFT, width.getRaw(YogaEdge.LEFT));
mYogaNode.setBorder(TOP, width.getRaw(YogaEdge.TOP));
mYogaNode.setBorder(RIGHT, width.getRaw(YogaEdge.RIGHT));
mYogaNode.setBorder(BOTTOM, width.getRaw(YogaEdge.BOTTOM));
mYogaNode.setBorder(VERTICAL, width.getRaw(YogaEdge.VERTICAL));
mYogaNode.setBorder(HORIZONTAL, width.getRaw(YogaEdge.HORIZONTAL));
mYogaNode.setBorder(START, width.getRaw(YogaEdge.START));
mYogaNode.setBorder(END, width.getRaw(YogaEdge.END));
mYogaNode.setBorder(ALL, width.getRaw(YogaEdge.ALL));
System.arraycopy(colors, 0, mBorderColors, 0, colors.length);
System.arraycopy(radii, 0, mBorderRadius, 0, radii.length);
}
@Override
public void calculateLayout(float width, float height) {
applyOverridesRecursive(this);
mYogaNode.calculateLayout(width, height);
}
@Override
public void calculateLayout() {
calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
}
@Override
public InternalNode child(Component child) {
if (child != null) {
return child(Layout.create(mComponentContext, child));
}
return this;
}
@Override
public InternalNode child(Component.Builder<?> child) {
if (child != null) {
child(child.build());
}
return this;
}
@Override
public InternalNode child(InternalNode child) {
if (child != null && child != NULL_LAYOUT) {
addChildAt(child, mYogaNode.getChildCount());
}
return this;
}
@Override
public InternalNode duplicateParentState(boolean duplicateParentState) {
mPrivateFlags |= PFLAG_DUPLICATE_PARENT_STATE_IS_SET;
mDuplicateParentState = duplicateParentState;
return this;
}
@Override
public void flex(float flex) {
mPrivateFlags |= PFLAG_FLEX_IS_SET;
mYogaNode.setFlex(flex);
}
// Used by stetho to re-set auto value
@Override
public InternalNode flexBasisAuto() {
mYogaNode.setFlexBasisAuto();
return this;
}
@Override
public void flexBasisPercent(float percent) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasisPercent(percent);
}
@Override
public void flexBasisPx(@Px int flexBasis) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasis(flexBasis);
}
@Override
public InternalNode flexDirection(YogaFlexDirection direction) {
mYogaNode.setFlexDirection(direction);
return this;
}
@Override
public void flexGrow(float flexGrow) {
mPrivateFlags |= PFLAG_FLEX_GROW_IS_SET;
mYogaNode.setFlexGrow(flexGrow);
}
@Override
public void flexShrink(float flexShrink) {
mPrivateFlags |= PFLAG_FLEX_SHRINK_IS_SET;
mYogaNode.setFlexShrink(flexShrink);
}
@Override
public InternalNode focusedHandler(@Nullable EventHandler<FocusedVisibleEvent> focusedHandler) {
mPrivateFlags |= PFLAG_FOCUSED_HANDLER_IS_SET;
mFocusedHandler = addVisibilityHandler(mFocusedHandler, focusedHandler);
return this;
}
/**
* @deprecated use {@link #foreground(ComparableDrawable)} more efficient diffing of drawables.
*/
@Deprecated
@Override
public InternalNode foreground(@Nullable Drawable foreground) {
return foreground(foreground != null ? DefaultComparableDrawable.create(foreground) : null);
}
@Override
public InternalNode foreground(@Nullable ComparableDrawable foreground) {
mPrivateFlags |= PFLAG_FOREGROUND_IS_SET;
mForeground = foreground;
return this;
}
@Override
public InternalNode foregroundColor(@ColorInt int foregroundColor) {
return foreground(ComparableColorDrawable.create(foregroundColor));
}
@Override
public InternalNode foregroundRes(@DrawableRes int resId) {
if (resId == 0) {
return foreground(null);
}
return foreground(ComparableResDrawable.create(mComponentContext.getAndroidContext(), resId));
}
@Override
public InternalNode fullImpressionHandler(
@Nullable EventHandler<FullImpressionVisibleEvent> fullImpressionHandler) {
mPrivateFlags |= PFLAG_FULL_IMPRESSION_HANDLER_IS_SET;
mFullImpressionHandler = addVisibilityHandler(mFullImpressionHandler, fullImpressionHandler);
return this;
}
@Override
public int[] getBorderColors() {
return mBorderColors;
}
@Override
public @Nullable PathEffect getBorderPathEffect() {
return mBorderPathEffect;
}
@Override
public float[] getBorderRadius() {
return mBorderRadius;
}
@Override
public @Nullable InternalNode getChildAt(int index) {
if (mYogaNode.getChildAt(index) == null) {
return null;
}
return (InternalNode) mYogaNode.getChildAt(index).getData();
}
@Override
public int getChildCount() {
return mYogaNode.getChildCount();
}
@Override
public int getChildIndex(InternalNode child) {
for (int i = 0, count = mYogaNode.getChildCount(); i < count; i++) {
if (mYogaNode.getChildAt(i) == child.getYogaNode()) {
return i;
}
}
return -1;
}
/**
* Return the list of components contributing to this InternalNode. We have no need for this in
* production but it is useful information to have while debugging. Therefor this list will only
* contain the root component if running in production mode.
*/
@Override
public List<Component> getComponents() {
return mComponents;
}
@Override
public @Nullable ArrayList<Component> getComponentsNeedingPreviousRenderData() {
return mComponentsNeedingPreviousRenderData;
}
@Override
public ComponentContext getContext() {
return mComponentContext;
}
@Override
public @Nullable DiffNode getDiffNode() {
return mDiffNode;
}
@Override
public void setDiffNode(@Nullable DiffNode diffNode) {
mDiffNode = diffNode;
}
@Override
public @Nullable EventHandler<FocusedVisibleEvent> getFocusedHandler() {
return mFocusedHandler;
}
@Override
public @Nullable ComparableDrawable getForeground() {
return mForeground;
}
@Override
public @Nullable EventHandler<FullImpressionVisibleEvent> getFullImpressionHandler() {
return mFullImpressionHandler;
}
@Override
public int getImportantForAccessibility() {
return mImportantForAccessibility;
}
@Nullable
@Override
public EventHandler<InvisibleEvent> getInvisibleHandler() {
return mInvisibleHandler;
}
@Override
public int getLastHeightSpec() {
return mLastHeightSpec;
}
@Override
public void setLastHeightSpec(int heightSpec) {
mLastHeightSpec = heightSpec;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned for the
* height. This is used together with {@link InternalNode#getLastHeightSpec()} to implement
* measure caching.
*/
@Override
public float getLastMeasuredHeight() {
return mLastMeasuredHeight;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the height.
*/
@Override
public void setLastMeasuredHeight(float lastMeasuredHeight) {
mLastMeasuredHeight = lastMeasuredHeight;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned for the
* width. This is used together with {@link InternalNode#getLastWidthSpec()} to implement measure
* caching.
*/
@Override
public float getLastMeasuredWidth() {
return mLastMeasuredWidth;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the width.
*/
@Override
public void setLastMeasuredWidth(float lastMeasuredWidth) {
mLastMeasuredWidth = lastMeasuredWidth;
}
@Override
public int getLastWidthSpec() {
return mLastWidthSpec;
}
@Override
public void setLastWidthSpec(int widthSpec) {
mLastWidthSpec = widthSpec;
}
@Override
public int getLayoutBorder(YogaEdge edge) {
return FastMath.round(mYogaNode.getLayoutBorder(edge));
}
@Override
public float getMaxHeight() {
return mYogaNode.getMaxHeight().value;
}
@Override
public float getMaxWidth() {
return mYogaNode.getMaxWidth().value;
}
@Override
public float getMinHeight() {
return mYogaNode.getMinHeight().value;
}
@Override
public float getMinWidth() {
return mYogaNode.getMinWidth().value;
}
@Override
public @Nullable InternalNode getNestedTree() {
return mNestedTreeProps != null ? mNestedTreeProps.mNestedTree : null;
}
/**
* Set the nested tree before measuring it in order to transfer over important information such as
* layout direction needed during measurement.
*/
@Override
public void setNestedTree(InternalNode nestedTree) {
if (nestedTree != NULL_LAYOUT) {
nestedTree.getOrCreateNestedTreeProps().mNestedTreeHolder = this;
}
getOrCreateNestedTreeProps().mNestedTree = nestedTree;
}
@Override
public @Nullable InternalNode getNestedTreeHolder() {
return mNestedTreeProps != null ? mNestedTreeProps.mNestedTreeHolder : null;
}
@Override
public @Nullable NodeInfo getNodeInfo() {
return mNodeInfo;
}
@Override
public void setNodeInfo(NodeInfo nodeInfo) {
mNodeInfo = nodeInfo;
}
@Override
public NestedTreeProps getOrCreateNestedTreeProps() {
if (mNestedTreeProps == null) {
mNestedTreeProps = new NestedTreeProps();
}
return mNestedTreeProps;
}
@Override
public NodeInfo getOrCreateNodeInfo() {
if (mNodeInfo == null) {
if (ComponentsConfiguration.isSparseNodeInfoIsEnabled) {
mNodeInfo = new SparseNodeInfo();
} else {
mNodeInfo = new DefaultNodeInfo();
}
}
return mNodeInfo;
}
@Override
public @Nullable InternalNode getParent() {
if (mYogaNode == null || mYogaNode.getOwner() == null) {
return null;
}
return (InternalNode) mYogaNode.getOwner().getData();
}
@Override
public @Nullable TreeProps getPendingTreeProps() {
return mNestedTreeProps != null ? mNestedTreeProps.mPendingTreeProps : null;
}
@Override
public @Nullable Component getRootComponent() {
return mComponents.isEmpty() ? null : mComponents.get(0);
}
@Override
public void setRootComponent(Component component) {
mComponents.clear();
mComponents.add(component);
}
@Override
public @Nullable StateListAnimator getStateListAnimator() {
return mStateListAnimator;
}
@Override
public @DrawableRes int getStateListAnimatorRes() {
return mStateListAnimatorRes;
}
@Override
public YogaDirection getStyleDirection() {
return mYogaNode.getStyleDirection();
}
@Override
public float getStyleHeight() {
return mYogaNode.getHeight().value;
}
@Override
public float getStyleWidth() {
return mYogaNode.getWidth().value;
}
/**
* A unique identifier which may be set for retrieving a component and its bounds when testing.
*/
@Override
public @Nullable String getTestKey() {
return mTestKey;
}
@Override
public @Nullable Edges getTouchExpansion() {
return mTouchExpansion;
}
@Override
public int getTouchExpansionBottom() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(YogaEdge.BOTTOM));
}
@Override
public int getTouchExpansionLeft() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionLeft)) {
mResolvedTouchExpansionLeft = resolveHorizontalEdges(mTouchExpansion, YogaEdge.LEFT);
}
return FastMath.round(mResolvedTouchExpansionLeft);
}
@Override
public int getTouchExpansionRight() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionRight)) {
mResolvedTouchExpansionRight = resolveHorizontalEdges(mTouchExpansion, YogaEdge.RIGHT);
}
return FastMath.round(mResolvedTouchExpansionRight);
}
@Override
public int getTouchExpansionTop() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(YogaEdge.TOP));
}
@Override
public @Nullable String getTransitionKey() {
return mTransitionKey;
}
@Override
public @Nullable Transition.TransitionKeyType getTransitionKeyType() {
return mTransitionKeyType;
}
@Override
public @Nullable ArrayList<Transition> getTransitions() {
return mTransitions;
}
@Override
public @Nullable EventHandler<UnfocusedVisibleEvent> getUnfocusedHandler() {
return mUnfocusedHandler;
}
@Override
public @Nullable EventHandler<VisibilityChangedEvent> getVisibilityChangedHandler() {
return mVisibilityChangedHandler;
}
@Override
public @Nullable EventHandler<VisibleEvent> getVisibleHandler() {
return mVisibleHandler;
}
@Override
public float getVisibleHeightRatio() {
return mVisibleHeightRatio;
}
@Override
public float getVisibleWidthRatio() {
return mVisibleWidthRatio;
}
@Override
public @Nullable ArrayList<WorkingRangeContainer.Registration> getWorkingRangeRegistrations() {
return mWorkingRangeRegistrations;
}
@Override
public YogaNode getYogaNode() {
return mYogaNode;
}
@Override
public boolean hasBorderColor() {
for (int color : mBorderColors) {
if (color != Color.TRANSPARENT) {
return true;
}
}
return false;
}
@Override
public boolean hasNestedTree() {
return mNestedTreeProps != null && mNestedTreeProps.mNestedTree != null;
}
@Override
public boolean hasNewLayout() {
return mYogaNode.hasNewLayout();
}
@Override
public boolean hasStateListAnimatorResSet() {
return (mPrivateFlags & PFLAG_STATE_LIST_ANIMATOR_RES_SET) != 0;
}
@Override
public boolean hasTouchExpansion() {
return ((mPrivateFlags & PFLAG_TOUCH_EXPANSION_IS_SET) != 0L);
}
@Override
public boolean hasTransitionKey() {
return !TextUtils.isEmpty(mTransitionKey);
}
@Override
public boolean hasVisibilityHandlers() {
return mVisibleHandler != null
|| mFocusedHandler != null
|| mUnfocusedHandler != null
|| mFullImpressionHandler != null
|| mInvisibleHandler != null
|| mVisibilityChangedHandler != null;
}
// Used by stetho to re-set auto value
@Override
public InternalNode heightAuto() {
mYogaNode.setHeightAuto();
return this;
}
@Override
public void heightPercent(float percent) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeightPercent(percent);
}
@Override
public void heightPx(@Px int height) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeight(height);
}
@Override
public InternalNode importantForAccessibility(int importantForAccessibility) {
mPrivateFlags |= PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET;
mImportantForAccessibility = importantForAccessibility;
return this;
}
@Override
public InternalNode invisibleHandler(@Nullable EventHandler<InvisibleEvent> invisibleHandler) {
mPrivateFlags |= PFLAG_INVISIBLE_HANDLER_IS_SET;
mInvisibleHandler = addVisibilityHandler(mInvisibleHandler, invisibleHandler);
return this;
}
@Override
public boolean isDuplicateParentStateEnabled() {
return mDuplicateParentState;
}
@Override
public boolean isForceViewWrapping() {
return mForceViewWrapping;
}
@Override
public boolean isImportantForAccessibilityIsSet() {
return (mPrivateFlags & PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET) == 0L
|| mImportantForAccessibility == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
}
/**
* For testing and debugging purposes only where initialization may have not occurred. For any
* production use, this should never be necessary.
*/
@Override
public boolean isInitialized() {
return mYogaNode != null && mComponentContext != null;
}
@Override
public boolean isLayoutDirectionInherit() {
return (mPrivateFlags & PFLAG_LAYOUT_DIRECTION_IS_SET) == 0L
|| getResolvedLayoutDirection() == YogaDirection.INHERIT;
}
/**
* @return Whether this node is holding a nested tree or not. The decision was made during tree
* creation {@link ComponentLifecycle#createLayout(ComponentContext, boolean)}.
*/
@Override
public boolean isNestedTreeHolder() {
return mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder;
}
private boolean isPaddingPercent(YogaEdge edge) {
return mIsPaddingPercent != null && mIsPaddingPercent[edge.intValue()];
}
@Override
public void isReferenceBaseline(boolean isReferenceBaseline) {
mYogaNode.setIsReferenceBaseline(isReferenceBaseline);
}
@Override
public InternalNode justifyContent(YogaJustify justifyContent) {
mYogaNode.setJustifyContent(justifyContent);
return this;
}
@Override
public void layoutDirection(YogaDirection direction) {
mPrivateFlags |= PFLAG_LAYOUT_DIRECTION_IS_SET;
mYogaNode.setDirection(direction);
}
@Override
public void marginAuto(YogaEdge edge) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginAuto(edge);
}
@Override
public void marginPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginPercent(edge, percent);
}
@Override
public void marginPx(YogaEdge edge, @Px int margin) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMargin(edge, margin);
}
/** Mark this node as a nested tree root holder. */
@Override
public void markIsNestedTreeHolder(TreeProps currentTreeProps) {
getOrCreateNestedTreeProps().mIsNestedTreeHolder = true;
getOrCreateNestedTreeProps().mPendingTreeProps = TreeProps.copy(currentTreeProps);
}
@Override
public void markLayoutSeen() {
mYogaNode.markLayoutSeen();
}
@Override
public void maxHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeightPercent(percent);
}
@Override
public void maxHeightPx(@Px int maxHeight) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeight(maxHeight);
}
@Override
public void maxWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidthPercent(percent);
}
@Override
public void maxWidthPx(@Px int maxWidth) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidth(maxWidth);
}
@Override
public void minHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeightPercent(percent);
}
@Override
public void minHeightPx(@Px int minHeight) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeight(minHeight);
}
@Override
public void minWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidthPercent(percent);
}
@Override
public void minWidthPx(@Px int minWidth) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidth(minWidth);
}
@Override
public void paddingPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder) {
getNestedTreePadding().set(edge, percent);
setIsPaddingPercent(edge, true);
} else {
mYogaNode.setPaddingPercent(edge, percent);
}
}
@Override
public void paddingPx(YogaEdge edge, @Px int padding) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder) {
getNestedTreePadding().set(edge, padding);
setIsPaddingPercent(edge, false);
} else {
mYogaNode.setPadding(edge, padding);
}
}
@Override
public void positionPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPositionPercent(edge, percent);
}
@Override
public void positionPx(YogaEdge edge, @Px int position) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPosition(edge, position);
}
@Override
public void positionType(@Nullable YogaPositionType positionType) {
mPrivateFlags |= PFLAG_POSITION_TYPE_IS_SET;
mYogaNode.setPositionType(positionType);
}
/** Continually walks the node hierarchy until a node returns a non inherited layout direction */
@Override
public YogaDirection recursivelyResolveLayoutDirection() {
YogaNode yogaNode = mYogaNode;
while (yogaNode != null && yogaNode.getLayoutDirection() == YogaDirection.INHERIT) {
yogaNode = yogaNode.getOwner();
}
return yogaNode == null ? YogaDirection.INHERIT : yogaNode.getLayoutDirection();
}
@Override
public void registerDebugComponent(DebugComponent debugComponent) {
if (mDebugComponents == null) {
mDebugComponents = new HashSet<>();
}
mDebugComponents.add(debugComponent);
}
@Override
public InternalNode removeChildAt(int index) {
return (InternalNode) mYogaNode.removeChildAt(index).getData();
}
/** This method marks all resolved layout property values to undefined. */
@Override
public void resetResolvedLayoutProperties() {
mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
mResolvedX = YogaConstants.UNDEFINED;
mResolvedY = YogaConstants.UNDEFINED;
mResolvedWidth = YogaConstants.UNDEFINED;
mResolvedHeight = YogaConstants.UNDEFINED;
}
@Override
public void setBorderWidth(YogaEdge edge, @Px int borderWidth) {
if (mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder) {
NestedTreeProps props = getOrCreateNestedTreeProps();
if (props.mNestedTreeBorderWidth == null) {
props.mNestedTreeBorderWidth = new Edges();
}
props.mNestedTreeBorderWidth.set(edge, borderWidth);
} else {
mYogaNode.setBorder(edge, borderWidth);
}
}
@Override
public void setCachedMeasuresValid(boolean valid) {
mCachedMeasuresValid = valid;
}
@Override
public void setMeasureFunction(YogaMeasureFunction measureFunction) {
mYogaNode.setMeasureFunction(measureFunction);
}
@Override
public void setStyleHeightFromSpec(int heightSpec) {
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.UNSPECIFIED:
mYogaNode.setHeight(YogaConstants.UNDEFINED);
break;
case SizeSpec.AT_MOST:
mYogaNode.setMaxHeight(SizeSpec.getSize(heightSpec));
break;
case SizeSpec.EXACTLY:
mYogaNode.setHeight(SizeSpec.getSize(heightSpec));
break;
}
}
@Override
public void setStyleWidthFromSpec(int widthSpec) {
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.UNSPECIFIED:
mYogaNode.setWidth(YogaConstants.UNDEFINED);
break;
case SizeSpec.AT_MOST:
mYogaNode.setMaxWidth(SizeSpec.getSize(widthSpec));
break;
case SizeSpec.EXACTLY:
mYogaNode.setWidth(SizeSpec.getSize(widthSpec));
break;
}
}
@Override
public boolean shouldDrawBorders() {
return hasBorderColor()
&& (mYogaNode.getLayoutBorder(LEFT) != 0
|| mYogaNode.getLayoutBorder(TOP) != 0
|| mYogaNode.getLayoutBorder(RIGHT) != 0
|| mYogaNode.getLayoutBorder(BOTTOM) != 0);
}
@Override
public InternalNode stateListAnimator(@Nullable StateListAnimator stateListAnimator) {
mPrivateFlags |= PFLAG_STATE_LIST_ANIMATOR_SET;
mStateListAnimator = stateListAnimator;
wrapInView();
return this;
}
@Override
public InternalNode stateListAnimatorRes(@DrawableRes int resId) {
mPrivateFlags |= PFLAG_STATE_LIST_ANIMATOR_RES_SET;
mStateListAnimatorRes = resId;
wrapInView();
return this;
}
@Override
public InternalNode testKey(@Nullable String testKey) {
mTestKey = testKey;
return this;
}
@Override
public InternalNode touchExpansionPx(YogaEdge edge, @Px int touchExpansion) {
if (mTouchExpansion == null) {
mTouchExpansion = new Edges();
}
mPrivateFlags |= PFLAG_TOUCH_EXPANSION_IS_SET;
mTouchExpansion.set(edge, touchExpansion);
return this;
}
@Override
public InternalNode transitionKey(@Nullable String key) {
if (SDK_INT >= ICE_CREAM_SANDWICH && !TextUtils.isEmpty(key)) {
mPrivateFlags |= PFLAG_TRANSITION_KEY_IS_SET;
mTransitionKey = key;
}
return this;
}
@Override
public InternalNode transitionKeyType(@Nullable Transition.TransitionKeyType type) {
mPrivateFlags |= PFLAG_TRANSITION_KEY_TYPE_IS_SET;
mTransitionKeyType = type;
return this;
}
@Override
public InternalNode unfocusedHandler(
@Nullable EventHandler<UnfocusedVisibleEvent> unfocusedHandler) {
mPrivateFlags |= PFLAG_UNFOCUSED_HANDLER_IS_SET;
mUnfocusedHandler = addVisibilityHandler(mUnfocusedHandler, unfocusedHandler);
return this;
}
@Override
public void useHeightAsBaseline(boolean useHeightAsBaselineFunction) {
if (useHeightAsBaselineFunction) {
mYogaNode.setBaselineFunction(
new YogaBaselineFunction() {
@Override
public float baseline(YogaNode yogaNode, float width, float height) {
return height;
}
});
}
}
@Override
public InternalNode visibilityChangedHandler(
@Nullable EventHandler<VisibilityChangedEvent> visibilityChangedHandler) {
mPrivateFlags |= PFLAG_VISIBLE_RECT_CHANGED_HANDLER_IS_SET;
mVisibilityChangedHandler =
addVisibilityHandler(mVisibilityChangedHandler, visibilityChangedHandler);
return this;
}
@Override
public InternalNode visibleHandler(@Nullable EventHandler<VisibleEvent> visibleHandler) {
mPrivateFlags |= PFLAG_VISIBLE_HANDLER_IS_SET;
mVisibleHandler = addVisibilityHandler(mVisibleHandler, visibleHandler);
return this;
}
@Override
public InternalNode visibleHeightRatio(float visibleHeightRatio) {
mVisibleHeightRatio = visibleHeightRatio;
return this;
}
@Override
public InternalNode visibleWidthRatio(float visibleWidthRatio) {
mVisibleWidthRatio = visibleWidthRatio;
return this;
}
@Override
public InternalNode widthAuto() {
mYogaNode.setWidthAuto();
return this;
}
@Override
public void widthPercent(float percent) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidthPercent(percent);
}
@Override
public void widthPx(@Px int width) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidth(width);
}
@Override
public InternalNode wrap(YogaWrap wrap) {
mYogaNode.setWrap(wrap);
return this;
}
@Override
public InternalNode wrapInView() {
mForceViewWrapping = true;
return this;
}
@Px
@Override
public int getX() {
if (YogaConstants.isUndefined(mResolvedX)) {
mResolvedX = mYogaNode.getLayoutX();
}
return (int) mResolvedX;
}
@Px
@Override
public int getY() {
if (YogaConstants.isUndefined(mResolvedY)) {
mResolvedY = mYogaNode.getLayoutY();
}
return (int) mResolvedY;
}
@Px
@Override
public int getWidth() {
if (YogaConstants.isUndefined(mResolvedWidth)) {
mResolvedWidth = mYogaNode.getLayoutWidth();
}
return (int) mResolvedWidth;
}
@Px
@Override
public int getHeight() {
if (YogaConstants.isUndefined(mResolvedHeight)) {
mResolvedHeight = mYogaNode.getLayoutHeight();
}
return (int) mResolvedHeight;
}
@Px
@Override
public int getPaddingTop() {
return FastMath.round(mYogaNode.getLayoutPadding(TOP));
}
@Px
@Override
public int getPaddingRight() {
return FastMath.round(mYogaNode.getLayoutPadding(RIGHT));
}
@Px
@Override
public int getPaddingBottom() {
return FastMath.round(mYogaNode.getLayoutPadding(BOTTOM));
}
@Px
@Override
public int getPaddingLeft() {
return FastMath.round(mYogaNode.getLayoutPadding(LEFT));
}
@Override
public boolean isPaddingSet() {
return (mPrivateFlags & PFLAG_PADDING_IS_SET) != 0L;
}
@Override
public @Nullable ComparableDrawable getBackground() {
return mBackground;
}
@Override
public YogaDirection getResolvedLayoutDirection() {
return mYogaNode.getLayoutDirection();
}
@Override
public void copyInto(InternalNode target) {
if (target == NULL_LAYOUT) {
return;
}
if (mNodeInfo != null) {
if (target.getNodeInfo() == null) {
target.setNodeInfo(mNodeInfo);
} else {
mNodeInfo.copyInto(target.getOrCreateNodeInfo());
}
}
if (target.isLayoutDirectionInherit()) {
target.layoutDirection(getResolvedLayoutDirection());
}
if (target.isImportantForAccessibilityIsSet()) {
target.importantForAccessibility(mImportantForAccessibility);
}
if ((mPrivateFlags & PFLAG_DUPLICATE_PARENT_STATE_IS_SET) != 0L) {
target.duplicateParentState(mDuplicateParentState);
}
if ((mPrivateFlags & PFLAG_BACKGROUND_IS_SET) != 0L) {
target.background(mBackground);
}
if ((mPrivateFlags & PFLAG_FOREGROUND_IS_SET) != 0L) {
target.foreground(mForeground);
}
if (mForceViewWrapping) {
target.wrapInView();
}
if ((mPrivateFlags & PFLAG_VISIBLE_HANDLER_IS_SET) != 0L) {
target.visibleHandler(mVisibleHandler);
}
if ((mPrivateFlags & PFLAG_FOCUSED_HANDLER_IS_SET) != 0L) {
target.focusedHandler(mFocusedHandler);
}
if ((mPrivateFlags & PFLAG_FULL_IMPRESSION_HANDLER_IS_SET) != 0L) {
target.fullImpressionHandler(mFullImpressionHandler);
}
if ((mPrivateFlags & PFLAG_INVISIBLE_HANDLER_IS_SET) != 0L) {
target.invisibleHandler(mInvisibleHandler);
}
if ((mPrivateFlags & PFLAG_UNFOCUSED_HANDLER_IS_SET) != 0L) {
target.unfocusedHandler(mUnfocusedHandler);
}
if ((mPrivateFlags & PFLAG_VISIBLE_RECT_CHANGED_HANDLER_IS_SET) != 0L) {
target.visibilityChangedHandler(mVisibilityChangedHandler);
}
if (mTestKey != null) {
target.testKey(mTestKey);
}
if ((mPrivateFlags & PFLAG_PADDING_IS_SET) != 0L) {
if (mNestedTreeProps == null || mNestedTreeProps.mNestedTreePadding == null) {
throw new IllegalStateException(
"copyInto() must be used when resolving a nestedTree. If padding was set on the holder node, we must have a mNestedTreePadding instance");
}
for (int i = 0; i < Edges.EDGES_LENGTH; i++) {
float value = mNestedTreeProps.mNestedTreePadding.getRaw(i);
if (!YogaConstants.isUndefined(value)) {
final YogaEdge edge = YogaEdge.fromInt(i);
if (isPaddingPercent(edge)) {
target.paddingPercent(edge, value);
} else {
target.paddingPx(edge, (int) value);
}
}
}
}
if ((mPrivateFlags & PFLAG_BORDER_IS_SET) != 0L) {
if (mNestedTreeProps == null || mNestedTreeProps.mNestedTreeBorderWidth == null) {
throw new IllegalStateException(
"copyInto() must be used when resolving a nestedTree.If border width was set on the holder node, we must have a mNestedTreeBorderWidth instance");
}
target.border(mNestedTreeProps.mNestedTreeBorderWidth, mBorderColors, mBorderRadius);
}
if ((mPrivateFlags & PFLAG_TRANSITION_KEY_IS_SET) != 0L) {
target.transitionKey(mTransitionKey);
}
if ((mPrivateFlags & PFLAG_TRANSITION_KEY_TYPE_IS_SET) != 0L) {
target.transitionKeyType(mTransitionKeyType);
}
if (mVisibleHeightRatio != 0) {
target.visibleHeightRatio(mVisibleHeightRatio);
}
if (mVisibleWidthRatio != 0) {
target.visibleWidthRatio(mVisibleWidthRatio);
}
if ((mPrivateFlags & PFLAG_STATE_LIST_ANIMATOR_SET) != 0L) {
target.stateListAnimator(mStateListAnimator);
}
if ((mPrivateFlags & PFLAG_STATE_LIST_ANIMATOR_RES_SET) != 0L) {
target.stateListAnimatorRes(mStateListAnimatorRes);
}
}
private void applyOverridesRecursive(@Nullable InternalNode node) {
if (ComponentsConfiguration.isDebugModeEnabled && node != null) {
DebugComponent.applyOverrides(mComponentContext, node);
for (int i = 0, count = node.getChildCount(); i < count; i++) {
applyOverridesRecursive(node.getChildAt(i));
}
if (node.hasNestedTree()) {
applyOverridesRecursive(node.getNestedTree());
}
}
}
@Override
public void applyAttributes(TypedArray a) {
for (int i = 0, size = a.getIndexCount(); i < size; i++) {
final int attr = a.getIndex(i);
if (attr == R.styleable.ComponentLayout_android_layout_width) {
int width = a.getLayoutDimension(attr, -1);
// We don't support WRAP_CONTENT or MATCH_PARENT so no-op for them
if (width >= 0) {
widthPx(width);
}
} else if (attr == R.styleable.ComponentLayout_android_layout_height) {
int height = a.getLayoutDimension(attr, -1);
// We don't support WRAP_CONTENT or MATCH_PARENT so no-op for them
if (height >= 0) {
heightPx(height);
}
} else if (attr == R.styleable.ComponentLayout_android_minHeight) {
minHeightPx(a.getDimensionPixelSize(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_minWidth) {
minWidthPx(a.getDimensionPixelSize(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingLeft) {
paddingPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingTop) {
paddingPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingRight) {
paddingPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingBottom) {
paddingPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingStart && SUPPORTS_RTL) {
paddingPx(START, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingEnd && SUPPORTS_RTL) {
paddingPx(END, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_padding) {
paddingPx(ALL, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginLeft) {
marginPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginTop) {
marginPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginRight) {
marginPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginBottom) {
marginPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginStart && SUPPORTS_RTL) {
marginPx(START, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginEnd && SUPPORTS_RTL) {
marginPx(END, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_margin) {
marginPx(ALL, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_importantForAccessibility
&& SDK_INT >= JELLY_BEAN) {
importantForAccessibility(a.getInt(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_duplicateParentState) {
duplicateParentState(a.getBoolean(attr, false));
} else if (attr == R.styleable.ComponentLayout_android_background) {
if (TypedArrayUtils.isColorAttribute(a, R.styleable.ComponentLayout_android_background)) {
backgroundColor(a.getColor(attr, 0));
} else {
backgroundRes(a.getResourceId(attr, -1));
}
} else if (attr == R.styleable.ComponentLayout_android_foreground) {
if (TypedArrayUtils.isColorAttribute(a, R.styleable.ComponentLayout_android_foreground)) {
foregroundColor(a.getColor(attr, 0));
} else {
foregroundRes(a.getResourceId(attr, -1));
}
} else if (attr == R.styleable.ComponentLayout_android_contentDescription) {
getOrCreateNodeInfo().setContentDescription(a.getString(attr));
} else if (attr == R.styleable.ComponentLayout_flex_direction) {
flexDirection(YogaFlexDirection.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_wrap) {
wrap(YogaWrap.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_justifyContent) {
justifyContent(YogaJustify.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_alignItems) {
alignItems(YogaAlign.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_alignSelf) {
alignSelf(YogaAlign.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex_positionType) {
positionType(YogaPositionType.fromInt(a.getInteger(attr, 0)));
} else if (attr == R.styleable.ComponentLayout_flex) {
final float flex = a.getFloat(attr, -1);
if (flex >= 0f) {
flex(flex);
}
} else if (attr == R.styleable.ComponentLayout_flex_left) {
positionPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_top) {
positionPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_right) {
positionPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_bottom) {
positionPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_flex_layoutDirection) {
final int layoutDirection = a.getInteger(attr, -1);
layoutDirection(YogaDirection.fromInt(layoutDirection));
}
}
}
@Override
public DefaultInternalNode deepClone() {
// 1. Return the null layout.
if (this == NULL_LAYOUT) {
return this;
}
// 2. Clone this layout.
final DefaultInternalNode copy = clone();
// 3. Clone the YogaNode of this layout and set it on the cloned layout.
YogaNode node = mYogaNode.cloneWithoutChildren();
copy.mYogaNode = node;
node.setData(copy);
// 4. Deep clone all children and add it to the cloned YogaNode
final int count = getChildCount();
for (int i = 0; i < count; i++) {
copy.addChildAt(getChildAt(i).deepClone(), i);
}
copy.mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
copy.mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
copy.mResolvedX = YogaConstants.UNDEFINED;
copy.mResolvedY = YogaConstants.UNDEFINED;
copy.mResolvedWidth = YogaConstants.UNDEFINED;
copy.mResolvedHeight = YogaConstants.UNDEFINED;
return copy;
}
@Override
public String getSimpleName() {
return mComponents.isEmpty() ? "<null>" : mComponents.get(0).getSimpleName();
}
protected DefaultInternalNode clone() {
try {
return (DefaultInternalNode) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@ReturnsOwnership
private Edges getNestedTreePadding() {
NestedTreeProps props = getOrCreateNestedTreeProps();
if (props.mNestedTreePadding == null) {
props.mNestedTreePadding = new Edges();
}
return props.mNestedTreePadding;
}
private float resolveHorizontalEdges(Edges spacing, YogaEdge edge) {
final boolean isRtl = (mYogaNode.getLayoutDirection() == YogaDirection.RTL);
final YogaEdge resolvedEdge;
switch (edge) {
case LEFT:
resolvedEdge = (isRtl ? YogaEdge.END : YogaEdge.START);
break;
case RIGHT:
resolvedEdge = (isRtl ? YogaEdge.START : YogaEdge.END);
break;
default:
throw new IllegalArgumentException("Not an horizontal padding edge: " + edge);
}
float result = spacing.getRaw(resolvedEdge);
if (YogaConstants.isUndefined(result)) {
result = spacing.get(edge);
}
return result;
}
private void setIsPaddingPercent(YogaEdge edge, boolean isPaddingPercent) {
if (mIsPaddingPercent == null && isPaddingPercent) {
mIsPaddingPercent = new boolean[YogaEdge.ALL.intValue() + 1];
}
if (mIsPaddingPercent != null) {
mIsPaddingPercent[edge.intValue()] = isPaddingPercent;
}
}
private <T extends Drawable> void setPaddingFromBackground(Drawable drawable) {
if (drawable != null) {
final Rect backgroundPadding = new Rect();
if (getDrawablePadding(drawable, backgroundPadding)) {
paddingPx(LEFT, backgroundPadding.left);
paddingPx(TOP, backgroundPadding.top);
paddingPx(RIGHT, backgroundPadding.right);
paddingPx(BOTTOM, backgroundPadding.bottom);
}
}
}
private boolean shouldApplyTouchExpansion() {
return mTouchExpansion != null && mNodeInfo != null && mNodeInfo.hasTouchEventHandlers();
}
/** Crash if the given node has context specific style set. */
@Override
public void assertContextSpecificStyleNotSet() {
List<CharSequence> errorTypes = null;
if ((mPrivateFlags & PFLAG_ALIGN_SELF_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "alignSelf");
}
if ((mPrivateFlags & PFLAG_POSITION_TYPE_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "positionType");
}
if ((mPrivateFlags & PFLAG_FLEX_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "flex");
}
if ((mPrivateFlags & PFLAG_FLEX_GROW_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "flexGrow");
}
if ((mPrivateFlags & PFLAG_MARGIN_IS_SET) != 0L) {
errorTypes = addOrCreateList(errorTypes, "margin");
}
if (errorTypes != null) {
final CharSequence errorStr = TextUtils.join(", ", errorTypes);
final ComponentsLogger logger = getContext().getLogger();
if (logger != null) {
logger.emitMessage(
WARNING,
"You should not set "
+ errorStr
+ " to a root layout in "
+ getRootComponent().getClass().getSimpleName());
}
}
}
static YogaNode createYogaNode(ComponentContext componentContext) {
return componentContext.mYogaNodeFactory != null
? componentContext.mYogaNodeFactory.create()
: NodeConfig.createYogaNode();
}
private @Nullable static <T> EventHandler<T> addVisibilityHandler(
@Nullable EventHandler<T> currentHandler, @Nullable EventHandler<T> newHandler) {
if (currentHandler == null) {
return newHandler;
}
if (newHandler == null) {
return currentHandler;
}
return new DelegatingEventHandler<>(currentHandler, newHandler);
}
/**
* This is a wrapper on top of built in {@link Drawable#getPadding(Rect)} which overrides default
* return value. The reason why we need this - is because on pre-L devices LayerDrawable always
* returns "true" even if drawable doesn't have padding (see https://goo.gl/gExcMQ). Since we
* heavily rely on correctness of this information, we need to check padding manually
*/
private static boolean getDrawablePadding(Drawable drawable, Rect outRect) {
drawable.getPadding(outRect);
return outRect.bottom != 0 || outRect.top != 0 || outRect.left != 0 || outRect.right != 0;
}
}
| rearrange some code and remove nit.
Summary: Move private method to the bottom and move interface implementation together.
Reviewed By: astreet
Differential Revision: D14870384
fbshipit-source-id: e6b41161800be523dd2ac14c5149f7ba83e86d09
| litho-core/src/main/java/com/facebook/litho/DefaultInternalNode.java | rearrange some code and remove nit. | <ide><path>itho-core/src/main/java/com/facebook/litho/DefaultInternalNode.java
<ide> return mNestedTreeProps != null && mNestedTreeProps.mIsNestedTreeHolder;
<ide> }
<ide>
<del> private boolean isPaddingPercent(YogaEdge edge) {
<del> return mIsPaddingPercent != null && mIsPaddingPercent[edge.intValue()];
<del> }
<del>
<ide> @Override
<ide> public void isReferenceBaseline(boolean isReferenceBaseline) {
<ide> mYogaNode.setIsReferenceBaseline(isReferenceBaseline);
<ide> }
<ide> if ((mPrivateFlags & PFLAG_STATE_LIST_ANIMATOR_RES_SET) != 0L) {
<ide> target.stateListAnimatorRes(mStateListAnimatorRes);
<del> }
<del> }
<del>
<del> private void applyOverridesRecursive(@Nullable InternalNode node) {
<del> if (ComponentsConfiguration.isDebugModeEnabled && node != null) {
<del> DebugComponent.applyOverrides(mComponentContext, node);
<del>
<del> for (int i = 0, count = node.getChildCount(); i < count; i++) {
<del> applyOverridesRecursive(node.getChildAt(i));
<del> }
<del>
<del> if (node.hasNestedTree()) {
<del> applyOverridesRecursive(node.getNestedTree());
<del> }
<ide> }
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del> @Override
<del> public DefaultInternalNode deepClone() {
<del>
<del> // 1. Return the null layout.
<del> if (this == NULL_LAYOUT) {
<del> return this;
<del> }
<del>
<del> // 2. Clone this layout.
<del> final DefaultInternalNode copy = clone();
<del>
<del> // 3. Clone the YogaNode of this layout and set it on the cloned layout.
<del> YogaNode node = mYogaNode.cloneWithoutChildren();
<del> copy.mYogaNode = node;
<del> node.setData(copy);
<del>
<del> // 4. Deep clone all children and add it to the cloned YogaNode
<del> final int count = getChildCount();
<del> for (int i = 0; i < count; i++) {
<del> copy.addChildAt(getChildAt(i).deepClone(), i);
<del> }
<del>
<del> copy.mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
<del> copy.mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
<del> copy.mResolvedX = YogaConstants.UNDEFINED;
<del> copy.mResolvedY = YogaConstants.UNDEFINED;
<del> copy.mResolvedWidth = YogaConstants.UNDEFINED;
<del> copy.mResolvedHeight = YogaConstants.UNDEFINED;
<del>
<del> return copy;
<del> }
<del>
<del> @Override
<del> public String getSimpleName() {
<del> return mComponents.isEmpty() ? "<null>" : mComponents.get(0).getSimpleName();
<del> }
<del>
<del> protected DefaultInternalNode clone() {
<del> try {
<del> return (DefaultInternalNode) super.clone();
<del> } catch (CloneNotSupportedException e) {
<del> e.printStackTrace();
<del> throw new RuntimeException(e);
<del> }
<del> }
<del>
<del> @ReturnsOwnership
<del> private Edges getNestedTreePadding() {
<del> NestedTreeProps props = getOrCreateNestedTreeProps();
<del> if (props.mNestedTreePadding == null) {
<del> props.mNestedTreePadding = new Edges();
<del> }
<del> return props.mNestedTreePadding;
<del> }
<del>
<del> private float resolveHorizontalEdges(Edges spacing, YogaEdge edge) {
<del> final boolean isRtl = (mYogaNode.getLayoutDirection() == YogaDirection.RTL);
<del>
<del> final YogaEdge resolvedEdge;
<del> switch (edge) {
<del> case LEFT:
<del> resolvedEdge = (isRtl ? YogaEdge.END : YogaEdge.START);
<del> break;
<del>
<del> case RIGHT:
<del> resolvedEdge = (isRtl ? YogaEdge.START : YogaEdge.END);
<del> break;
<del>
<del> default:
<del> throw new IllegalArgumentException("Not an horizontal padding edge: " + edge);
<del> }
<del>
<del> float result = spacing.getRaw(resolvedEdge);
<del> if (YogaConstants.isUndefined(result)) {
<del> result = spacing.get(edge);
<del> }
<del>
<del> return result;
<del> }
<del>
<del> private void setIsPaddingPercent(YogaEdge edge, boolean isPaddingPercent) {
<del> if (mIsPaddingPercent == null && isPaddingPercent) {
<del> mIsPaddingPercent = new boolean[YogaEdge.ALL.intValue() + 1];
<del> }
<del> if (mIsPaddingPercent != null) {
<del> mIsPaddingPercent[edge.intValue()] = isPaddingPercent;
<del> }
<del> }
<del>
<del> private <T extends Drawable> void setPaddingFromBackground(Drawable drawable) {
<del>
<del> if (drawable != null) {
<del> final Rect backgroundPadding = new Rect();
<del> if (getDrawablePadding(drawable, backgroundPadding)) {
<del> paddingPx(LEFT, backgroundPadding.left);
<del> paddingPx(TOP, backgroundPadding.top);
<del> paddingPx(RIGHT, backgroundPadding.right);
<del> paddingPx(BOTTOM, backgroundPadding.bottom);
<del> }
<del> }
<del> }
<del>
<del> private boolean shouldApplyTouchExpansion() {
<del> return mTouchExpansion != null && mNodeInfo != null && mNodeInfo.hasTouchEventHandlers();
<del> }
<del>
<ide> /** Crash if the given node has context specific style set. */
<ide> @Override
<ide> public void assertContextSpecificStyleNotSet() {
<ide> }
<ide> }
<ide>
<add> @Override
<add> public DefaultInternalNode deepClone() {
<add>
<add> // 1. Return the null layout.
<add> if (this == NULL_LAYOUT) {
<add> return this;
<add> }
<add>
<add> // 2. Clone this layout.
<add> final DefaultInternalNode copy = clone();
<add>
<add> // 3. Clone the YogaNode of this layout and set it on the cloned layout.
<add> YogaNode node = mYogaNode.cloneWithoutChildren();
<add> copy.mYogaNode = node;
<add> node.setData(copy);
<add>
<add> // 4. Deep clone all children and add it to the cloned YogaNode
<add> final int count = getChildCount();
<add> for (int i = 0; i < count; i++) {
<add> copy.addChildAt(getChildAt(i).deepClone(), i);
<add> }
<add>
<add> copy.resetResolvedLayoutProperties();
<add>
<add> return copy;
<add> }
<add>
<add> @Override
<add> public String getSimpleName() {
<add> return mComponents.isEmpty() ? "<null>" : mComponents.get(0).getSimpleName();
<add> }
<add>
<add> protected DefaultInternalNode clone() {
<add> try {
<add> return (DefaultInternalNode) super.clone();
<add> } catch (CloneNotSupportedException e) {
<add> e.printStackTrace();
<add> throw new RuntimeException(e);
<add> }
<add> }
<add>
<add> private boolean isPaddingPercent(YogaEdge edge) {
<add> return mIsPaddingPercent != null && mIsPaddingPercent[edge.intValue()];
<add> }
<add>
<add> private void applyOverridesRecursive(@Nullable InternalNode node) {
<add> if (ComponentsConfiguration.isDebugModeEnabled && node != null) {
<add> DebugComponent.applyOverrides(mComponentContext, node);
<add>
<add> for (int i = 0, count = node.getChildCount(); i < count; i++) {
<add> applyOverridesRecursive(node.getChildAt(i));
<add> }
<add>
<add> if (node.hasNestedTree()) {
<add> applyOverridesRecursive(node.getNestedTree());
<add> }
<add> }
<add> }
<add>
<add> @ReturnsOwnership
<add> private Edges getNestedTreePadding() {
<add> NestedTreeProps props = getOrCreateNestedTreeProps();
<add> if (props.mNestedTreePadding == null) {
<add> props.mNestedTreePadding = new Edges();
<add> }
<add> return props.mNestedTreePadding;
<add> }
<add>
<add> private float resolveHorizontalEdges(Edges spacing, YogaEdge edge) {
<add> final boolean isRtl = (mYogaNode.getLayoutDirection() == YogaDirection.RTL);
<add>
<add> final YogaEdge resolvedEdge;
<add> switch (edge) {
<add> case LEFT:
<add> resolvedEdge = (isRtl ? YogaEdge.END : YogaEdge.START);
<add> break;
<add>
<add> case RIGHT:
<add> resolvedEdge = (isRtl ? YogaEdge.START : YogaEdge.END);
<add> break;
<add>
<add> default:
<add> throw new IllegalArgumentException("Not an horizontal padding edge: " + edge);
<add> }
<add>
<add> float result = spacing.getRaw(resolvedEdge);
<add> if (YogaConstants.isUndefined(result)) {
<add> result = spacing.get(edge);
<add> }
<add>
<add> return result;
<add> }
<add>
<add> private void setIsPaddingPercent(YogaEdge edge, boolean isPaddingPercent) {
<add> if (mIsPaddingPercent == null && isPaddingPercent) {
<add> mIsPaddingPercent = new boolean[YogaEdge.ALL.intValue() + 1];
<add> }
<add> if (mIsPaddingPercent != null) {
<add> mIsPaddingPercent[edge.intValue()] = isPaddingPercent;
<add> }
<add> }
<add>
<add> private void setPaddingFromBackground(Drawable drawable) {
<add>
<add> if (drawable != null) {
<add> final Rect backgroundPadding = new Rect();
<add> if (getDrawablePadding(drawable, backgroundPadding)) {
<add> paddingPx(LEFT, backgroundPadding.left);
<add> paddingPx(TOP, backgroundPadding.top);
<add> paddingPx(RIGHT, backgroundPadding.right);
<add> paddingPx(BOTTOM, backgroundPadding.bottom);
<add> }
<add> }
<add> }
<add>
<add> private boolean shouldApplyTouchExpansion() {
<add> return mTouchExpansion != null && mNodeInfo != null && mNodeInfo.hasTouchEventHandlers();
<add> }
<add>
<ide> static YogaNode createYogaNode(ComponentContext componentContext) {
<ide> return componentContext.mYogaNodeFactory != null
<ide> ? componentContext.mYogaNodeFactory.create() |
|
Java | unlicense | 0d33941a9d9283cd3db975bb0be920fad987e6bb | 0 | Reddy360/CustomPotions | package pe.nn.connor.custompotions;
import java.util.HashMap;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffectType;
public class CustomPotions extends JavaPlugin{
private HashMap<String, PotionEffectType> potionNames;
@Override
public void onEnable() {
//Create Potion name list
potionNames = new HashMap<String, PotionEffectType>();
//Create automated system for adding new potions
//This allows any new potion effect to be used prior to an update
for(PotionEffectType type : PotionEffectType.values()){
potionNames.put(type.getName(), type);
}
}
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if(command.getName().equalsIgnoreCase("custompotions")){
if(args.length == 1){
if(args[0].equalsIgnoreCase("help")){
sender.sendMessage("Custom Potions help");
sender.sendMessage("This will be changed in the release build");
sender.sendMessage("");
sender.sendMessage(label + " give potion:strength:duration (-splash)");
return true;
}
}
}
return false;
}
}
| pe/nn/connor/custompotions/CustomPotions.java | package pe.nn.connor.custompotions;
import java.util.HashMap;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffectType;
public class CustomPotions extends JavaPlugin{
private HashMap<String, PotionEffectType> potionNames;
@Override
public void onEnable() {
//Create Potion name list
potionNames = new HashMap<String, PotionEffectType>();
//Create automated system for adding new potions
//This allows any new potion effect to be used prior to an update
for(PotionEffectType type : PotionEffectType.values()){
potionNames.put(type.getName(), type);
}
}
}
| Added custompotions command (only with help subcommand)
| pe/nn/connor/custompotions/CustomPotions.java | Added custompotions command (only with help subcommand) | <ide><path>e/nn/connor/custompotions/CustomPotions.java
<ide>
<ide> import java.util.HashMap;
<ide>
<add>import org.bukkit.command.Command;
<add>import org.bukkit.command.CommandSender;
<ide> import org.bukkit.plugin.java.JavaPlugin;
<ide> import org.bukkit.potion.PotionEffectType;
<ide>
<ide> public class CustomPotions extends JavaPlugin{
<ide> private HashMap<String, PotionEffectType> potionNames;
<add>
<ide> @Override
<ide> public void onEnable() {
<ide> //Create Potion name list
<ide> potionNames.put(type.getName(), type);
<ide> }
<ide> }
<add>
<add> @Override
<add> public boolean onCommand(CommandSender sender, Command command,
<add> String label, String[] args) {
<add> if(command.getName().equalsIgnoreCase("custompotions")){
<add> if(args.length == 1){
<add> if(args[0].equalsIgnoreCase("help")){
<add> sender.sendMessage("Custom Potions help");
<add> sender.sendMessage("This will be changed in the release build");
<add> sender.sendMessage("");
<add> sender.sendMessage(label + " give potion:strength:duration (-splash)");
<add> return true;
<add> }
<add> }
<add> }
<add> return false;
<add> }
<ide> } |
|
Java | apache-2.0 | c834fe2c75ffb648cd2d457ba1e2d304807e28f8 | 0 | evanx/vellumcore | /*
* Source https://github.com/evanx by @evanxsummers
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file to
you under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the
License. You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package vellum.exception;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import vellum.util.Strings;
import vellum.util.Args;
/**
* Utility methods related to exceptions.
*
* @author evan.summers
*/
public class Exceptions {
public static Throwable getThrowable(Object[] args) {
if (args.length > 0 && args[0] instanceof Throwable) {
return (Throwable) args[0];
}
return null;
}
public static String getMessage(Object[] args) {
return Args.format(args);
}
public static String getMessage(Throwable e) {
if (e.getMessage() == null) {
return e.getClass().getSimpleName();
} else {
return String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage());
}
}
public static RuntimeException newRuntimeException(Object... args) {
if (args.length == 1) {
Throwable e = getThrowable(args);
if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
}
return new ArgsRuntimeException(args);
}
public static String printStackTrace(Throwable exception) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
try {
exception.printStackTrace(ps);
return baos.toString(Strings.ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.newRuntimeException(e);
}
}
public static void warn(Exception e) {
e.printStackTrace(System.err);
}
}
| src/vellum/exception/Exceptions.java | /*
* Source https://github.com/evanx by @evanxsummers
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file to
you under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the
License. You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package vellum.exception;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import vellum.util.Strings;
import vellum.util.Args;
/**
* Utility methods related to exceptions.
*
* @author evan.summers
*/
public class Exceptions {
public static Throwable getThrowable(Object[] args) {
if (args.length > 0 && args[0] instanceof Throwable) {
return (Throwable) args[0];
}
return null;
}
public static String getMessage(Object[] args) {
return Args.format(args);
}
public static String getMessage(Throwable e) {
return String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage());
}
public static RuntimeException newRuntimeException(Object ... args) {
if (args.length == 1) {
Throwable e = getThrowable(args);
if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
}
return new ArgsRuntimeException(args);
}
public static String printStackTrace(Throwable exception) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
try {
exception.printStackTrace(ps);
return baos.toString(Strings.ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.newRuntimeException(e);
}
}
public static void warn(Exception e) {
e.printStackTrace(System.err);
}
}
| Exceptions message formatting if null | src/vellum/exception/Exceptions.java | Exceptions message formatting if null | <ide><path>rc/vellum/exception/Exceptions.java
<ide> /*
<ide> * Source https://github.com/evanx by @evanxsummers
<ide>
<del> Licensed to the Apache Software Foundation (ASF) under one
<del> or more contributor license agreements. See the NOTICE file
<del> distributed with this work for additional information
<del> regarding copyright ownership. The ASF licenses this file to
<del> you under the Apache License, Version 2.0 (the "License").
<del> You may not use this file except in compliance with the
<del> License. You may obtain a copy of the License at:
<add> Licensed to the Apache Software Foundation (ASF) under one
<add> or more contributor license agreements. See the NOTICE file
<add> distributed with this work for additional information
<add> regarding copyright ownership. The ASF licenses this file to
<add> you under the Apache License, Version 2.0 (the "License").
<add> You may not use this file except in compliance with the
<add> License. You may obtain a copy of the License at:
<ide>
<del> http://www.apache.org/licenses/LICENSE-2.0
<add> http://www.apache.org/licenses/LICENSE-2.0
<ide>
<del> Unless required by applicable law or agreed to in writing,
<del> software distributed under the License is distributed on an
<del> "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<del> KIND, either express or implied. See the License for the
<del> specific language governing permissions and limitations
<del> under the License.
<add> Unless required by applicable law or agreed to in writing,
<add> software distributed under the License is distributed on an
<add> "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add> KIND, either express or implied. See the License for the
<add> specific language governing permissions and limitations
<add> under the License.
<ide> */
<ide> package vellum.exception;
<ide>
<ide> */
<ide> public class Exceptions {
<ide>
<del> public static Throwable getThrowable(Object[] args) {
<del> if (args.length > 0 && args[0] instanceof Throwable) {
<del> return (Throwable) args[0];
<del> }
<del> return null;
<del> }
<add> public static Throwable getThrowable(Object[] args) {
<add> if (args.length > 0 && args[0] instanceof Throwable) {
<add> return (Throwable) args[0];
<add> }
<add> return null;
<add> }
<ide>
<del> public static String getMessage(Object[] args) {
<del> return Args.format(args);
<del> }
<add> public static String getMessage(Object[] args) {
<add> return Args.format(args);
<add> }
<ide>
<del> public static String getMessage(Throwable e) {
<del> return String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage());
<del> }
<del>
<del> public static RuntimeException newRuntimeException(Object ... args) {
<del> if (args.length == 1) {
<del> Throwable e = getThrowable(args);
<del> if (e instanceof RuntimeException) {
<del> return (RuntimeException) e;
<del> }
<del> }
<del> return new ArgsRuntimeException(args);
<del> }
<add> public static String getMessage(Throwable e) {
<add> if (e.getMessage() == null) {
<add> return e.getClass().getSimpleName();
<add> } else {
<add> return String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage());
<add> }
<add> }
<ide>
<del> public static String printStackTrace(Throwable exception) {
<del> ByteArrayOutputStream baos = new ByteArrayOutputStream();
<del> PrintStream ps = new PrintStream(baos);
<del> try {
<del> exception.printStackTrace(ps);
<del> return baos.toString(Strings.ENCODING);
<del> } catch (UnsupportedEncodingException e) {
<del> throw Exceptions.newRuntimeException(e);
<del> }
<del> }
<del>
<del> public static void warn(Exception e) {
<del> e.printStackTrace(System.err);
<del> }
<del>
<add> public static RuntimeException newRuntimeException(Object... args) {
<add> if (args.length == 1) {
<add> Throwable e = getThrowable(args);
<add> if (e instanceof RuntimeException) {
<add> return (RuntimeException) e;
<add> }
<add> }
<add> return new ArgsRuntimeException(args);
<add> }
<add>
<add> public static String printStackTrace(Throwable exception) {
<add> ByteArrayOutputStream baos = new ByteArrayOutputStream();
<add> PrintStream ps = new PrintStream(baos);
<add> try {
<add> exception.printStackTrace(ps);
<add> return baos.toString(Strings.ENCODING);
<add> } catch (UnsupportedEncodingException e) {
<add> throw Exceptions.newRuntimeException(e);
<add> }
<add> }
<add>
<add> public static void warn(Exception e) {
<add> e.printStackTrace(System.err);
<add> }
<add>
<ide> } |
|
Java | bsd-3-clause | 60d233821021c30f765cffc86c0fe23b2e49d106 | 0 | febit/wit,zqq90/webit-script | // Copyright (c) 2013-2016, febit.org. All Rights Reserved.
package org.febit.wit.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.febit.wit.exceptions.ScriptRuntimeException;
import org.febit.wit.lang.InternalVoid;
/**
*
* @author zqq90
*/
public class ALU {
private static final int OBJECT = (1 << 29) - 1;
private static final int STRING = (1 << 10) - 1;
private static final int CHAR = (1 << 9) - 1;
private static final int BIG_DECIMAL = (1 << 8) - 1;
private static final int BIG_INTEGER = (1 << 7) - 1;
private static final int DOUBLE = (1 << 6) - 1;
private static final int FLOAT = (1 << 5) - 1;
private static final int LONG = (1 << 4) - 1;
private static final int INTEGER = (1 << 3) - 1;
private static final int SHORT = (1 << 2) - 1;
private static final int BYTE = (1 << 1) - 1;
private ALU() {
}
private static int getTypeMark(final Object o1) {
final Class cls = o1.getClass();
if (cls == String.class) {
return STRING;
} else if (cls == Integer.class) {
return INTEGER;
} else if (cls == Long.class) {
return LONG;
} else if (cls == Short.class) {
return SHORT;
} else if (cls == Double.class) {
return DOUBLE;
} else if (cls == Float.class) {
return FLOAT;
} else if (cls == Character.class) {
return CHAR;
} else if (cls == Byte.class) {
return BYTE;
} else if (o1 instanceof Number) {
if (o1 instanceof BigInteger) {
return BIG_INTEGER;
} else {
//Note: otherwise, treat as BigDecimal
return BIG_DECIMAL;
}
}
return OBJECT;
}
private static int getTypeMark(final Object o1, final Object o2) {
requireNonNull(o1, o2);
return getTypeMark(o1) | getTypeMark(o2);
}
// +1
public static Object plusOne(final Object o1) {
requireNonNull(o1);
if (o1 instanceof Number) {
final Number num = (Number) o1;
switch (getTypeMark(num)) {
case INTEGER:
case SHORT:
case BYTE:
return num.intValue() + 1;
case LONG:
return num.longValue() + 1L;
case DOUBLE:
return num.doubleValue() + 1D;
case FLOAT:
return num.floatValue() + 1F;
case BIG_INTEGER:
return toBigInteger(num).add(BigInteger.ONE);
case BIG_DECIMAL:
return toBigDecimal(num).add(BigDecimal.ONE);
default:
}
} else if (o1 instanceof Character) {
return ((Character) o1) + 1;
}
throw unsupportedTypeException(o1);
}
// -1
public static Object minusOne(final Object o1) {
requireNonNull(o1);
if (o1 instanceof Number) {
final Number num = (Number) o1;
switch (getTypeMark(num)) {
case INTEGER:
case SHORT:
case BYTE:
return num.intValue() - 1;
case LONG:
return num.longValue() - 1L;
case DOUBLE:
return num.doubleValue() - 1D;
case FLOAT:
return num.floatValue() - 1F;
case BIG_INTEGER:
return toBigInteger(num).subtract(BigInteger.ONE);
case BIG_DECIMAL:
return toBigDecimal(num).subtract(BigDecimal.ONE);
default:
}
} else if (o1 instanceof Character) {
return ((Character) o1) - 1;
}
throw unsupportedTypeException(o1);
}
//+
public static Object plus(final Object o1, final Object o2) {
if (o1 == null || o2 == null) {
return o1 != null ? o1 : o2;
}
switch (getTypeMark(o1, o2)) {
case STRING:
case OBJECT:
return o1.toString().concat(o2.toString());
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() + ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() + ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() + ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() + ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).add(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).add(toBigDecimal(o2));
case CHAR:
return plus(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
//-
public static Object minus(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() - ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() - ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() - ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() - ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).subtract(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).subtract(toBigDecimal(o2));
case CHAR:
return minus(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// negative
public static Object negative(final Object o1) {
requireNonNull(o1);
switch (getTypeMark(o1)) {
case INTEGER:
return -((Integer) o1);
case LONG:
return -((Long) o1);
case DOUBLE:
return -((Double) o1);
case FLOAT:
return -((Float) o1);
case SHORT:
return -((Short) o1);
case BIG_INTEGER:
return ((BigInteger) o1).negate();
case BIG_DECIMAL:
return ((BigDecimal) o1).negate();
case CHAR:
return -((Character) o1);
default:
}
throw unsupportedTypeException(o1);
}
//*
public static Object mult(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() * ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() * ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() * ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() * ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).multiply(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).multiply(toBigDecimal(o2));
case CHAR:
return mult(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// /
public static Object div(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() / ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() / ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() / ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() / ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).divide(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).divide(toBigDecimal(o2));
case CHAR:
return div(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// %
public static Object mod(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() % ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() % ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() % ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() % ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).remainder(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).remainder(toBigDecimal(o2));
case CHAR:
return mod(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// &&
public static Object and(final Object o1, final Object o2) {
return isTrue(o1) ? o2 : o1;
}
// ||
public static Object or(final Object o1, final Object o2) {
return isTrue(o1) ? o1 : o2;
}
// !
public static boolean not(final Object o1) {
return !isTrue(o1);
}
// ==
public static boolean isEqual(final Object o1, final Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
switch (getTypeMark(o1, o2)) {
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() == ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() == ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) == 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) == 0;
case CHAR:
return isEqual(charToInt(o1), charToInt(o2));
default:
}
return false;
}
// >
public static boolean greater(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() > ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() > ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) > 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) > 0;
case CHAR:
return greater(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// >=
public static boolean greaterEqual(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return greaterEqual(charToInt(o1), charToInt(o2));
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() >= ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() >= ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) >= 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) >= 0;
default:
}
throw unsupportedTypeException(o1, o2);
}
// <
public static boolean less(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return less(charToInt(o1), charToInt(o2));
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() < ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() < ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) < 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) < 0;
default:
}
throw unsupportedTypeException(o1, o2);
}
// <=
public static boolean lessEqual(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return lessEqual(charToInt(o1), charToInt(o2));
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() <= ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() <= ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) <= 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) <= 0;
default:
}
throw unsupportedTypeException(o1, o2);
}
// &
public static Object bitAnd(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return bitAnd(charToInt(o1), charToInt(o2));
case BYTE:
return ((Number) o1).byteValue() & ((Number) o2).byteValue();
case SHORT:
return ((Number) o1).shortValue() & ((Number) o2).shortValue();
case INTEGER:
return ((Number) o1).intValue() & ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() & ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).and(toBigInteger(o2));
}
//Note: else unsupported
default:
}
throw unsupportedTypeException(o1, o2);
}
// |
public static Object bitOr(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return bitOr(charToInt(o1), charToInt(o2));
case BYTE:
return ((Number) o1).byteValue() | ((Number) o2).byteValue();
case SHORT:
return ((Number) o1).shortValue() | ((Number) o2).shortValue();
case INTEGER:
return ((Number) o1).intValue() | ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() | ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).or(toBigInteger(o2));
}
//Note: else unsupported
default:
}
throw unsupportedTypeException(o1, o2);
}
// ^ XOR
public static Object bitXor(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return bitXor(charToInt(o1), charToInt(o2));
case BYTE:
return ((Number) o1).byteValue() ^ ((Number) o2).byteValue();
case SHORT:
return ((Number) o1).shortValue() ^ ((Number) o2).shortValue();
case INTEGER:
return ((Number) o1).intValue() ^ ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() ^ ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).xor(toBigInteger(o2));
}
//Note: else unsupported
default:
}
throw unsupportedTypeException(o1, o2);
}
// ~
public static Object bitNot(final Object o1) {
requireNonNull(o1);
switch (getTypeMark(o1)) {
case CHAR:
return ~((Character) o1);
case BYTE:
return ~((Byte) o1);
case SHORT:
return ~((Short) o1);
case INTEGER:
return ~((Integer) o1);
case LONG:
return ~((Long) o1);
case BIG_INTEGER:
return ((BigInteger) o1).not();
default:
}
throw unsupportedTypeException(o1);
}
// <<
public static Object lshift(final Object o1, final Object o2) {
requireNonNull(o1, o2);
if (o2 instanceof Number) {
int right = ((Number) o2).intValue();
switch (getTypeMark(o1)) {
case CHAR:
return ((Character) o1) << right;
case BYTE:
return ((Byte) o1) << right;
case SHORT:
return ((Short) o1) << right;
case INTEGER:
return ((Integer) o1) << right;
case LONG:
return ((Long) o1) << right;
case BIG_INTEGER:
return ((BigInteger) o1).shiftLeft(right);
default:
}
}
throw unsupportedTypeException(o1, o2);
}
// >>
public static Object rshift(final Object o1, final Object o2) {
requireNonNull(o1, o2);
if (o2 instanceof Number) {
int right = ((Number) o2).intValue();
switch (getTypeMark(o1)) {
case CHAR:
return ((Character) o1) >> right;
case BYTE:
return ((Byte) o1) >> right;
case SHORT:
return ((Short) o1) >> right;
case INTEGER:
return ((Integer) o1) >> right;
case LONG:
return ((Long) o1) >> right;
case BIG_INTEGER:
return ((BigInteger) o1).shiftRight(right);
default:
}
}
throw unsupportedTypeException(o1, o2);
}
// >>>
public static Object urshift(final Object o1, final Object o2) {
requireNonNull(o1, o2);
if (o2 instanceof Number) {
int right = ((Number) o2).intValue();
switch (getTypeMark(o1)) {
case CHAR:
return ((Character) o1) >>> right;
case BYTE:
return ((Byte) o1) >>> right;
case SHORT:
return ((Short) o1) >>> right;
case INTEGER:
return ((Integer) o1) >>> right;
case LONG:
return ((Long) o1) >>> right;
default:
}
}
throw unsupportedTypeException(o1, o2);
}
private static Object charToInt(final Object o1) {
if (o1 instanceof Character) {
return Integer.valueOf((Character) o1);
}
return o1;
}
private static boolean isSafeToLong(Class type) {
return type == Integer.class
|| type == Long.class
|| type == Short.class
|| type == Byte.class;
}
private static BigInteger toBigInteger(final Object o1) {
if (o1 instanceof BigInteger) {
return (BigInteger) o1;
}
if (isSafeToLong(o1.getClass())) {
return BigInteger.valueOf(((Number) o1).longValue());
}
if (o1 instanceof BigDecimal) {
return ((BigDecimal) o1).toBigInteger();
}
return new BigDecimal(o1.toString()).toBigInteger();
}
private static BigDecimal toBigDecimal(final Object o1) {
if (o1 == null) {
return BigDecimal.ZERO;
}
if (o1 instanceof BigDecimal) {
return (BigDecimal) o1;
}
if (isSafeToLong(o1.getClass())) {
return BigDecimal.valueOf(((Number) o1).longValue());
}
if (o1 instanceof BigInteger) {
return new BigDecimal((BigInteger) o1);
}
// floating decimals
return new BigDecimal(o1.toString());
}
public static boolean isTrue(final Object o) {
if (o == null) {
return false;
}
if (o.getClass() == Boolean.class) {
return (Boolean) o;
}
if (o == InternalVoid.VOID) {
return false;
}
//if Collection empty
return CollectionUtil.notEmpty(o, true);
}
private static boolean notDoubleOrFloat(Object o1) {
Class type = o1.getClass();
return type != Float.class
&& type != Double.class;
}
private static boolean notDoubleOrFloat(Object o1, Object o2) {
return notDoubleOrFloat(o1) && notDoubleOrFloat(o2);
}
private static ScriptRuntimeException unsupportedTypeException(final Object o1, final Object o2) {
return new ScriptRuntimeException(StringUtil.format("Unsupported type: left[{}], right[{}]", o1.getClass(), o2.getClass()));
}
private static ScriptRuntimeException unsupportedTypeException(final Object o1) {
return new ScriptRuntimeException(StringUtil.format("Unsupported type: [{}]", o1.getClass()));
}
private static void requireNonNull(final Object obj) {
if (obj == null) {
throw new ScriptRuntimeException("value is null");
}
}
private static void requireNonNull(final Object o1, final Object o2) {
if (o1 == null || o2 == null) {
throw new ScriptRuntimeException(
o1 != null
? "right value is null"
: o2 != null
? "left value is null"
: "left & right values are null");
}
}
}
| wit-core/src/main/java/org/febit/wit/util/ALU.java | // Copyright (c) 2013-2016, febit.org. All Rights Reserved.
package org.febit.wit.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.febit.wit.exceptions.ScriptRuntimeException;
import org.febit.wit.lang.InternalVoid;
/**
*
* @author zqq90
*/
public class ALU {
private static final int OBJECT = (1 << 29) - 1;
private static final int STRING = (1 << 10) - 1;
private static final int CHAR = (1 << 9) - 1;
private static final int BIG_DECIMAL = (1 << 8) - 1;
private static final int BIG_INTEGER = (1 << 7) - 1;
private static final int DOUBLE = (1 << 6) - 1;
private static final int FLOAT = (1 << 5) - 1;
private static final int LONG = (1 << 4) - 1;
private static final int INTEGER = (1 << 3) - 1;
private static final int SHORT = (1 << 2) - 1;
private static final int BYTE = (1 << 1) - 1;
private ALU() {
}
private static int getTypeMark(final Object o1) {
final Class cls = o1.getClass();
if (cls == String.class) {
return STRING;
} else if (cls == Integer.class) {
return INTEGER;
} else if (cls == Long.class) {
return LONG;
} else if (cls == Short.class) {
return SHORT;
} else if (cls == Double.class) {
return DOUBLE;
} else if (cls == Float.class) {
return FLOAT;
} else if (cls == Character.class) {
return CHAR;
} else if (cls == Byte.class) {
return BYTE;
} else if (o1 instanceof Number) {
if (o1 instanceof BigInteger) {
return BIG_INTEGER;
} else {
//Note: otherwise, treat as BigDecimal
return BIG_DECIMAL;
}
}
return OBJECT;
}
private static int getTypeMark(final Object o1, final Object o2) {
requireNonNull(o1, o2);
return getTypeMark(o1) | getTypeMark(o2);
}
// +1
public static Object plusOne(final Object o1) {
requireNonNull(o1);
if (o1 instanceof Number) {
final Number num = (Number) o1;
switch (getTypeMark(num)) {
case INTEGER:
case SHORT:
case BYTE:
return num.intValue() + 1;
case LONG:
return num.longValue() + 1L;
case DOUBLE:
return num.doubleValue() + 1D;
case FLOAT:
return num.floatValue() + 1F;
case BIG_INTEGER:
return toBigInteger(num).add(BigInteger.ONE);
case BIG_DECIMAL:
return toBigDecimal(num).add(BigDecimal.ONE);
default:
}
} else if (o1 instanceof Character) {
return ((Character) o1) + 1;
}
throw unsupportedTypeException(o1);
}
// -1
public static Object minusOne(final Object o1) {
requireNonNull(o1);
if (o1 instanceof Number) {
final Number num = (Number) o1;
switch (getTypeMark(num)) {
case INTEGER:
case SHORT:
case BYTE:
return num.intValue() - 1;
case LONG:
return num.longValue() - 1L;
case DOUBLE:
return num.doubleValue() - 1D;
case FLOAT:
return num.floatValue() - 1F;
case BIG_INTEGER:
return toBigInteger(num).subtract(BigInteger.ONE);
case BIG_DECIMAL:
return toBigDecimal(num).subtract(BigDecimal.ONE);
default:
}
} else if (o1 instanceof Character) {
return ((Character) o1) - 1;
}
throw unsupportedTypeException(o1);
}
//+
public static Object plus(final Object o1, final Object o2) {
if (o1 == null || o2 == null) {
return o1 != null ? o1 : o2;
}
switch (getTypeMark(o1, o2)) {
case STRING:
case OBJECT:
return o1.toString().concat(o2.toString());
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() + ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() + ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() + ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() + ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).add(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).add(toBigDecimal(o2));
case CHAR:
return plus(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
//-
public static Object minus(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() - ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() - ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() - ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() - ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).subtract(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).subtract(toBigDecimal(o2));
case CHAR:
return minus(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// negative
public static Object negative(final Object o1) {
requireNonNull(o1);
switch (getTypeMark(o1)) {
case INTEGER:
return -((Integer) o1);
case LONG:
return -((Long) o1);
case DOUBLE:
return -((Double) o1);
case FLOAT:
return -((Float) o1);
case SHORT:
return -((Short) o1);
case BIG_INTEGER:
return ((BigInteger) o1).negate();
case BIG_DECIMAL:
return ((BigDecimal) o1).negate();
case CHAR:
return -((Character) o1);
default:
}
throw unsupportedTypeException(o1);
}
//*
public static Object mult(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() * ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() * ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() * ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() * ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).multiply(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).multiply(toBigDecimal(o2));
case CHAR:
return mult(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// /
public static Object div(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() / ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() / ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() / ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() / ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).divide(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).divide(toBigDecimal(o2));
case CHAR:
return div(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// %
public static Object mod(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case INTEGER:
case SHORT:
case BYTE:
return ((Number) o1).intValue() % ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() % ((Number) o2).longValue();
case DOUBLE:
return ((Number) o1).doubleValue() % ((Number) o2).doubleValue();
case FLOAT:
return ((Number) o1).floatValue() % ((Number) o2).floatValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).remainder(toBigInteger(o2));
}
//Note: else upgrade to BigDecimal
case BIG_DECIMAL:
return toBigDecimal(o1).remainder(toBigDecimal(o2));
case CHAR:
return mod(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// &&
public static Object and(final Object o1, final Object o2) {
return isTrue(o1) ? o2 : o1;
}
// ||
public static Object or(final Object o1, final Object o2) {
return isTrue(o1) ? o1 : o2;
}
// !
public static boolean not(final Object o1) {
return !isTrue(o1);
}
// ==
public static boolean isEqual(final Object o1, final Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
switch (getTypeMark(o1, o2)) {
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() == ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() == ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) == 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) == 0;
case CHAR:
return isEqual(charToInt(o1), charToInt(o2));
default:
}
return false;
}
// >
public static boolean greater(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() > ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() > ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) > 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) > 0;
case CHAR:
return greater(charToInt(o1), charToInt(o2));
default:
}
throw unsupportedTypeException(o1, o2);
}
// >=
public static boolean greaterEqual(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return greaterEqual(charToInt(o1), charToInt(o2));
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() >= ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() >= ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) >= 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) >= 0;
default:
}
throw unsupportedTypeException(o1, o2);
}
// <
public static boolean less(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return less(charToInt(o1), charToInt(o2));
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() < ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() < ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) < 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) < 0;
default:
}
throw unsupportedTypeException(o1, o2);
}
// <=
public static boolean lessEqual(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return lessEqual(charToInt(o1), charToInt(o2));
case BYTE:
case SHORT:
case INTEGER:
return ((Number) o1).intValue() <= ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() <= ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).compareTo(toBigInteger(o2)) <= 0;
}
//Note: else upgrade to BigDecimal
case DOUBLE:
case FLOAT:
//Note: Floating point numbers should not be tested for equality.
case BIG_DECIMAL:
return toBigDecimal(o1).compareTo(toBigDecimal(o2)) <= 0;
default:
}
throw unsupportedTypeException(o1, o2);
}
// &
public static Object bitAnd(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return bitAnd(charToInt(o1), charToInt(o2));
case BYTE:
return ((Number) o1).byteValue() & ((Number) o2).byteValue();
case SHORT:
return ((Number) o1).shortValue() & ((Number) o2).shortValue();
case INTEGER:
return ((Number) o1).intValue() & ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() & ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).and(toBigInteger(o2));
}
//Note: else unsupported
default:
}
throw unsupportedTypeException(o1, o2);
}
// |
public static Object bitOr(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return bitOr(charToInt(o1), charToInt(o2));
case BYTE:
return ((Number) o1).byteValue() | ((Number) o2).byteValue();
case SHORT:
return ((Number) o1).shortValue() | ((Number) o2).shortValue();
case INTEGER:
return ((Number) o1).intValue() | ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() | ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).or(toBigInteger(o2));
}
//Note: else unsupported
default:
}
throw unsupportedTypeException(o1, o2);
}
// ^ XOR
public static Object bitXor(final Object o1, final Object o2) {
switch (getTypeMark(o1, o2)) {
case CHAR:
return bitXor(charToInt(o1), charToInt(o2));
case BYTE:
return ((Number) o1).byteValue() ^ ((Number) o2).byteValue();
case SHORT:
return ((Number) o1).shortValue() ^ ((Number) o2).shortValue();
case INTEGER:
return ((Number) o1).intValue() ^ ((Number) o2).intValue();
case LONG:
return ((Number) o1).longValue() ^ ((Number) o2).longValue();
case BIG_INTEGER:
if (notDoubleOrFloat(o1, o2)) {
return toBigInteger(o1).xor(toBigInteger(o2));
}
//Note: else unsupported
default:
}
throw unsupportedTypeException(o1, o2);
}
// ~
public static Object bitNot(final Object o1) {
requireNonNull(o1);
switch (getTypeMark(o1)) {
case CHAR:
return ~((Character) o1);
case BYTE:
return ~((Byte) o1);
case SHORT:
return ~((Short) o1);
case INTEGER:
return ~((Integer) o1);
case LONG:
return ~((Long) o1);
case BIG_INTEGER:
return ((BigInteger) o1).not();
default:
}
throw unsupportedTypeException(o1);
}
// <<
public static Object lshift(final Object o1, final Object o2) {
requireNonNull(o1, o2);
if (o2 instanceof Number) {
int right = ((Number) o2).intValue();
switch (getTypeMark(o1)) {
case CHAR:
return ((Character) o1) << right;
case BYTE:
return ((Byte) o1) << right;
case SHORT:
return ((Short) o1) << right;
case INTEGER:
return ((Integer) o1) << right;
case LONG:
return ((Long) o1) << right;
case BIG_INTEGER:
return ((BigInteger) o1).shiftLeft(right);
default:
}
}
throw unsupportedTypeException(o1, o2);
}
// >>
public static Object rshift(final Object o1, final Object o2) {
requireNonNull(o1, o2);
if (o2 instanceof Number) {
int right = ((Number) o2).intValue();
switch (getTypeMark(o1)) {
case CHAR:
return ((Character) o1) >> right;
case BYTE:
return ((Byte) o1) >> right;
case SHORT:
return ((Short) o1) >> right;
case INTEGER:
return ((Integer) o1) >> right;
case LONG:
return ((Long) o1) >> right;
case BIG_INTEGER:
return ((BigInteger) o1).shiftRight(right);
default:
}
}
throw unsupportedTypeException(o1, o2);
}
// >>>
public static Object urshift(final Object o1, final Object o2) {
requireNonNull(o1, o2);
if (o2 instanceof Number) {
int right = ((Number) o2).intValue();
switch (getTypeMark(o1)) {
case CHAR:
return ((Character) o1) >>> right;
case BYTE:
return ((Byte) o1) >>> right;
case SHORT:
return ((Short) o1) >>> right;
case INTEGER:
return ((Integer) o1) >>> right;
case LONG:
return ((Long) o1) >>> right;
default:
}
}
throw unsupportedTypeException(o1, o2);
}
private static Object charToInt(final Object o1) {
if (o1 instanceof Character) {
return Integer.valueOf((Character) o1);
}
return o1;
}
private static boolean isSafeToLong(Class type) {
return type == Integer.class
|| type == Long.class
|| type == Short.class
|| type == Byte.class;
}
private static BigInteger toBigInteger(final Object o1) {
if (o1 instanceof BigInteger) {
return (BigInteger) o1;
}
if (isSafeToLong(o1.getClass())) {
return BigInteger.valueOf(((Number) o1).longValue());
}
if (o1 instanceof BigDecimal) {
return ((BigDecimal) o1).toBigInteger();
}
return new BigDecimal(o1.toString()).toBigInteger();
}
private static BigDecimal toBigDecimal(final Object o1) {
if (o1 == null) {
return BigDecimal.ZERO;
}
if (o1 instanceof BigDecimal) {
return (BigDecimal) o1;
}
if (isSafeToLong(o1.getClass())) {
return BigDecimal.valueOf(((Number) o1).longValue());
}
if (o1 instanceof BigInteger) {
return new BigDecimal((BigInteger) o1);
}
// floating decimals
return new BigDecimal(o1.toString());
}
public static boolean isTrue(final Object o) {
if (o == null) {
return false;
}
if (o.getClass() == Boolean.class) {
return (Boolean) o;
}
if (o == InternalVoid.VOID) {
return false;
}
//if Collection empty
return CollectionUtil.notEmpty(o, true);
}
private static boolean notDoubleOrFloat(Object o1) {
Class type = o1.getClass();
return type != Float.class
&& type != Double.class;
}
private static boolean notDoubleOrFloat(Object o1, Object o2) {
return notDoubleOrFloat(o1) && notDoubleOrFloat(o2);
}
private static ScriptRuntimeException unsupportedTypeException(final Object o1, final Object o2) {
return new ScriptRuntimeException(StringUtil.format("Unsupported type: left[{}], right[{}]", o1.getClass(), o2.getClass()));
}
private static ScriptRuntimeException unsupportedTypeException(final Object o1) {
return new ScriptRuntimeException(StringUtil.format("Unsupported type: [{}]", o1.getClass()));
}
private static void requireNonNull(final Object obj) {
if (obj == null) {
throw new ScriptRuntimeException("value is null");
}
}
private static void requireNonNull(final Object o1, final Object o2) {
if (o1 == null || o2 == null) {
throw new ScriptRuntimeException(
o1 == null
? (o2 == null ? "left & right values are null" : "left value is null")
: (o2 == null ? "right value is null" : "left & right values are not null"));
}
}
}
| update ALU | wit-core/src/main/java/org/febit/wit/util/ALU.java | update ALU | <ide><path>it-core/src/main/java/org/febit/wit/util/ALU.java
<ide> private static void requireNonNull(final Object o1, final Object o2) {
<ide> if (o1 == null || o2 == null) {
<ide> throw new ScriptRuntimeException(
<del> o1 == null
<del> ? (o2 == null ? "left & right values are null" : "left value is null")
<del> : (o2 == null ? "right value is null" : "left & right values are not null"));
<add> o1 != null
<add> ? "right value is null"
<add> : o2 != null
<add> ? "left value is null"
<add> : "left & right values are null");
<ide> }
<ide> }
<ide> } |
|
Java | mit | 6c45612fd105a24498d4bfc87b52d347520afce8 | 0 | hackathon-fintech/hackathon-backend,hackathon-fintech/hackathon-backend,hackathon-fintech/hackathon-backend | package com.variacode.bancointeligente.core.rest;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CORSFilter implements Filter {
public CORSFilter() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(
ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Origin", "*"
);
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Credentials", "true"
);
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"
);
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Headers", "password,token,rut,body, X-Requested-With, origin, content-type, accept"
);
chain.doFilter(request, response);
}
}
| src/main/java/com/variacode/bancointeligente/core/rest/CORSFilter.java | package com.variacode.bancointeligente.core.rest;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CORSFilter implements Filter {
public CORSFilter() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(
ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Origin", "*"
);
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Credentials", "true"
);
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"
);
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Headers", "password,rut,body, X-Requested-With, origin, content-type, accept"
);
chain.doFilter(request, response);
}
}
| fuck yes
| src/main/java/com/variacode/bancointeligente/core/rest/CORSFilter.java | fuck yes | <ide><path>rc/main/java/com/variacode/bancointeligente/core/rest/CORSFilter.java
<ide> "Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"
<ide> );
<ide> ((HttpServletResponse) response).addHeader(
<del> "Access-Control-Allow-Headers", "password,rut,body, X-Requested-With, origin, content-type, accept"
<add> "Access-Control-Allow-Headers", "password,token,rut,body, X-Requested-With, origin, content-type, accept"
<ide> );
<ide> chain.doFilter(request, response);
<ide> } |
|
JavaScript | mit | 239e2f7456a3cb08365ae261b6d7cd5fc44ba673 | 0 | karfcz/kff |
var createClass = require('../functions/createClass');
var convertValueType = require('../functions/convertValueType');
var noop = require('../functions/noop');
var Binder = require('../Binder');
var View = require('../View');
var insertBefore = require('../functions/nodeMan').insertBefore;
var removeChild = require('../functions/nodeMan').removeChild;
var Cursor = require('../Cursor');
var createInsertBinder = function(negate, force){
return createClass(
{
extend: Binder
},
/** @lends InsertBinder.prototype */
{
/**
* One-way data binder (model to DOM) for inserting/removing element from DOM.
*
* @constructs
* @augments Binder
* @param {Object} options Options objectt
*/
constructor: function(options)
{
Binder.call(this, options);
this.equalsTo = undefined;
this.valueCursor = undefined;
},
init: function()
{
this.equalsTo = true;
this.valueCursor = undefined;
if(this.options.params[0])
{
this.equalsTo = this.convertBindingValue(this.options.params[0]);
if(this.equalsTo instanceof Cursor)
{
this.valueCursor = this.equalsTo;
this.equalsTo = this.valueCursor.get();
}
if(this.equalsTo == null) this.equalsTo = null;
}
// if(this.options.params[0])
// {
// if(this.options.parsers.length === 0) this.equalsTo = convertValueType(this.options.params[0]);
// else this.equalsTo = this.parse(this.options.params[0]);
// }
// else this.options.params[0] = this.equalsTo;
this.negate = this.options.params[1] === 'ne' || negate;
this.forceRerender = force || this.options.params[2] === 'force' || this.options.params[1] === 'force';
this.isInserted = true;
if(this.forceRerender)
{
this.isRun = false;
this.isRendered = true;
this.renderSubviews = this.view.renderSubviews;
this.runSubviews = this.view.runSubviews;
this.destroySubviews = this.view.destroySubviews;
this.view.renderSubviews = noop;
this.view.runSubviews = noop;
this.view.destroySubviews = noop;
}
Binder.prototype.init.call(this);
},
destroy: function()
{
if(this.forceRerender)
{
this.view.renderSubviews = this.renderSubviews;
this.view.runSubviews = this.runSubviews;
this.view.destroySubviews = this.destroySubviews;
}
if(!this.isInserted && this.anchor)
{
var parentNode = this.anchor.parentNode;
if(parentNode)
{
parentNode.replaceChild(this.$element[0], this.anchor);
}
this.isInserted = true;
}
this.anchor = null;
Binder.prototype.destroy.call(this);
},
refresh: function()
{
var parentNode;
if(!this.anchor)
{
this.anchor = this.view.env.document.createTextNode('');
this.$element[0].parentNode.insertBefore(this.anchor, this.$element[0]);
}
var nodeInsert = insertBefore;
var nodeRemove = removeChild;
if(this.animate)
{
nodeInsert = this.view.scope[this.animate]['insert'];
nodeRemove = this.view.scope[this.animate]['remove'];
}
if(this.matchValue())
{
if(!this.isInserted)
{
parentNode = this.anchor.parentNode;
if(parentNode)
{
nodeInsert(parentNode, this.anchor, this.$element[0]);
// parentNode.replaceChild(this.$element[0], this.anchor);
}
this.isInserted = true;
}
if(this.forceRerender)
{
if(!this.isRendered)
{
this.renderSubviews.call(this.view);
this.isRendered = true;
}
if(!this.isRun)
{
this.runSubviews.call(this.view);
this.isRun = true;
}
}
}
else
{
if(this.isInserted)
{
parentNode = this.$element[0].parentNode;
if(parentNode)
{
nodeRemove(parentNode, this.$element[0], this.f(function()
{
if(this.forceRerender && this.isRendered)
{
this.destroySubviews.call(this.view);
this.isRendered = false;
this.isRun = false;
}
this.isInserted = false;
}));
this.isInserted = false;
// parentNode.removeChild(this.$element[0]);
// parentNode.replaceChild(this.anchor, this.$element[0]);
}
}
else if(this.forceRerender && this.isRendered)
{
this.destroySubviews.call(this.view);
this.isRendered = false;
this.isRun = false;
}
}
},
matchValue: function()
{
if(this.options.params.length > 0)
{
if(this.valueCursor)
{
this.equalsTo = this.valueCursor.get();
if(this.equalsTo == null) this.equalsTo = null;
}
var value = this.value;
if(value == null) value = null;
if(this.negate) return value !== this.equalsTo;
else return value === this.equalsTo;
}
else return this.value;
}
});
};
// InsertBinder = createInsertBinder(false, false);
var IfBinder = createInsertBinder(false, true);
var IfNotBinder = createInsertBinder(true, true);
// BindingView.registerBinder('insert', InsertBinder);
View.registerBinder('if', IfBinder);
View.registerBinder('ifnot', IfNotBinder);
module.exports = {
IfBinder: IfBinder,
IfNotBinder: IfNotBinder
};
| src/binders/InsertBinder.js |
var createClass = require('../functions/createClass');
var convertValueType = require('../functions/convertValueType');
var noop = require('../functions/noop');
var Binder = require('../Binder');
var View = require('../View');
var insertBefore = require('../functions/nodeMan').insertBefore;
var removeChild = require('../functions/nodeMan').removeChild;
var createInsertBinder = function(negate, force){
return createClass(
{
extend: Binder
},
/** @lends InsertBinder.prototype */
{
/**
* One-way data binder (model to DOM) for inserting/removing element from DOM.
*
* @constructs
* @augments Binder
* @param {Object} options Options objectt
*/
constructor: function(options)
{
Binder.call(this, options);
},
init: function()
{
this.equalsTo = true;
if(this.options.params[0])
{
if(this.options.parsers.length === 0) this.equalsTo = convertValueType(this.options.params[0]);
else this.equalsTo = this.parse(this.options.params[0]);
}
else this.options.params[0] = this.equalsTo;
this.negate = this.options.params[1] === 'ne' || negate;
this.forceRerender = force || this.options.params[2] === 'force' || this.options.params[1] === 'force';
this.isInserted = true;
if(this.forceRerender)
{
this.isRun = false;
this.isRendered = true;
this.renderSubviews = this.view.renderSubviews;
this.runSubviews = this.view.runSubviews;
this.destroySubviews = this.view.destroySubviews;
this.view.renderSubviews = noop;
this.view.runSubviews = noop;
this.view.destroySubviews = noop;
}
Binder.prototype.init.call(this);
},
destroy: function()
{
if(this.forceRerender)
{
this.view.renderSubviews = this.renderSubviews;
this.view.runSubviews = this.runSubviews;
this.view.destroySubviews = this.destroySubviews;
}
if(!this.isInserted && this.anchor)
{
var parentNode = this.anchor.parentNode;
if(parentNode)
{
parentNode.replaceChild(this.$element[0], this.anchor);
}
this.isInserted = true;
}
this.anchor = null;
Binder.prototype.destroy.call(this);
},
refresh: function()
{
var parentNode;
if(!this.anchor)
{
this.anchor = this.view.env.document.createTextNode('');
this.$element[0].parentNode.insertBefore(this.anchor, this.$element[0]);
}
var nodeInsert = insertBefore;
var nodeRemove = removeChild;
if(this.animate)
{
nodeInsert = this.view.scope[this.animate]['insert'];
nodeRemove = this.view.scope[this.animate]['remove'];
}
if(this.matchValue())
{
if(!this.isInserted)
{
parentNode = this.anchor.parentNode;
if(parentNode)
{
nodeInsert(parentNode, this.anchor, this.$element[0]);
// parentNode.replaceChild(this.$element[0], this.anchor);
}
this.isInserted = true;
}
if(this.forceRerender)
{
if(!this.isRendered)
{
this.renderSubviews.call(this.view);
this.isRendered = true;
}
if(!this.isRun)
{
this.runSubviews.call(this.view);
this.isRun = true;
}
}
}
else
{
if(this.isInserted)
{
parentNode = this.$element[0].parentNode;
if(parentNode)
{
nodeRemove(parentNode, this.$element[0], this.f(function()
{
if(this.forceRerender && this.isRendered)
{
this.destroySubviews.call(this.view);
this.isRendered = false;
this.isRun = false;
}
this.isInserted = false;
}));
this.isInserted = false;
// parentNode.removeChild(this.$element[0]);
// parentNode.replaceChild(this.anchor, this.$element[0]);
}
}
else if(this.forceRerender && this.isRendered)
{
this.destroySubviews.call(this.view);
this.isRendered = false;
this.isRun = false;
}
}
},
matchValue: function()
{
if(this.options.params.length > 0)
{
if(this.negate) return this.value !== this.equalsTo;
else return this.value === this.equalsTo;
}
else return this.value;
}
});
};
// InsertBinder = createInsertBinder(false, false);
var IfBinder = createInsertBinder(false, true);
var IfNotBinder = createInsertBinder(true, true);
// BindingView.registerBinder('insert', InsertBinder);
View.registerBinder('if', IfBinder);
View.registerBinder('ifnot', IfNotBinder);
module.exports = {
IfBinder: IfBinder,
IfNotBinder: IfNotBinder
};
| feat(InsertBinder): allow use of @model.value notation in if/ifnot binder for dynamic value setting
| src/binders/InsertBinder.js | feat(InsertBinder): allow use of @model.value notation in if/ifnot binder for dynamic value setting | <ide><path>rc/binders/InsertBinder.js
<ide> var View = require('../View');
<ide> var insertBefore = require('../functions/nodeMan').insertBefore;
<ide> var removeChild = require('../functions/nodeMan').removeChild;
<add>var Cursor = require('../Cursor');
<ide>
<ide> var createInsertBinder = function(negate, force){
<ide>
<ide> constructor: function(options)
<ide> {
<ide> Binder.call(this, options);
<add> this.equalsTo = undefined;
<add> this.valueCursor = undefined;
<ide> },
<ide>
<ide> init: function()
<ide> {
<ide> this.equalsTo = true;
<add> this.valueCursor = undefined;
<ide>
<ide> if(this.options.params[0])
<ide> {
<del> if(this.options.parsers.length === 0) this.equalsTo = convertValueType(this.options.params[0]);
<del> else this.equalsTo = this.parse(this.options.params[0]);
<del> }
<del> else this.options.params[0] = this.equalsTo;
<add> this.equalsTo = this.convertBindingValue(this.options.params[0]);
<add> if(this.equalsTo instanceof Cursor)
<add> {
<add> this.valueCursor = this.equalsTo;
<add> this.equalsTo = this.valueCursor.get();
<add> }
<add> if(this.equalsTo == null) this.equalsTo = null;
<add> }
<add>
<add>
<add> // if(this.options.params[0])
<add> // {
<add> // if(this.options.parsers.length === 0) this.equalsTo = convertValueType(this.options.params[0]);
<add> // else this.equalsTo = this.parse(this.options.params[0]);
<add> // }
<add> // else this.options.params[0] = this.equalsTo;
<ide>
<ide> this.negate = this.options.params[1] === 'ne' || negate;
<ide>
<ide> {
<ide> if(this.options.params.length > 0)
<ide> {
<del> if(this.negate) return this.value !== this.equalsTo;
<del> else return this.value === this.equalsTo;
<add> if(this.valueCursor)
<add> {
<add> this.equalsTo = this.valueCursor.get();
<add> if(this.equalsTo == null) this.equalsTo = null;
<add> }
<add> var value = this.value;
<add> if(value == null) value = null;
<add> if(this.negate) return value !== this.equalsTo;
<add> else return value === this.equalsTo;
<ide> }
<ide> else return this.value;
<ide> } |
|
Java | apache-2.0 | 3690a6bdc516d20e6e332786a1252e87a88d2a1b | 0 | dailystudio/devbricks,dailystudio/devbricks | package com.dailystudio.app.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import com.dailystudio.R;
import com.dailystudio.development.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nanye on 17/5/8.
*/
public abstract class SettingsFragment extends BaseIntentFragment {
public interface LayoutHolder {
View getView();
View createView(Context context, Setting setting);
void invalidate(Context context, Setting setting);
}
public final static String ACTION_SETTINGS_CHANGED =
"devbricks.intent.ACTION_SETTINGS_CHANGED";
public final static String EXTRA_SETTING_NAME =
"devbricks.intent.EXTRA_SETTING_NAME";
public static class Setting {
private Context mContext;
private String mName;
private Drawable mIcon;
private CharSequence mLabel;
private LayoutHolder mHolder;
public Setting(Context context, String name, int iconResId, int labelResId, LayoutHolder holder) {
mContext = context.getApplicationContext();
mHolder = holder;
mName = name;
setIcon(iconResId);
setLabel(labelResId);
}
public String getName() {
return mName;
}
public void setIcon(Drawable d) {
mIcon = d;
}
public void setIcon(int iconResId) {
if (mContext == null) {
return;
}
final Resources res = mContext.getResources();
if (res == null) {
return;
}
setIcon(res.getDrawable(iconResId));
}
public void setLabel(CharSequence label) {
mLabel = label;
}
public void setLabel(int labelResId) {
if (mContext == null) {
return;
}
final Resources res = mContext.getResources();
if (res == null) {
return;
}
setLabel(res.getString(labelResId));
}
public Drawable getIcon() {
return mIcon;
}
public CharSequence getLabel() {
return mLabel;
}
public Context getContext() {
return mContext;
}
public LayoutHolder getLayoutHolder() {
return mHolder;
}
public void notifyDataChanges() {
mHandler.removeCallbacks(mNotifyDataChangesRunnable);
mHandler.postDelayed(mNotifyDataChangesRunnable, 300);
}
@Override
public String toString() {
return String.format("%s(0x%08x): label = %s, icon = %s, holder = %s",
getClass().getSimpleName(),
hashCode(),
getLabel(),
getIcon(),
getLayoutHolder());
}
protected void notifySettingsChanged() {
SettingsFragment.notifySettingChange(getContext(), getName());
}
private Runnable mNotifyDataChangesRunnable = new Runnable() {
@Override
public void run() {
if (mHolder != null) {
mHolder.invalidate(getContext(), Setting.this);
}
}
};
private Handler mHandler = new Handler();
}
public static class TextSetting extends Setting {
private CharSequence mDesc;
public TextSetting(Context context,
String name,
int iconResId,
int labelResId,
TextSettingsLayoutHolder holder) {
this(context, name, iconResId, labelResId, -1, holder);
}
public TextSetting(Context context,
String name,
int iconResId,
int labelResId,
int descResId,
TextSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
setDesc(descResId);
}
public void setDesc(CharSequence desc) {
mDesc = desc;
}
public void setDesc(int descResId) {
final Context context = getContext();
if (context == null) {
return;
}
final Resources res = context.getResources();
if (res == null) {
return;
}
if (descResId <= 0) {
setDesc(null);
return;
}
setDesc(res.getString(descResId));
}
public CharSequence getDesc() {
return mDesc;
}
}
public abstract static class EditSetting extends Setting {
public EditSetting(Context context,
String name,
int iconResId,
int labelResId,
EditSettingLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public CharSequence getEditHint(Context context) {
return null;
}
public Drawable getEditButtonDrawable(Context context) {
return null;
}
public abstract CharSequence getEditText(Context context);
public abstract void setEditText(Context context, CharSequence text);
public abstract void onEditButtonClicked(Context context);
}
public class EditSettingLayoutHolder extends BaseSettingLayoutHolder {
private EditText mEditText;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_edit, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (context == null) {
return;
}
final EditSetting editSetting = (EditSetting) setting;
if (mEditText != null) {
mEditText.setText(editSetting.getEditText(context));
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof EditSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final EditSetting editSetting = (EditSetting) setting;
final ImageView editButton = (ImageView) settingView.findViewById(
R.id.setting_edit_image_button);
if (editButton != null) {
final Drawable drawable =
((EditSetting) setting).getEditButtonDrawable(context);
if (drawable == null) {
editButton.setVisibility(View.GONE);
editButton.setOnClickListener(null);
} else {
editButton.setVisibility(View.VISIBLE);
editButton.setImageDrawable(drawable);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editSetting.onEditButtonClicked(context);
}
});
}
}
mEditText = (EditText) settingView.findViewById(
R.id.setting_edit);
if (mEditText != null) {
mEditText.setText(editSetting.getEditText(context));
mEditText.setHint(editSetting.getEditHint(context));
mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == false) {
Editable editable = mEditText.getText();
if (editable != null) {
performEditTextChange(editSetting,
editable);
}
}
}
});
}
}
protected void performEditTextChange(EditSetting editSetting, CharSequence s) {
if (editSetting == null) {
return;
}
mHandler.removeMessages(MSG_TEXT_CHANGED);
TextChangeData tcd = new TextChangeData();
tcd.editSetting = editSetting;
tcd.text = s;
Message msg = Message.obtain(mHandler, MSG_TEXT_CHANGED, tcd);
mHandler.sendMessageDelayed(msg, DELAY);
}
private final static int MSG_TEXT_CHANGED = 0x1;
private final static long DELAY = 500;
private class TextChangeData {
private EditSetting editSetting;
private CharSequence text;
}
private Handler mHandler = new Handler() {
@Override
public void dispatchMessage(Message msg) {
if (msg.what == MSG_TEXT_CHANGED
&& msg.obj instanceof TextChangeData) {
TextChangeData tcd = (TextChangeData)msg.obj;
if (tcd.editSetting != null) {
tcd.editSetting.setEditText(getContext(), tcd.text);
tcd.editSetting.notifySettingsChanged();
}
return;
}
super.dispatchMessage(msg);
}
};
}
public static abstract class SwitchSetting extends TextSetting {
public SwitchSetting(Context context,
String name,
int iconResId,
int labelResId,
SwitchSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public SwitchSetting(Context context,
String name,
int iconResId,
int labelResId,
int descResId,
SwitchSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, descResId, holder);
}
public abstract boolean isSwitchOn(Context context);
public abstract void setSwitchOn(Context context, boolean on);
}
public static abstract class SeekBarSetting extends Setting {
public SeekBarSetting(Context context,
String name,
int iconResId,
int labelResId,
SeekBarSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public abstract int getProgress(Context context);
public abstract void setProgress(Context context, int progress);
public abstract int getMinValue(Context context);
public abstract int getMaxValue(Context context);
public abstract int getStep(Context context);
}
public interface RadioSettingItem {
public CharSequence getLabel();
public String getId();
}
public class SimpleRadioSettingItem implements RadioSettingItem {
private Context mContext;
private int mLabelResId;
private String mItemId;
public SimpleRadioSettingItem(@NonNull Context context,
int labelResId,
@NonNull String itemId) {
mContext = context.getApplicationContext();
mLabelResId = labelResId;
mItemId = itemId;
}
@Override
public CharSequence getLabel() {
return mContext.getString(mLabelResId);
}
@Override
public String getId() {
return mItemId;
}
}
public abstract static class RadioSetting<T extends RadioSettingItem> extends Setting {
private List<T> mRadioItems = new ArrayList<>();
private Object mLock = new Object();
public RadioSetting(Context context,
String name,
int iconResId,
int labelResId,
RadioSettingsLayoutHolder holder,
T[] items) {
super(context, name, iconResId, labelResId, holder);
addItems(items);
}
public void addItem(T item) {
synchronized (mLock) {
mRadioItems.add(item);
}
notifyDataChanges();
}
public void addItems(T[] items) {
if (items == null
|| items.length <= 0) {
return;
}
synchronized (mLock) {
for (T item : items) {
mRadioItems.add(item);
}
}
notifyDataChanges();
}
public void clear() {
synchronized (mLock) {
mRadioItems.clear();
}
notifyDataChanges();
}
public T getItem(int position) {
return mRadioItems.get(position);
}
public int getItemCount() {
return mRadioItems.size();
}
public T findItemById(String itemId) {
if (TextUtils.isEmpty(itemId)) {
return null;
}
for (T item: mRadioItems) {
if (itemId.equals(item.getId())) {
return item;
}
}
return null;
}
protected abstract String getSelectedId();
protected abstract void setSelected(String selectedId);
}
public class RadioSettingsLayoutHolder<T extends RadioSettingItem> extends BaseSettingLayoutHolder {
private RadioGroup mRadioGroup;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_radio, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (mRadioGroup == null) {
return;
}
mRadioGroup.removeAllViews();
if (setting instanceof RadioSetting) {
bindRadios(getContext(), mRadioGroup,
(RadioSetting)setting);
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof RadioSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final RadioSetting radioSetting = (RadioSetting) setting;
mRadioGroup = (RadioGroup) settingView.findViewById(
R.id.selection_group);
if (mRadioGroup != null) {
}
}
private void bindRadios(Context context,
RadioGroup radioGroup,
final RadioSetting<T> radioSetting) {
if (context == null
|| radioGroup == null
|| radioSetting == null) {
return;
}
final int N = radioSetting.getItemCount();
if (N <= 0) {
return;
}
final String selectedId = radioSetting.getSelectedId();
RadioSettingItem item;
RadioButton rb;
RadioButton[] rbs = new RadioButton[N];
for (int i = 0; i < N; i++) {
item = radioSetting.getItem(i);
rb = new RadioButton(context);
rb.setText(item.getLabel());
rb.setTextAppearance(context, R.style.SettingsText);
rb.setTag(item);
rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked && compoundButton != null) {
Object o = compoundButton.getTag();
if (o instanceof RadioSettingItem) {
RadioSettingItem i = (RadioSettingItem)o;
radioSetting.setSelected(i.getId());
}
radioSetting.notifySettingsChanged();
}
}
});
mRadioGroup.addView(rb);
rbs[i] = rb;
}
for (int i = 0; i < N; i++) {
item = radioSetting.getItem(i);
rb = rbs[i];
if (!TextUtils.isEmpty(selectedId)
&& selectedId.equals(item.getId())) {
rb.setChecked(true);
} else {
rb.setChecked(false);
}
}
}
}
public class SwitchSettingsLayoutHolder extends TextSettingsLayoutHolder {
private Switch mSwitch;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_switch, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (mSwitch != null
&& setting instanceof SwitchSetting) {
final boolean switchOn =
((SwitchSetting)setting).isSwitchOn(context);
mSwitch.setChecked(switchOn);
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof SwitchSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final SwitchSetting switchSetting = (SwitchSetting) setting;
mSwitch = settingView.findViewById(
R.id.setting_switch);
if (mSwitch != null) {
final boolean switchOn =
switchSetting.isSwitchOn(context);
mSwitch.setChecked(switchOn);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switchSetting.setSwitchOn(context, isChecked);
switchSetting.notifySettingsChanged();
}
});
}
}
}
public class TextSettingsLayoutHolder extends BaseSettingLayoutHolder {
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_text, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof TextSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final TextSetting textSetting = (TextSetting) setting;
TextView descView = settingView.findViewById(R.id.setting_desc);
if (descView != null) {
final CharSequence desc = textSetting.getDesc();
descView.setText(desc);
if (TextUtils.isEmpty(desc)) {
descView.setVisibility(View.GONE);
} else {
descView.setVisibility(View.VISIBLE);
}
}
View rootView = settingView.findViewById(
R.id.setting_root);
if (rootView != null) {
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Logger.debug("clicked on text settings");
textSetting.notifySettingsChanged();
}
});
}
}
}
public class SeekBarSettingsLayoutHolder extends BaseSettingLayoutHolder {
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_seek_bar, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
View view = getView();
if (view == null) {
return;
}
if (setting instanceof SeekBarSetting == false) {
return;
}
SeekBarSetting seekBarSetting = (SeekBarSetting)setting;
SeekBar seekBarView = (SeekBar) view.findViewById(
R.id.setting_seek_bar);
syncProgressWithSetting(getContext(), seekBarView, seekBarSetting);
}
private void syncProgressWithSetting(Context context,
SeekBar seekBar,
SeekBarSetting seekBarSetting) {
if (context == null
|| seekBar == null
|| seekBarSetting == null) {
return;
}
final int progress = seekBarSetting.getProgress(context);
final int step = seekBarSetting.getStep(context);
final int min = seekBarSetting.getMinValue(context);
final int max = seekBarSetting.getMaxValue(context);
final int prg = min + (progress * step);
/*
Logger.debug("prg = %d, [min: %d, max: %d, step: %d",
prg, min, max, step);
*/
seekBar.setProgress((prg - min) / step);
seekBar.setMax((max - min) / step);
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof SeekBarSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final SeekBarSetting seekBarSetting = (SeekBarSetting) setting;
final TextView seekValView = (TextView) settingView.findViewById(
R.id.setting_seek_value);
if (seekValView != null) {
seekValView.setText(String.valueOf(
seekBarSetting.getProgress(context)));
}
SeekBar seekBarView = (SeekBar) settingView.findViewById(
R.id.setting_seek_bar);
if (seekBarView != null) {
syncProgressWithSetting(getContext(), seekBarView, seekBarSetting);
seekBarView.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int prg = seekBarSetting.getMinValue(context)
+ (progress * seekBarSetting.getStep(context));
if (seekValView != null) {
seekValView.setText(String.valueOf(prg));
}
seekBarSetting.setProgress(context, prg);
seekBarSetting.notifySettingsChanged();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
}
public abstract class BaseSettingLayoutHolder implements LayoutHolder {
private View mView;
@Override
final public View createView(Context context, Setting setting) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
mView = onCreateView(context, layoutInflater, setting);
bingSetting(mView, setting);
return mView;
}
@Override
public View getView() {
return mView;
}
protected void bingSetting(View settingView, Setting setting) {
if (settingView == null
|| setting == null) {
return;
}
ImageView iconView = (ImageView) settingView.findViewById(
R.id.setting_icon);
if (iconView != null) {
iconView.setImageDrawable(setting.getIcon());
}
TextView labelView = (TextView) settingView.findViewById(
R.id.setting_label);
if (labelView != null) {
labelView.setText(setting.getLabel());
}
}
protected abstract View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting);
}
private ViewGroup mSettingsContainer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, null);
setupViews(view);
return view;
}
private void setupViews(View fragmentView) {
if (fragmentView == null) {
return;
}
mSettingsContainer = (ViewGroup) fragmentView.findViewById(R.id.settings_container);
reloadSettings();
}
protected void reloadSettings() {
mSettingsContainer.removeAllViews();
Setting[] settings = createSettings(getContext());
if (settings != null) {
for (Setting s: settings) {
addSetting(s);
}
}
}
protected abstract Setting[] createSettings(Context context);
public void addSetting(Setting setting) {
Logger.debug("add setting: %s", setting);
if (setting == null) {
return;
}
Logger.debug("mSettingsContainer = %s", mSettingsContainer);
if (mSettingsContainer == null) {
return;
}
LayoutHolder lh = setting.getLayoutHolder();
if (lh == null) {
return;
}
View view = lh.createView(getContext(), setting);
if (view == null) {
return;
}
LinearLayout.LayoutParams llp =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
Logger.debug("add settings view: %s", view);
mSettingsContainer.addView(view, llp);
}
public static void registerSettingChangesReceiver(Context context, BroadcastReceiver receiver) {
if (context == null || receiver == null) {
return;
}
IntentFilter filter = new IntentFilter(ACTION_SETTINGS_CHANGED);
try {
LocalBroadcastManager.getInstance(context)
.registerReceiver(receiver, filter);
} catch (Exception e) {
Logger.warn("could not register receiver [%s] on %s: %s",
receiver, ACTION_SETTINGS_CHANGED, e.toString());
}
}
public static void unregisterSettingChangesReceiver(Context context, BroadcastReceiver receiver) {
if (context == null || receiver == null) {
return;
}
try {
LocalBroadcastManager.getInstance(context)
.unregisterReceiver(receiver);
} catch (Exception e) {
Logger.warn("could not unregister receiver [%s] from %s: %s",
receiver, ACTION_SETTINGS_CHANGED, e.toString());
}
}
public static void notifySettingChange(Context context, String settingId) {
Intent i = new Intent(ACTION_SETTINGS_CHANGED);
i.putExtra(EXTRA_SETTING_NAME, settingId);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
}
}
| src/main/java/com/dailystudio/app/fragment/SettingsFragment.java | package com.dailystudio.app.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import com.dailystudio.R;
import com.dailystudio.development.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nanye on 17/5/8.
*/
public abstract class SettingsFragment extends BaseIntentFragment {
public interface LayoutHolder {
View getView();
View createView(Context context, Setting setting);
void invalidate(Context context, Setting setting);
}
public final static String ACTION_SETTINGS_CHANGED =
"devbricks.intent.ACTION_SETTINGS_CHANGED";
public final static String EXTRA_SETTING_NAME =
"devbricks.intent.EXTRA_SETTING_NAME";
public static class Setting {
private Context mContext;
private String mName;
private Drawable mIcon;
private CharSequence mLabel;
private LayoutHolder mHolder;
public Setting(Context context, String name, int iconResId, int labelResId, LayoutHolder holder) {
mContext = context.getApplicationContext();
mHolder = holder;
mName = name;
setIcon(iconResId);
setLabel(labelResId);
}
public String getName() {
return mName;
}
public void setIcon(Drawable d) {
mIcon = d;
}
public void setIcon(int iconResId) {
if (mContext == null) {
return;
}
final Resources res = mContext.getResources();
if (res == null) {
return;
}
setIcon(res.getDrawable(iconResId));
}
public void setLabel(CharSequence label) {
mLabel = label;
}
public void setLabel(int labelResId) {
if (mContext == null) {
return;
}
final Resources res = mContext.getResources();
if (res == null) {
return;
}
setLabel(res.getString(labelResId));
}
public Drawable getIcon() {
return mIcon;
}
public CharSequence getLabel() {
return mLabel;
}
public Context getContext() {
return mContext;
}
public LayoutHolder getLayoutHolder() {
return mHolder;
}
public void notifyDataChanges() {
mHandler.removeCallbacks(mNotifyDataChangesRunnable);
mHandler.postDelayed(mNotifyDataChangesRunnable, 300);
}
@Override
public String toString() {
return String.format("%s(0x%08x): label = %s, icon = %s, holder = %s",
getClass().getSimpleName(),
hashCode(),
getLabel(),
getIcon(),
getLayoutHolder());
}
protected void notifySettingsChanged() {
Intent i = new Intent(ACTION_SETTINGS_CHANGED);
i.putExtra(EXTRA_SETTING_NAME, getName());
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(i);
}
private Runnable mNotifyDataChangesRunnable = new Runnable() {
@Override
public void run() {
if (mHolder != null) {
mHolder.invalidate(getContext(), Setting.this);
}
}
};
private Handler mHandler = new Handler();
}
public static class TextSetting extends Setting {
private CharSequence mDesc;
public TextSetting(Context context,
String name,
int iconResId,
int labelResId,
TextSettingsLayoutHolder holder) {
this(context, name, iconResId, labelResId, -1, holder);
}
public TextSetting(Context context,
String name,
int iconResId,
int labelResId,
int descResId,
TextSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
setDesc(descResId);
}
public void setDesc(CharSequence desc) {
mDesc = desc;
}
public void setDesc(int descResId) {
final Context context = getContext();
if (context == null) {
return;
}
final Resources res = context.getResources();
if (res == null) {
return;
}
if (descResId <= 0) {
setDesc(null);
return;
}
setDesc(res.getString(descResId));
}
public CharSequence getDesc() {
return mDesc;
}
}
public abstract static class EditSetting extends Setting {
public EditSetting(Context context,
String name,
int iconResId,
int labelResId,
EditSettingLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public CharSequence getEditHint(Context context) {
return null;
}
public Drawable getEditButtonDrawable(Context context) {
return null;
}
public abstract CharSequence getEditText(Context context);
public abstract void setEditText(Context context, CharSequence text);
public abstract void onEditButtonClicked(Context context);
}
public class EditSettingLayoutHolder extends BaseSettingLayoutHolder {
private EditText mEditText;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_edit, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (context == null) {
return;
}
final EditSetting editSetting = (EditSetting) setting;
if (mEditText != null) {
mEditText.setText(editSetting.getEditText(context));
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof EditSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final EditSetting editSetting = (EditSetting) setting;
final ImageView editButton = (ImageView) settingView.findViewById(
R.id.setting_edit_image_button);
if (editButton != null) {
final Drawable drawable =
((EditSetting) setting).getEditButtonDrawable(context);
if (drawable == null) {
editButton.setVisibility(View.GONE);
editButton.setOnClickListener(null);
} else {
editButton.setVisibility(View.VISIBLE);
editButton.setImageDrawable(drawable);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editSetting.onEditButtonClicked(context);
}
});
}
}
mEditText = (EditText) settingView.findViewById(
R.id.setting_edit);
if (mEditText != null) {
mEditText.setText(editSetting.getEditText(context));
mEditText.setHint(editSetting.getEditHint(context));
mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == false) {
Editable editable = mEditText.getText();
if (editable != null) {
performEditTextChange(editSetting,
editable);
}
}
}
});
}
}
protected void performEditTextChange(EditSetting editSetting, CharSequence s) {
if (editSetting == null) {
return;
}
mHandler.removeMessages(MSG_TEXT_CHANGED);
TextChangeData tcd = new TextChangeData();
tcd.editSetting = editSetting;
tcd.text = s;
Message msg = Message.obtain(mHandler, MSG_TEXT_CHANGED, tcd);
mHandler.sendMessageDelayed(msg, DELAY);
}
private final static int MSG_TEXT_CHANGED = 0x1;
private final static long DELAY = 500;
private class TextChangeData {
private EditSetting editSetting;
private CharSequence text;
}
private Handler mHandler = new Handler() {
@Override
public void dispatchMessage(Message msg) {
if (msg.what == MSG_TEXT_CHANGED
&& msg.obj instanceof TextChangeData) {
TextChangeData tcd = (TextChangeData)msg.obj;
if (tcd.editSetting != null) {
tcd.editSetting.setEditText(getContext(), tcd.text);
tcd.editSetting.notifySettingsChanged();
}
return;
}
super.dispatchMessage(msg);
}
};
}
public static abstract class SwitchSetting extends TextSetting {
public SwitchSetting(Context context,
String name,
int iconResId,
int labelResId,
SwitchSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public SwitchSetting(Context context,
String name,
int iconResId,
int labelResId,
int descResId,
SwitchSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, descResId, holder);
}
public abstract boolean isSwitchOn(Context context);
public abstract void setSwitchOn(Context context, boolean on);
}
public static abstract class SeekBarSetting extends Setting {
public SeekBarSetting(Context context,
String name,
int iconResId,
int labelResId,
SeekBarSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public abstract int getProgress(Context context);
public abstract void setProgress(Context context, int progress);
public abstract int getMinValue(Context context);
public abstract int getMaxValue(Context context);
public abstract int getStep(Context context);
}
public interface RadioSettingItem {
public CharSequence getLabel();
public String getId();
}
public class SimpleRadioSettingItem implements RadioSettingItem {
private Context mContext;
private int mLabelResId;
private String mItemId;
public SimpleRadioSettingItem(@NonNull Context context,
int labelResId,
@NonNull String itemId) {
mContext = context.getApplicationContext();
mLabelResId = labelResId;
mItemId = itemId;
}
@Override
public CharSequence getLabel() {
return mContext.getString(mLabelResId);
}
@Override
public String getId() {
return mItemId;
}
}
public abstract static class RadioSetting<T extends RadioSettingItem> extends Setting {
private List<T> mRadioItems = new ArrayList<>();
private Object mLock = new Object();
public RadioSetting(Context context,
String name,
int iconResId,
int labelResId,
RadioSettingsLayoutHolder holder,
T[] items) {
super(context, name, iconResId, labelResId, holder);
addItems(items);
}
public void addItem(T item) {
synchronized (mLock) {
mRadioItems.add(item);
}
notifyDataChanges();
}
public void addItems(T[] items) {
if (items == null
|| items.length <= 0) {
return;
}
synchronized (mLock) {
for (T item : items) {
mRadioItems.add(item);
}
}
notifyDataChanges();
}
public void clear() {
synchronized (mLock) {
mRadioItems.clear();
}
notifyDataChanges();
}
public T getItem(int position) {
return mRadioItems.get(position);
}
public int getItemCount() {
return mRadioItems.size();
}
public T findItemById(String itemId) {
if (TextUtils.isEmpty(itemId)) {
return null;
}
for (T item: mRadioItems) {
if (itemId.equals(item.getId())) {
return item;
}
}
return null;
}
protected abstract String getSelectedId();
protected abstract void setSelected(String selectedId);
}
public class RadioSettingsLayoutHolder<T extends RadioSettingItem> extends BaseSettingLayoutHolder {
private RadioGroup mRadioGroup;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_radio, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (mRadioGroup == null) {
return;
}
mRadioGroup.removeAllViews();
if (setting instanceof RadioSetting) {
bindRadios(getContext(), mRadioGroup,
(RadioSetting)setting);
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof RadioSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final RadioSetting radioSetting = (RadioSetting) setting;
mRadioGroup = (RadioGroup) settingView.findViewById(
R.id.selection_group);
if (mRadioGroup != null) {
}
}
private void bindRadios(Context context,
RadioGroup radioGroup,
final RadioSetting<T> radioSetting) {
if (context == null
|| radioGroup == null
|| radioSetting == null) {
return;
}
final int N = radioSetting.getItemCount();
if (N <= 0) {
return;
}
final String selectedId = radioSetting.getSelectedId();
RadioSettingItem item;
RadioButton rb;
RadioButton[] rbs = new RadioButton[N];
for (int i = 0; i < N; i++) {
item = radioSetting.getItem(i);
rb = new RadioButton(context);
rb.setText(item.getLabel());
rb.setTextAppearance(context, R.style.SettingsText);
rb.setTag(item);
rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked && compoundButton != null) {
Object o = compoundButton.getTag();
if (o instanceof RadioSettingItem) {
RadioSettingItem i = (RadioSettingItem)o;
radioSetting.setSelected(i.getId());
}
radioSetting.notifySettingsChanged();
}
}
});
mRadioGroup.addView(rb);
rbs[i] = rb;
}
for (int i = 0; i < N; i++) {
item = radioSetting.getItem(i);
rb = rbs[i];
if (!TextUtils.isEmpty(selectedId)
&& selectedId.equals(item.getId())) {
rb.setChecked(true);
} else {
rb.setChecked(false);
}
}
}
}
public class SwitchSettingsLayoutHolder extends TextSettingsLayoutHolder {
private Switch mSwitch;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_switch, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (mSwitch != null
&& setting instanceof SwitchSetting) {
final boolean switchOn =
((SwitchSetting)setting).isSwitchOn(context);
mSwitch.setChecked(switchOn);
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof SwitchSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final SwitchSetting switchSetting = (SwitchSetting) setting;
mSwitch = settingView.findViewById(
R.id.setting_switch);
if (mSwitch != null) {
final boolean switchOn =
switchSetting.isSwitchOn(context);
mSwitch.setChecked(switchOn);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switchSetting.setSwitchOn(context, isChecked);
switchSetting.notifySettingsChanged();
}
});
}
}
}
public class TextSettingsLayoutHolder extends BaseSettingLayoutHolder {
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_text, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof TextSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final TextSetting textSetting = (TextSetting) setting;
TextView descView = settingView.findViewById(R.id.setting_desc);
if (descView != null) {
final CharSequence desc = textSetting.getDesc();
descView.setText(desc);
if (TextUtils.isEmpty(desc)) {
descView.setVisibility(View.GONE);
} else {
descView.setVisibility(View.VISIBLE);
}
}
View rootView = settingView.findViewById(
R.id.setting_root);
if (rootView != null) {
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Logger.debug("clicked on text settings");
textSetting.notifySettingsChanged();
}
});
}
}
}
public class SeekBarSettingsLayoutHolder extends BaseSettingLayoutHolder {
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_seek_bar, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
View view = getView();
if (view == null) {
return;
}
if (setting instanceof SeekBarSetting == false) {
return;
}
SeekBarSetting seekBarSetting = (SeekBarSetting)setting;
SeekBar seekBarView = (SeekBar) view.findViewById(
R.id.setting_seek_bar);
syncProgressWithSetting(getContext(), seekBarView, seekBarSetting);
}
private void syncProgressWithSetting(Context context,
SeekBar seekBar,
SeekBarSetting seekBarSetting) {
if (context == null
|| seekBar == null
|| seekBarSetting == null) {
return;
}
final int progress = seekBarSetting.getProgress(context);
final int step = seekBarSetting.getStep(context);
final int min = seekBarSetting.getMinValue(context);
final int max = seekBarSetting.getMaxValue(context);
final int prg = min + (progress * step);
/*
Logger.debug("prg = %d, [min: %d, max: %d, step: %d",
prg, min, max, step);
*/
seekBar.setProgress((prg - min) / step);
seekBar.setMax((max - min) / step);
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof SeekBarSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final SeekBarSetting seekBarSetting = (SeekBarSetting) setting;
final TextView seekValView = (TextView) settingView.findViewById(
R.id.setting_seek_value);
if (seekValView != null) {
seekValView.setText(String.valueOf(
seekBarSetting.getProgress(context)));
}
SeekBar seekBarView = (SeekBar) settingView.findViewById(
R.id.setting_seek_bar);
if (seekBarView != null) {
syncProgressWithSetting(getContext(), seekBarView, seekBarSetting);
seekBarView.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int prg = seekBarSetting.getMinValue(context)
+ (progress * seekBarSetting.getStep(context));
if (seekValView != null) {
seekValView.setText(String.valueOf(prg));
}
seekBarSetting.setProgress(context, prg);
seekBarSetting.notifySettingsChanged();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
}
public abstract class BaseSettingLayoutHolder implements LayoutHolder {
private View mView;
@Override
final public View createView(Context context, Setting setting) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
mView = onCreateView(context, layoutInflater, setting);
bingSetting(mView, setting);
return mView;
}
@Override
public View getView() {
return mView;
}
protected void bingSetting(View settingView, Setting setting) {
if (settingView == null
|| setting == null) {
return;
}
ImageView iconView = (ImageView) settingView.findViewById(
R.id.setting_icon);
if (iconView != null) {
iconView.setImageDrawable(setting.getIcon());
}
TextView labelView = (TextView) settingView.findViewById(
R.id.setting_label);
if (labelView != null) {
labelView.setText(setting.getLabel());
}
}
protected abstract View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting);
}
private ViewGroup mSettingsContainer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, null);
setupViews(view);
return view;
}
private void setupViews(View fragmentView) {
if (fragmentView == null) {
return;
}
mSettingsContainer = (ViewGroup) fragmentView.findViewById(R.id.settings_container);
reloadSettings();
}
protected void reloadSettings() {
mSettingsContainer.removeAllViews();
Setting[] settings = createSettings(getContext());
if (settings != null) {
for (Setting s: settings) {
addSetting(s);
}
}
}
protected abstract Setting[] createSettings(Context context);
public void addSetting(Setting setting) {
Logger.debug("add setting: %s", setting);
if (setting == null) {
return;
}
Logger.debug("mSettingsContainer = %s", mSettingsContainer);
if (mSettingsContainer == null) {
return;
}
LayoutHolder lh = setting.getLayoutHolder();
if (lh == null) {
return;
}
View view = lh.createView(getContext(), setting);
if (view == null) {
return;
}
LinearLayout.LayoutParams llp =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
Logger.debug("add settings view: %s", view);
mSettingsContainer.addView(view, llp);
}
public static void registerSettingChangesReceiver(Context context, BroadcastReceiver receiver) {
if (context == null || receiver == null) {
return;
}
IntentFilter filter = new IntentFilter(ACTION_SETTINGS_CHANGED);
try {
LocalBroadcastManager.getInstance(context)
.registerReceiver(receiver, filter);
} catch (Exception e) {
Logger.warn("could not register receiver [%s] on %s: %s",
receiver, ACTION_SETTINGS_CHANGED, e.toString());
}
}
public static void unregisterSettingChangesReceiver(Context context, BroadcastReceiver receiver) {
if (context == null || receiver == null) {
return;
}
try {
LocalBroadcastManager.getInstance(context)
.unregisterReceiver(receiver);
} catch (Exception e) {
Logger.warn("could not unregister receiver [%s] from %s: %s",
receiver, ACTION_SETTINGS_CHANGED, e.toString());
}
}
}
| [*][DEV]: new interface for notify setting change from app side;
| src/main/java/com/dailystudio/app/fragment/SettingsFragment.java | [*][DEV]: new interface for notify setting change from app side; | <ide><path>rc/main/java/com/dailystudio/app/fragment/SettingsFragment.java
<ide> }
<ide>
<ide> protected void notifySettingsChanged() {
<del> Intent i = new Intent(ACTION_SETTINGS_CHANGED);
<del>
<del> i.putExtra(EXTRA_SETTING_NAME, getName());
<del>
<del> LocalBroadcastManager.getInstance(getContext()).sendBroadcast(i);
<add> SettingsFragment.notifySettingChange(getContext(), getName());
<ide> }
<ide>
<ide> private Runnable mNotifyDataChangesRunnable = new Runnable() {
<ide> }
<ide> }
<ide>
<add> public static void notifySettingChange(Context context, String settingId) {
<add> Intent i = new Intent(ACTION_SETTINGS_CHANGED);
<add>
<add> i.putExtra(EXTRA_SETTING_NAME, settingId);
<add>
<add> LocalBroadcastManager.getInstance(context).sendBroadcast(i);
<add> }
<add>
<ide> } |
|
Java | mpl-2.0 | fb4203aa8e7db9be5b7e5cd359885202faeeede4 | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*************************************************************************
*
* $RCSfile: XOutputStreamWrapper.java,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-07-23 14:00:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package com.sun.star.script.framework.io;
import java.io.*;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.io.XStream;
import com.sun.star.util.XModifiable;
import com.sun.star.script.framework.log.*;
public class XOutputStreamWrapper extends OutputStream {
XOutputStream m_xOutputStream;
public XOutputStreamWrapper(XOutputStream xOs ) {
this.m_xOutputStream = xOs;
}
public void write(int b)
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException("Stream is null");
}
byte[] bytes = new byte[1];
bytes[0] = (byte) b;
try
{
m_xOutputStream.writeBytes( bytes );
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void write(byte[] b)
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
try
{
m_xOutputStream.writeBytes( b );
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void write( byte[] b, int off, int len )
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
byte[] bytes = new byte[len];
for ( int i=off; i< off+len; i++ )
{
bytes[i] = b[i];
}
try
{
m_xOutputStream.writeBytes(bytes);
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void flush()
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
try
{
m_xOutputStream.flush();
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void close()
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
try
{
m_xOutputStream.closeOutput();
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
}
| scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java | /*************************************************************************
*
* $RCSfile: XOutputStreamWrapper.java,v $
*
* $Revision: 1.2 $
*
* last change: $Author: svesik $ $Date: 2004-04-19 23:07:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package com.sun.star.script.framework.io;
import java.io.*;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.io.XStream;
import com.sun.star.util.XModifiable;
import com.sun.star.script.framework.log.*;
import com.sun.star.embed.XStorage;
public class XOutputStreamWrapper extends OutputStream {
XStream m_xStream;
XOutputStream m_xOutputStream;
XStorageHelper helper;
public XOutputStreamWrapper( XStorageHelper helper, String streamName, int mode ) throws java.io.IOException
{
this.helper = helper;
XStorage streamParent = helper.getStorage();
try
{
m_xStream = streamParent.openStreamElement( streamName, mode );
m_xOutputStream = m_xStream.getOutputStream();
}
catch ( Exception e )
{
try
{
helper.disposeObject();
}
catch ( Exception ignore )
{
}
throw new java.io.IOException( "Failed to open stream: " + streamName + " exceptopn: " + e.toString() );
}
}
public XOutputStreamWrapper(XOutputStream xOs ) {
this.m_xOutputStream = xOs;
}
public void write(int b)
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException("Stream is null");
}
byte[] bytes = new byte[1];
bytes[0] = (byte) b;
try
{
m_xOutputStream.writeBytes( bytes );
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void write(byte[] b)
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
try
{
m_xOutputStream.writeBytes( b );
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void write( byte[] b, int off, int len )
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
byte[] bytes = new byte[len];
for ( int i=off; i< off+len; i++ )
{
bytes[i] = b[i];
}
try
{
m_xOutputStream.writeBytes(bytes);
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void flush()
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
try
{
m_xOutputStream.flush();
}
catch ( com.sun.star.io.IOException ioe )
{
throw new java.io.IOException(ioe.getMessage());
}
}
public void close()
throws java.io.IOException
{
if ( m_xOutputStream == null )
{
throw new java.io.IOException( "Stream is null" );
}
try
{
if ( m_xStream != null )
{
XStorageHelper.disposeObject( m_xStream );
helper.disposeObject( true );
helper = null;
}
else
{
m_xOutputStream.closeOutput();
}
}
catch ( com.sun.star.io.IOException ioe )
{
LogUtils.DEBUG("XOutputstreamWrapper.close() Error disposing storage :" + ioe );
LogUtils.DEBUG( LogUtils.getTrace( ioe ) );
//throw new java.io.IOException(ioe.getMessage());
}
finally
{
if ( helper != null )
{
try
{
helper.disposeObject();
helper = null;
}
catch ( Exception e )
{
}
}
}
}
}
| INTEGRATION: CWS scriptingf7 (1.2.14); FILE MERGED
2004/06/24 12:41:06 npower 1.2.14.2: #25269# close() method doesn't call closeOutput fixing this
2004/06/12 09:01:07 npower 1.2.14.1: #i25269# changes required to support tdoc urls
Issue number:
Submitted by:
Reviewed by:
| scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java | INTEGRATION: CWS scriptingf7 (1.2.14); FILE MERGED 2004/06/24 12:41:06 npower 1.2.14.2: #25269# close() method doesn't call closeOutput fixing this 2004/06/12 09:01:07 npower 1.2.14.1: #i25269# changes required to support tdoc urls Issue number: Submitted by: Reviewed by: | <ide><path>cripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java
<ide> *
<ide> * $RCSfile: XOutputStreamWrapper.java,v $
<ide> *
<del> * $Revision: 1.2 $
<add> * $Revision: 1.3 $
<ide> *
<del> * last change: $Author: svesik $ $Date: 2004-04-19 23:07:47 $
<add> * last change: $Author: hr $ $Date: 2004-07-23 14:00:56 $
<ide> *
<ide> * The Contents of this file are made available subject to the terms of
<ide> * either of the following licenses
<ide> import com.sun.star.util.XModifiable;
<ide> import com.sun.star.script.framework.log.*;
<ide>
<del>import com.sun.star.embed.XStorage;
<ide>
<ide> public class XOutputStreamWrapper extends OutputStream {
<del> XStream m_xStream;
<ide> XOutputStream m_xOutputStream;
<del> XStorageHelper helper;
<del> public XOutputStreamWrapper( XStorageHelper helper, String streamName, int mode ) throws java.io.IOException
<del> {
<del> this.helper = helper;
<del> XStorage streamParent = helper.getStorage();
<del>
<del> try
<del> {
<del> m_xStream = streamParent.openStreamElement( streamName, mode );
<del> m_xOutputStream = m_xStream.getOutputStream();
<del> }
<del> catch ( Exception e )
<del> {
<del> try
<del> {
<del> helper.disposeObject();
<del> }
<del> catch ( Exception ignore )
<del> {
<del> }
<del> throw new java.io.IOException( "Failed to open stream: " + streamName + " exceptopn: " + e.toString() );
<del> }
<del>
<del>
<del> }
<ide> public XOutputStreamWrapper(XOutputStream xOs ) {
<ide> this.m_xOutputStream = xOs;
<ide> }
<ide> }
<ide> try
<ide> {
<del> if ( m_xStream != null )
<del> {
<del> XStorageHelper.disposeObject( m_xStream );
<del> helper.disposeObject( true );
<del> helper = null;
<del> }
<del> else
<del> {
<del> m_xOutputStream.closeOutput();
<del> }
<add> m_xOutputStream.closeOutput();
<ide> }
<ide> catch ( com.sun.star.io.IOException ioe )
<ide> {
<del> LogUtils.DEBUG("XOutputstreamWrapper.close() Error disposing storage :" + ioe );
<del> LogUtils.DEBUG( LogUtils.getTrace( ioe ) );
<del> //throw new java.io.IOException(ioe.getMessage());
<del> }
<del> finally
<del> {
<del> if ( helper != null )
<del> {
<del> try
<del> {
<del> helper.disposeObject();
<del> helper = null;
<del> }
<del> catch ( Exception e )
<del> {
<del> }
<del> }
<del>
<add> throw new java.io.IOException(ioe.getMessage());
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 8a33d4805d115c489fb914f9372e3ff36a0cbf7b | 0 | awaitility/awaitility,awaitility/awaitility,jayway/awaitility,awaitility/awaitility | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.awaitility.core;
import org.awaitility.Duration;
import org.awaitility.constraint.AtMostWaitConstraint;
import org.awaitility.constraint.WaitConstraint;
import org.awaitility.pollinterval.FixedPollInterval;
import org.awaitility.pollinterval.PollInterval;
import org.awaitility.spi.ProxyConditionFactory;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.classpath.ClassPathResolver.existInCP;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.is;
/**
* A factory for creating {@link org.awaitility.core.Condition} objects. It's not recommended to
* instantiate this class directly.
*/
public class ConditionFactory {
/**
* Timing constraint.
*/
private final WaitConstraint timeoutConstraint;
/**
* The poll interval.
*/
private final PollInterval pollInterval;
/**
* The catch uncaught exceptions.
*/
private final boolean catchUncaughtExceptions;
/**
* The ignore exceptions.
*/
private final ExceptionIgnorer exceptionsIgnorer;
/**
* The alias.
*/
private final String alias;
/**
* The poll delay.
*/
private final Duration pollDelay;
/**
* The condition evaluation listener
*/
private final ConditionEvaluationListener conditionEvaluationListener;
/**
* The executor lifecycle
*/
private final ExecutorLifecycle executorLifecycle;
/**
* Instantiates a new condition factory.
*
* @param alias the alias
* @param timeoutConstraint the timeout constraint
* @param pollInterval the poll interval
* @param pollDelay The poll delay
* @param catchUncaughtExceptions the catch uncaught exceptions
* @param exceptionsIgnorer Determine which exceptions that should ignored
* @param conditionEvaluationListener Determine which exceptions that should ignored
* @param executorLifecycle The executor service and the lifecycle of the executor service that'll be used to evaluate the condition during polling
*/
public ConditionFactory(final String alias, WaitConstraint timeoutConstraint, PollInterval pollInterval, Duration pollDelay,
boolean catchUncaughtExceptions, ExceptionIgnorer exceptionsIgnorer,
ConditionEvaluationListener conditionEvaluationListener, ExecutorLifecycle executorLifecycle) {
if (pollInterval == null) {
throw new IllegalArgumentException("pollInterval cannot be null");
}
if (timeoutConstraint == null) {
throw new IllegalArgumentException("timeout cannot be null");
}
this.alias = alias;
this.timeoutConstraint = timeoutConstraint;
this.pollInterval = pollInterval;
this.catchUncaughtExceptions = catchUncaughtExceptions;
this.pollDelay = pollDelay;
this.conditionEvaluationListener = conditionEvaluationListener;
this.exceptionsIgnorer = exceptionsIgnorer;
this.executorLifecycle = executorLifecycle;
}
/**
* Handle condition evaluation results each time evaluation of a condition occurs. Works only with a Hamcrest matcher-based condition.
*
* @param conditionEvaluationListener the condition evaluation listener
* @return the condition factory
*/
public ConditionFactory conditionEvaluationListener(ConditionEvaluationListener conditionEvaluationListener) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @return the condition factory
*/
public ConditionFactory timeout(Duration timeout) {
return atMost(timeout);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @return the condition factory
*/
public ConditionFactory atMost(Duration timeout) {
return new ConditionFactory(alias, timeoutConstraint.withMaxWaitTime(timeout), pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Set the alias
*
* @param alias alias
* @return the condition factory
* @see org.awaitility.Awaitility#await(String)
*/
public ConditionFactory alias(String alias) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Condition has to be evaluated not earlier than <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @return the condition factory
*/
public ConditionFactory atLeast(Duration timeout) {
return new ConditionFactory(alias, timeoutConstraint.withMinWaitTime(timeout), pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Condition has to be evaluated not earlier than <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory atLeast(long timeout, TimeUnit unit) {
return atLeast(new Duration(timeout, unit));
}
/**
* Specifies the duration window which has to be satisfied during operation execution. In case operation is executed
* before <code>atLeast</code> or after <code>atMost</code> timeout exception is thrown.
*
* @param atLeast lower part of execution window
* @param atMost upper part of execution window
* @return the condition factory
*/
public ConditionFactory between(Duration atLeast, Duration atMost) {
return atLeast(atLeast).and().atMost(atMost);
}
/**
* Specifies the duration window which has to be satisfied during operation execution. In case operation is executed
* before <code>atLeastDuration</code> or after <code>atMostDuration</code> timeout exception is thrown.
*
* @param atLeastDuration lower part of execution window
* @param atMostDuration upper part of execution window
* @return the condition factory
*/
public ConditionFactory between(long atLeastDuration, TimeUnit atLeastTimeUnit, long atMostDuration, TimeUnit atMostTimeUnit) {
return between(new Duration(atLeastDuration, atLeastTimeUnit), new Duration(atMostDuration, atMostTimeUnit));
}
/**
* Await forever until the condition is satisfied. Caution: You can block
* subsequent tests and the entire build can hang indefinitely, it's
* recommended to always use a timeout.
*
* @return the condition factory
*/
public ConditionFactory forever() {
return new ConditionFactory(alias, AtMostWaitConstraint.FOREVER, pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Specify the polling interval Awaitility will use for this await
* statement. This means the frequency in which the condition is checked for
* completion.
* <p>
* Note that the poll delay will be automatically set as to the same value
* as the interval (if using a {@link FixedPollInterval}) unless it's specified explicitly using
* {@link #pollDelay(Duration)}, {@link #pollDelay(long, TimeUnit)} or
* {@link org.awaitility.core.ConditionFactory#pollDelay(org.awaitility.Duration)}.
* </p>
*
* @param pollInterval the poll interval
* @return the condition factory
*/
public ConditionFactory pollInterval(Duration pollInterval) {
return new ConditionFactory(alias, timeoutConstraint, new FixedPollInterval(pollInterval), pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory timeout(long timeout, TimeUnit unit) {
return atMost(timeout, unit);
}
/**
* Specify the delay that will be used before Awaitility starts polling for
* the result the first time. If you don't specify a poll delay explicitly
* it'll be the same as the poll interval.
*
* @param delay the delay
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory pollDelay(long delay, TimeUnit unit) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, new Duration(delay, unit),
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Specify the delay that will be used before Awaitility starts polling for
* the result the first time. If you don't specify a poll delay explicitly
* it'll be the same as the poll interval.
*
* @param pollDelay the poll delay
* @return the condition factory
*/
public ConditionFactory pollDelay(Duration pollDelay) {
if (pollDelay == null) {
throw new IllegalArgumentException("pollDelay cannot be null");
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory atMost(long timeout, TimeUnit unit) {
return atMost(new Duration(timeout, unit));
}
/**
* Specify the polling interval Awaitility will use for this await
* statement. This means the frequency in which the condition is checked for
* completion.
* <p> </p>
* Note that the poll delay will be automatically set as to the same value
* as the interval unless it's specified explicitly using
* {@link #pollDelay(Duration)}, {@link #pollDelay(long, TimeUnit)} or
* {@link org.awaitility.core.ConditionFactory#pollDelay(org.awaitility.Duration)} , or
* ConditionFactory#andWithPollDelay(long, TimeUnit)}. This is the same as creating a {@link FixedPollInterval}.
*
* @param pollInterval the poll interval
* @param unit the unit
* @return the condition factory
* @see FixedPollInterval
*/
public ConditionFactory pollInterval(long pollInterval, TimeUnit unit) {
PollInterval fixedPollInterval = new FixedPollInterval(new Duration(pollInterval, unit));
return new ConditionFactory(alias, timeoutConstraint, fixedPollInterval, definePollDelay(pollDelay, fixedPollInterval),
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
public ConditionFactory pollInterval(PollInterval pollInterval) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, definePollDelay(pollDelay, pollInterval), catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to catch uncaught exceptions from other threads. This
* is useful in multi-threaded systems when you want your test to fail
* regardless of which thread throwing the exception. Default is
* <code>true</code>.
*
* @return the condition factory
*/
public ConditionFactory catchUncaughtExceptions() {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, true, exceptionsIgnorer,
conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore exceptions instance of the supplied exceptionType type.
* Exceptions will be treated as evaluating to <code>false</code>.
* This is useful in situations where the evaluated conditions may temporarily throw exceptions.
* <p/>
* <p>If you want to ignore a specific exceptionType then use {@link #ignoreException(Class)}</p>
*
* @param exceptionType The exception type (hierarchy) to ignore
* @return the condition factory
*/
public ConditionFactory ignoreExceptionsInstanceOf(final Class<? extends Throwable> exceptionType) {
if (exceptionType == null) {
throw new IllegalArgumentException("exceptionType cannot be null");
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new PredicateExceptionIgnorer(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return exceptionType.isAssignableFrom(e.getClass());
}
}),
conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore a specific exception and <i>no</i> subclasses of this exception.
* Exceptions will be treated as evaluating to <code>false</code>.
* This is useful in situations where the evaluated conditions may temporarily throw exceptions.
* <p>If you want to ignore a subtypes of this exception then use {@link #ignoreExceptionsInstanceOf(Class)}} </p>
*
* @param exceptionType The exception type to ignore
* @return the condition factory
*/
public ConditionFactory ignoreException(final Class<? extends Throwable> exceptionType) {
if (exceptionType == null) {
throw new IllegalArgumentException("exception cannot be null");
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new PredicateExceptionIgnorer(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return e.getClass().equals(exceptionType);
}
}),
conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore <i>all</i> exceptions that occur during evaluation.
* Exceptions will be treated as evaluating to
* <code>false</code>. This is useful in situations where the evaluated
* conditions may temporarily throw exceptions.
*
* @return the condition factory.
*/
public ConditionFactory ignoreExceptions() {
return ignoreExceptionsMatching(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return true;
}
});
}
/**
* Instruct Awaitility to not ignore any exceptions that occur during evaluation.
* This is only useful if Awaitility is configured to ignore exceptions by default but you want to
* have a different behavior for a single test case.
*
* @return the condition factory.
*/
public ConditionFactory ignoreNoExceptions() {
return ignoreExceptionsMatching(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return false;
}
});
}
/**
* Instruct Awaitility to ignore exceptions that occur during evaluation and matches the supplied Hamcrest matcher.
* Exceptions will be treated as evaluating to
* <code>false</code>. This is useful in situations where the evaluated conditions may temporarily throw exceptions.
*
* @return the condition factory.
*/
public ConditionFactory ignoreExceptionsMatching(Matcher<? super Throwable> matcher) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new HamcrestExceptionIgnorer(matcher), conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore exceptions that occur during evaluation and matches the supplied <code>predicate</code>.
* Exceptions will be treated as evaluating to
* <code>false</code>. This is useful in situations where the evaluated conditions may temporarily throw exceptions.
*
* @return the condition factory.
*/
public ConditionFactory ignoreExceptionsMatching(Predicate<? super Throwable> predicate) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new PredicateExceptionIgnorer(predicate), conditionEvaluationListener, executorLifecycle);
}
/**
* Await for an asynchronous operation. This method returns the same
* {@link org.awaitility.core.ConditionFactory} instance and is used only to get a more
* fluent-like syntax.
*
* @return the condition factory
*/
public ConditionFactory await() {
return this;
}
/**
* Await for an asynchronous operation and give this await instance a
* particular name. This is useful in cases when you have several await
* statements in one test and you want to know which one that fails (the
* alias will be shown if a timeout exception occurs).
*
* @param alias the alias
* @return the condition factory
*/
public ConditionFactory await(String alias) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory and() {
return this;
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory with() {
return this;
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory then() {
return this;
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory given() {
return this;
}
/**
* Don't catch uncaught exceptions in other threads. This will <i>not</i>
* make the await statement fail if exceptions occur in other threads.
*
* @return the condition factory
*/
public ConditionFactory dontCatchUncaughtExceptions() {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Specify the executor service whose threads will be used to evaluate the poll condition in Awaitility.
* Note that the executor service must be shutdown manually!
*
* This is an advanced feature and it should only be used sparingly.
*
* @param executorService The executor service that Awaitility will use when polling condition evaluations
* @return the condition factory
*/
public ConditionFactory pollExecutorService(ExecutorService executorService) {
if (executorService != null && executorService instanceof ScheduledExecutorService) {
throw new IllegalArgumentException("Poll executor service cannot be an instance of " + ScheduledExecutorService.class.getName());
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withoutCleanup(executorService));
}
/**
* Specify a thread supplier whose thread will be used to evaluate the poll condition in Awaitility.
* The supplier will be called only once and the thread it returns will be reused during all condition evaluations.
* This is an advanced feature and it should only be used sparingly.
*
* @param threadSupplier A supplier of the thread that Awaitility will use when polling
* @return the condition factory
*/
public ConditionFactory pollThread(final Function<Runnable, Thread> threadSupplier) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withNormalCleanupBehavior(new Supplier<ExecutorService>() {
@Override
public ExecutorService get() {
return InternalExecutorServiceFactory.create(threadSupplier);
}
}));
}
/**
* Instructs Awaitility to execute the polling of the condition from the same as the test.
* This is an advanced feature and you should be careful when combining this with conditions that
* wait forever (or a long time) since Awaitility cannot interrupt the thread when it's using the same
* thread as the test. For safety you should always combine tests using this feature with a test framework specific timeout,
* for example in JUnit:
*<pre>
* @Test(timeout = 2000L)
* public void myTest() {
* Awaitility.pollInSameThread();
* await().forever().until(...);
* }
*</pre>
* @return the condition factory
*/
public ConditionFactory pollInSameThread() {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withNormalCleanupBehavior(new Supplier<ExecutorService>() {
@Override
public ExecutorService get() {
return InternalExecutorServiceFactory.sameThreadExecutorService();
}
}));
}
/**
* Specify the condition that must be met when waiting for a method call.
* E.g.
* <p> </p>
* <pre>
* await().untilCall(to(orderService).size(), is(greaterThan(2)));
* </pre>
*
* @param <T> the generic type
* @param proxyMethodReturnValue the return value of the method call
* @param matcher The condition that must be met when
* @return a T object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public <T> T untilCall(T proxyMethodReturnValue, final Matcher<? super T> matcher) {
if (!existInCP("java.util.ServiceLoader")) {
throw new UnsupportedOperationException("java.util.ServiceLoader not found in classpath so cannot create condition");
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
Iterator<ProxyConditionFactory> iterator = java.util.ServiceLoader.load(ProxyConditionFactory.class, cl).iterator();
if (!iterator.hasNext()) {
throw new UnsupportedOperationException("There's currently no plugin installed that can handle proxy conditions, please consider adding 'awaitility-proxy' to the classpath. If using Maven you can do:" +
"<dependency>\n" +
"\t<groupId>org.awaitility</groupId>\n" +
"\t<artifactId>awaitility-proxy</artifactId>\n" +
"\t<version>${awaitility.version}</version>\n" +
"</dependency>\n");
}
@SuppressWarnings("unchecked") ProxyConditionFactory<T> factory = iterator.next();
if (factory == null) {
throw new IllegalArgumentException("Internal error: Proxy condition plugin initialization returned null, please report an issue.");
}
return until(factory.createProxyCondition(proxyMethodReturnValue, matcher, generateConditionSettings()));
}
/**
* Await until a {@link java.util.concurrent.Callable} supplies a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().until(numberOfPersons(), is(greaterThan(2)));
* </pre>
* <p> </p>
* where "numberOfPersons()" returns a standard {@link java.util.concurrent.Callable}:
* <p> </p>
* <pre>
* private Callable<Integer> numberOfPersons() {
* return new Callable<Integer>() {
* public Integer call() {
* return personRepository.size();
* }
* };
* }
* </pre>
* <p> </p>
* Using a generic {@link java.util.concurrent.Callable} as done by using this version of "until"
* allows you to reuse the "numberOfPersons()" definition in multiple await
* statements. I.e. you can easily create another await statement (perhaps
* in a different test case) using e.g.
* <p> </p>
* <pre>
* await().until(numberOfPersons(), is(equalTo(6)));
* </pre>
*
* @param <T> the generic type
* @param supplier the supplier that is responsible for getting the value that
* should be matched.
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @return a T object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public <T> T until(final Callable<T> supplier, final Matcher<? super T> matcher) {
return until(new CallableHamcrestCondition<T>(supplier, matcher, generateConditionSettings()));
}
/**
* Wait until the given supplier matches the supplied predicate. For example:
*
* <pre>
* await().until(myRepository::count, cnt -> cnt == 2);
* </pre>
*
* @param supplier The supplier that returns the object that will be evaluated by the predicate.
* @param predicate The predicate that must match
* @param <T> the generic type
* @since 3.1.1
* @return a T object.
*/
public <T> T until(final Callable<T> supplier, final Predicate<? super T> predicate) {
return until(supplier, new TypeSafeMatcher<T>() {
@Override
protected void describeMismatchSafely(T item, Description description) {
description.appendText("it returned <false> for input of ").appendValue(item);
}
@Override
public void describeTo(Description description) {
description.appendText("the predicate to return <true>");
}
@Override
protected boolean matchesSafely(T item) {
return predicate.matches(item);
}
});
}
/**
* Await until a {@link java.lang.Runnable} supplier execution passes (ends without throwing an exception). E.g. with Java 8:
* <p> </p>
* <pre>
* await().untilAsserted(() -> Assertions.assertThat(personRepository.size()).isEqualTo(6));
* </pre>
* or
* <pre>
* await().untilAsserted(() -> assertEquals(6, personRepository.size()));
* </pre>
* <p> </p>
* This method is intended to benefit from lambda expressions introduced in Java 8. It allows to use standard AssertJ/FEST Assert assertions
* (by the way also standard JUnit/TestNG assertions) to test asynchronous calls and systems.
* <p> </p>
* {@link java.lang.AssertionError} instances thrown by the supplier are treated as an assertion failure and proper error message is propagated on timeout.
* Other exceptions are rethrown immediately as an execution errors.
* <p> </p>
* While technically it is completely valid to use plain Runnable class in Java 7 code, the resulting expression is very verbose and can decrease
* the readability of the test case, e.g.
* <p> </p>
* <pre>
* await().untilAsserted(new Runnable() {
* public void run() {
* Assertions.assertThat(personRepository.size()).isEqualTo(6);
* }
* });
* </pre>
* <p> </p>
* <b>NOTE:</b><br>
* Be <i>VERY</i> careful so that you're not using this method incorrectly in languages (like Kotlin and Groovy) that doesn't
* disambiguate between a {@link ThrowingRunnable} that doesn't return anything (void) and {@link Callable} that returns a value.
* For example in Kotlin you can do like this:
* <p> </p>
* <pre>
* await().untilAsserted { true == false }
* </pre>
* and the compiler won't complain with an error (as is the case in Java). If you were to execute this test in Kotlin it'll pass!
*
* @param assertion the supplier that is responsible for executing the assertion and throwing AssertionError on failure.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
* @since 1.6.0
*/
public void untilAsserted(final ThrowingRunnable assertion) {
until(new AssertionCondition(assertion, generateConditionSettings()));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @return a {@link java.lang.Integer} object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public Integer untilAtomic(final AtomicInteger atomic, final Matcher<? super Integer> matcher) {
return until(new CallableHamcrestCondition<Integer>(new Callable<Integer>() {
public Integer call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @return a {@link java.lang.Long} object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public Long untilAtomic(final AtomicLong atomic, final Matcher<? super Long> matcher) {
return until(new CallableHamcrestCondition<Long>(new Callable<Long>() {
public Long call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void untilAtomic(final AtomicBoolean atomic, final Matcher<? super Boolean> matcher) {
until(new CallableHamcrestCondition<Boolean>(new Callable<Boolean>() {
public Boolean call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a Atomic boolean becomes true.
*
* @param atomic the atomic variable
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void untilTrue(final AtomicBoolean atomic) {
untilAtomic(atomic, anyOf(is(Boolean.TRUE), is(true)));
}
/**
* Await until a Atomic boolean becomes false.
*
* @param atomic the atomic variable
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void untilFalse(final AtomicBoolean atomic) {
untilAtomic(atomic, anyOf(is(Boolean.FALSE), is(false)));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @param <V> a V object.
* @return a V object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public <V> V untilAtomic(final AtomicReference<V> atomic, final Matcher<? super V> matcher) {
return until(new CallableHamcrestCondition<V>(new Callable<V>() {
public V call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a {@link java.util.concurrent.Callable} returns <code>true</code>. This is method
* is not as generic as the other variants of "until" but it allows for a
* more precise and in some cases even more english-like syntax. E.g.
* <p> </p>
* <pre>
* await().until(numberOfPersonsIsEqualToThree());
* </pre>
* <p> </p>
* where "numberOfPersonsIsEqualToThree()" returns a standard
* {@link java.util.concurrent.Callable} of type {@link java.lang.Boolean}:
* <p> </p>
* <pre>
* private Callable<Boolean> numberOfPersons() {
* return new Callable<Boolean>() {
* public Boolean call() {
* return personRepository.size() == 3;
* }
* };
* }
* </pre>
*
* @param conditionEvaluator the condition evaluator
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void until(Callable<Boolean> conditionEvaluator) {
until(new CallableCondition(conditionEvaluator, generateConditionSettings()));
}
private ConditionSettings generateConditionSettings() {
Duration actualPollDelay = definePollDelay(pollDelay, pollInterval);
if (actualPollDelay.isForever()) {
throw new IllegalArgumentException("Cannot delay polling forever");
}
Duration timeout = timeoutConstraint.getMaxWaitTime();
final long timeoutInMS = timeout.getValueInMS();
if (!timeout.isForever() && timeoutInMS <= actualPollDelay.getValueInMS()) {
throw new IllegalStateException(String.format("Timeout (%s %s) must be greater than the poll delay (%s %s).",
timeout.getValue(), timeout.getTimeUnitAsString(), actualPollDelay.getValue(), actualPollDelay.getTimeUnitAsString()));
} else if ((!actualPollDelay.isForever() && !timeout.isForever()) && timeoutInMS <= actualPollDelay.getValueInMS()) {
throw new IllegalStateException(String.format("Timeout (%s %s) must be greater than the poll delay (%s %s).",
timeout.getValue(), timeout.getTimeUnitAsString(), actualPollDelay.getValue(), actualPollDelay.getTimeUnitAsString()));
}
ExecutorLifecycle executorLifecycle;
if (this.executorLifecycle == null) {
executorLifecycle = ExecutorLifecycle.withNormalCleanupBehavior(new Supplier<ExecutorService>() {
@Override
public ExecutorService get() {
return InternalExecutorServiceFactory.create(new BiFunction<Runnable, String, Thread>() {
@Override
public Thread apply(Runnable r, String threadName) {
return new Thread(Thread.currentThread().getThreadGroup(), r, threadName);
}
}, alias);
}
});
} else {
executorLifecycle = this.executorLifecycle;
}
return new ConditionSettings(alias, catchUncaughtExceptions, timeoutConstraint, pollInterval, actualPollDelay,
conditionEvaluationListener, exceptionsIgnorer, executorLifecycle);
}
private <T> T until(Condition<T> condition) {
return condition.await();
}
/**
* Ensures backward compatibility (especially that poll delay is the same as poll interval for fixed poll interval).
* It also make sure that poll delay is {@link Duration#ZERO} for all other poll intervals if poll delay was not explicitly
* defined. If poll delay was explicitly defined the it will just be returned.
*
* @param pollDelay The poll delay
* @param pollInterval The chosen (or default) poll interval
* @return The poll delay to use
*/
private Duration definePollDelay(Duration pollDelay, PollInterval pollInterval) {
final Duration pollDelayToUse;
// If a poll delay is null then a poll delay has not been explicitly defined by the user
if (pollDelay == null) {
if (pollInterval != null && pollInterval instanceof FixedPollInterval) {
pollDelayToUse = pollInterval.next(1, Duration.ZERO); // Will return same poll delay as poll interval
} else {
pollDelayToUse = Duration.ZERO; // Default poll delay for non-fixed poll intervals
}
} else {
// Poll delay was explicitly defined, use it!
pollDelayToUse = pollDelay;
}
return pollDelayToUse;
}
}
| awaitility/src/main/java/org/awaitility/core/ConditionFactory.java | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.awaitility.core;
import org.awaitility.Duration;
import org.awaitility.constraint.AtMostWaitConstraint;
import org.awaitility.constraint.WaitConstraint;
import org.awaitility.pollinterval.FixedPollInterval;
import org.awaitility.pollinterval.PollInterval;
import org.awaitility.spi.ProxyConditionFactory;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.classpath.ClassPathResolver.existInCP;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.is;
/**
* A factory for creating {@link org.awaitility.core.Condition} objects. It's not recommended to
* instantiate this class directly.
*/
public class ConditionFactory {
/**
* Timing constraint.
*/
private final WaitConstraint timeoutConstraint;
/**
* The poll interval.
*/
private final PollInterval pollInterval;
/**
* The catch uncaught exceptions.
*/
private final boolean catchUncaughtExceptions;
/**
* The ignore exceptions.
*/
private final ExceptionIgnorer exceptionsIgnorer;
/**
* The alias.
*/
private final String alias;
/**
* The poll delay.
*/
private final Duration pollDelay;
/**
* The condition evaluation listener
*/
private final ConditionEvaluationListener conditionEvaluationListener;
/**
* The executor lifecycle
*/
private final ExecutorLifecycle executorLifecycle;
/**
* Instantiates a new condition factory.
*
* @param alias the alias
* @param timeoutConstraint the timeout constraint
* @param pollInterval the poll interval
* @param pollDelay The poll delay
* @param catchUncaughtExceptions the catch uncaught exceptions
* @param exceptionsIgnorer Determine which exceptions that should ignored
* @param conditionEvaluationListener Determine which exceptions that should ignored
* @param executorLifecycle The executor service and the lifecycle of the executor service that'll be used to evaluate the condition during polling
*/
public ConditionFactory(final String alias, WaitConstraint timeoutConstraint, PollInterval pollInterval, Duration pollDelay,
boolean catchUncaughtExceptions, ExceptionIgnorer exceptionsIgnorer,
ConditionEvaluationListener conditionEvaluationListener, ExecutorLifecycle executorLifecycle) {
if (pollInterval == null) {
throw new IllegalArgumentException("pollInterval cannot be null");
}
if (timeoutConstraint == null) {
throw new IllegalArgumentException("timeout cannot be null");
}
this.alias = alias;
this.timeoutConstraint = timeoutConstraint;
this.pollInterval = pollInterval;
this.catchUncaughtExceptions = catchUncaughtExceptions;
this.pollDelay = pollDelay;
this.conditionEvaluationListener = conditionEvaluationListener;
this.exceptionsIgnorer = exceptionsIgnorer;
this.executorLifecycle = executorLifecycle;
}
/**
* Handle condition evaluation results each time evaluation of a condition occurs. Works only with a Hamcrest matcher-based condition.
*
* @param conditionEvaluationListener the condition evaluation listener
* @return the condition factory
*/
public ConditionFactory conditionEvaluationListener(ConditionEvaluationListener conditionEvaluationListener) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @return the condition factory
*/
public ConditionFactory timeout(Duration timeout) {
return atMost(timeout);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @return the condition factory
*/
public ConditionFactory atMost(Duration timeout) {
return new ConditionFactory(alias, timeoutConstraint.withMaxWaitTime(timeout), pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Set the alias
*
* @param alias alias
* @return the condition factory
* @see org.awaitility.Awaitility#await(String)
*/
public ConditionFactory alias(String alias) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Condition has to be evaluated not earlier than <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @return the condition factory
*/
public ConditionFactory atLeast(Duration timeout) {
return new ConditionFactory(alias, timeoutConstraint.withMinWaitTime(timeout), pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Condition has to be evaluated not earlier than <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory atLeast(long timeout, TimeUnit unit) {
return atLeast(new Duration(timeout, unit));
}
/**
* Specifies the duration window which has to be satisfied during operation execution. In case operation is executed
* before <code>atLeast</code> or after <code>atMost</code> timeout exception is thrown.
*
* @param atLeast lower part of execution window
* @param atMost upper part of execution window
* @return the condition factory
*/
public ConditionFactory between(Duration atLeast, Duration atMost) {
return atLeast(atLeast).and().atMost(atMost);
}
/**
* Specifies the duration window which has to be satisfied during operation execution. In case operation is executed
* before <code>atLeastDuration</code> or after <code>atMostDuration</code> timeout exception is thrown.
*
* @param atLeastDuration lower part of execution window
* @param atMostDuration upper part of execution window
* @return the condition factory
*/
public ConditionFactory between(long atLeastDuration, TimeUnit atLeastTimeUnit, long atMostDuration, TimeUnit atMostTimeUnit) {
return between(new Duration(atLeastDuration, atLeastTimeUnit), new Duration(atMostDuration, atMostTimeUnit));
}
/**
* Await forever until the condition is satisfied. Caution: You can block
* subsequent tests and the entire build can hang indefinitely, it's
* recommended to always use a timeout.
*
* @return the condition factory
*/
public ConditionFactory forever() {
return new ConditionFactory(alias, AtMostWaitConstraint.FOREVER, pollInterval, pollDelay,
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Specify the polling interval Awaitility will use for this await
* statement. This means the frequency in which the condition is checked for
* completion.
* <p>
* Note that the poll delay will be automatically set as to the same value
* as the interval (if using a {@link FixedPollInterval}) unless it's specified explicitly using
* {@link #pollDelay(Duration)}, {@link #pollDelay(long, TimeUnit)} or
* {@link org.awaitility.core.ConditionFactory#pollDelay(org.awaitility.Duration)}.
* </p>
*
* @param pollInterval the poll interval
* @return the condition factory
*/
public ConditionFactory pollInterval(Duration pollInterval) {
return new ConditionFactory(alias, timeoutConstraint, new FixedPollInterval(pollInterval), pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory timeout(long timeout, TimeUnit unit) {
return atMost(timeout, unit);
}
/**
* Specify the delay that will be used before Awaitility starts polling for
* the result the first time. If you don't specify a poll delay explicitly
* it'll be the same as the poll interval.
*
* @param delay the delay
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory pollDelay(long delay, TimeUnit unit) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, new Duration(delay, unit),
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Specify the delay that will be used before Awaitility starts polling for
* the result the first time. If you don't specify a poll delay explicitly
* it'll be the same as the poll interval.
*
* @param pollDelay the poll delay
* @return the condition factory
*/
public ConditionFactory pollDelay(Duration pollDelay) {
if (pollDelay == null) {
throw new IllegalArgumentException("pollDelay cannot be null");
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Await at most <code>timeout</code> before throwing a timeout exception.
*
* @param timeout the timeout
* @param unit the unit
* @return the condition factory
*/
public ConditionFactory atMost(long timeout, TimeUnit unit) {
return atMost(new Duration(timeout, unit));
}
/**
* Specify the polling interval Awaitility will use for this await
* statement. This means the frequency in which the condition is checked for
* completion.
* <p> </p>
* Note that the poll delay will be automatically set as to the same value
* as the interval unless it's specified explicitly using
* {@link #pollDelay(Duration)}, {@link #pollDelay(long, TimeUnit)} or
* {@link org.awaitility.core.ConditionFactory#pollDelay(org.awaitility.Duration)} , or
* ConditionFactory#andWithPollDelay(long, TimeUnit)}. This is the same as creating a {@link FixedPollInterval}.
*
* @param pollInterval the poll interval
* @param unit the unit
* @return the condition factory
* @see FixedPollInterval
*/
public ConditionFactory pollInterval(long pollInterval, TimeUnit unit) {
PollInterval fixedPollInterval = new FixedPollInterval(new Duration(pollInterval, unit));
return new ConditionFactory(alias, timeoutConstraint, fixedPollInterval, definePollDelay(pollDelay, fixedPollInterval),
catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
public ConditionFactory pollInterval(PollInterval pollInterval) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, definePollDelay(pollDelay, pollInterval), catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to catch uncaught exceptions from other threads. This
* is useful in multi-threaded systems when you want your test to fail
* regardless of which thread throwing the exception. Default is
* <code>true</code>.
*
* @return the condition factory
*/
public ConditionFactory catchUncaughtExceptions() {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, true, exceptionsIgnorer,
conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore exceptions instance of the supplied exceptionType type.
* Exceptions will be treated as evaluating to <code>false</code>.
* This is useful in situations where the evaluated conditions may temporarily throw exceptions.
* <p/>
* <p>If you want to ignore a specific exceptionType then use {@link #ignoreException(Class)}</p>
*
* @param exceptionType The exception type (hierarchy) to ignore
* @return the condition factory
*/
public ConditionFactory ignoreExceptionsInstanceOf(final Class<? extends Throwable> exceptionType) {
if (exceptionType == null) {
throw new IllegalArgumentException("exceptionType cannot be null");
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new PredicateExceptionIgnorer(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return exceptionType.isAssignableFrom(e.getClass());
}
}),
conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore a specific exception and <i>no</i> subclasses of this exception.
* Exceptions will be treated as evaluating to <code>false</code>.
* This is useful in situations where the evaluated conditions may temporarily throw exceptions.
* <p>If you want to ignore a subtypes of this exception then use {@link #ignoreExceptionsInstanceOf(Class)}} </p>
*
* @param exceptionType The exception type to ignore
* @return the condition factory
*/
public ConditionFactory ignoreException(final Class<? extends Throwable> exceptionType) {
if (exceptionType == null) {
throw new IllegalArgumentException("exception cannot be null");
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new PredicateExceptionIgnorer(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return e.getClass().equals(exceptionType);
}
}),
conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore <i>all</i> exceptions that occur during evaluation.
* Exceptions will be treated as evaluating to
* <code>false</code>. This is useful in situations where the evaluated
* conditions may temporarily throw exceptions.
*
* @return the condition factory.
*/
public ConditionFactory ignoreExceptions() {
return ignoreExceptionsMatching(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return true;
}
});
}
/**
* Instruct Awaitility to not ignore any exceptions that occur during evaluation.
* This is only useful if Awaitility is configured to ignore exceptions by default but you want to
* have a different behavior for a single test case.
*
* @return the condition factory.
*/
public ConditionFactory ignoreNoExceptions() {
return ignoreExceptionsMatching(new Predicate<Throwable>() {
public boolean matches(Throwable e) {
return false;
}
});
}
/**
* Instruct Awaitility to ignore exceptions that occur during evaluation and matches the supplied Hamcrest matcher.
* Exceptions will be treated as evaluating to
* <code>false</code>. This is useful in situations where the evaluated conditions may temporarily throw exceptions.
*
* @return the condition factory.
*/
public ConditionFactory ignoreExceptionsMatching(Matcher<? super Throwable> matcher) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new HamcrestExceptionIgnorer(matcher), conditionEvaluationListener, executorLifecycle);
}
/**
* Instruct Awaitility to ignore exceptions that occur during evaluation and matches the supplied <code>predicate</code>.
* Exceptions will be treated as evaluating to
* <code>false</code>. This is useful in situations where the evaluated conditions may temporarily throw exceptions.
*
* @return the condition factory.
*/
public ConditionFactory ignoreExceptionsMatching(Predicate<? super Throwable> predicate) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
new PredicateExceptionIgnorer(predicate), conditionEvaluationListener, executorLifecycle);
}
/**
* Await for an asynchronous operation. This method returns the same
* {@link org.awaitility.core.ConditionFactory} instance and is used only to get a more
* fluent-like syntax.
*
* @return the condition factory
*/
public ConditionFactory await() {
return this;
}
/**
* Await for an asynchronous operation and give this await instance a
* particular name. This is useful in cases when you have several await
* statements in one test and you want to know which one that fails (the
* alias will be shown if a timeout exception occurs).
*
* @param alias the alias
* @return the condition factory
*/
public ConditionFactory await(String alias) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory and() {
return this;
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory with() {
return this;
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory then() {
return this;
}
/**
* A method to increase the readability of the Awaitility DSL. It simply
* returns the same condition factory instance.
*
* @return the condition factory
*/
public ConditionFactory given() {
return this;
}
/**
* Don't catch uncaught exceptions in other threads. This will <i>not</i>
* make the await statement fail if exceptions occur in other threads.
*
* @return the condition factory
*/
public ConditionFactory dontCatchUncaughtExceptions() {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
}
/**
* Specify the executor service whose threads will be used to evaluate the poll condition in Awaitility.
* Note that the executor service must be shutdown manually!
*
* This is an advanced feature and it should only be used sparingly.
*
* @param executorService The executor service that Awaitility will use when polling condition evaluations
* @return the condition factory
*/
public ConditionFactory pollExecutorService(ExecutorService executorService) {
if (executorService != null && executorService instanceof ScheduledExecutorService) {
throw new IllegalArgumentException("Poll executor service cannot be an instance of " + ScheduledExecutorService.class.getName());
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withoutCleanup(executorService));
}
/**
* Specify a thread supplier whose thread will be used to evaluate the poll condition in Awaitility.
* The supplier will be called only once and the thread it returns will be reused during all condition evaluations.
* This is an advanced feature and it should only be used sparingly.
*
* @param threadSupplier A supplier of the thread that Awaitility will use when polling
* @return the condition factory
*/
public ConditionFactory pollThread(final Function<Runnable, Thread> threadSupplier) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withNormalCleanupBehavior(new Supplier<ExecutorService>() {
@Override
public ExecutorService get() {
return InternalExecutorServiceFactory.create(threadSupplier);
}
}));
}
/**
* Instructs Awaitility to execute the polling of the condition from the same as the test.
* This is an advanced feature and you should be careful when combining this with conditions that
* wait forever (or a long time) since Awaitility cannot interrupt the thread when it's using the same
* thread as the test. For safety you should always combine tests using this feature with a test framework specific timeout,
* for example in JUnit:
*<pre>
* @Test(timeout = 2000L)
* public void myTest() {
* Awaitility.pollInSameThread();
* await().forever().until(...);
* }
*</pre>
* @return the condition factory
*/
public ConditionFactory pollInSameThread() {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withNormalCleanupBehavior(new Supplier<ExecutorService>() {
@Override
public ExecutorService get() {
return InternalExecutorServiceFactory.sameThreadExecutorService();
}
}));
}
/**
* Specify the condition that must be met when waiting for a method call.
* E.g.
* <p> </p>
* <pre>
* await().untilCall(to(orderService).size(), is(greaterThan(2)));
* </pre>
*
* @param <T> the generic type
* @param proxyMethodReturnValue the return value of the method call
* @param matcher The condition that must be met when
* @return a T object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public <T> T untilCall(T proxyMethodReturnValue, final Matcher<? super T> matcher) {
if (!existInCP("java.util.ServiceLoader")) {
throw new UnsupportedOperationException("java.util.ServiceLoader not found in classpath so cannot create condition");
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
Iterator<ProxyConditionFactory> iterator = java.util.ServiceLoader.load(ProxyConditionFactory.class, cl).iterator();
if (!iterator.hasNext()) {
throw new UnsupportedOperationException("There's currently no plugin installed that can handle proxy conditions, please consider adding 'awaitility-proxy' to the classpath. If using Maven you can do:" +
"<dependency>\n" +
"\t<groupId>org.awaitility</groupId>\n" +
"\t<artifactId>awaitility-proxy</artifactId>\n" +
"\t<version>${awaitility.version}</version>\n" +
"</dependency>\n");
}
@SuppressWarnings("unchecked") ProxyConditionFactory<T> factory = iterator.next();
if (factory == null) {
throw new IllegalArgumentException("Internal error: Proxy condition plugin initialization returned null, please report an issue.");
}
return until(factory.createProxyCondition(proxyMethodReturnValue, matcher, generateConditionSettings()));
}
/**
* Await until a {@link java.util.concurrent.Callable} supplies a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().until(numberOfPersons(), is(greaterThan(2)));
* </pre>
* <p> </p>
* where "numberOfPersons()" returns a standard {@link java.util.concurrent.Callable}:
* <p> </p>
* <pre>
* private Callable<Integer> numberOfPersons() {
* return new Callable<Integer>() {
* public Integer call() {
* return personRepository.size();
* }
* };
* }
* </pre>
* <p> </p>
* Using a generic {@link java.util.concurrent.Callable} as done by using this version of "until"
* allows you to reuse the "numberOfPersons()" definition in multiple await
* statements. I.e. you can easily create another await statement (perhaps
* in a different test case) using e.g.
* <p> </p>
* <pre>
* await().until(numberOfPersons(), is(equalTo(6)));
* </pre>
*
* @param <T> the generic type
* @param supplier the supplier that is responsible for getting the value that
* should be matched.
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @return a T object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public <T> T until(final Callable<T> supplier, final Matcher<? super T> matcher) {
return until(new CallableHamcrestCondition<T>(supplier, matcher, generateConditionSettings()));
}
/**
* Wait until the given supplier matches the supplied predicate. For example:
*
* <pre>
* await().until(myRepository::count, cnt -> cnt == 2);
* </pre>
*
* @param supplier The supplier that returns the object that will be evaluated by the predicate.
* @param predicate The predicate that must match
* @param <T> the generic type
* @since 3.1.1
* @return a T object.
*/
public <T> T until(final Callable<T> supplier, final Predicate<? super T> predicate) {
return until(supplier, new TypeSafeMatcher<T>() {
@Override
protected void describeMismatchSafely(T item, Description description) {
description.appendText("it returned <false> for input of ").appendValue(item);
}
@Override
public void describeTo(Description description) {
description.appendText("the predicate to return <true>");
}
@Override
protected boolean matchesSafely(T item) {
return predicate.matches(item);
}
});
}
/**
* Await until a {@link java.lang.Runnable} supplier execution passes (ends without throwing an exception). E.g. with Java 8:
* <p> </p>
* <pre>
* await().untilAsserted(() -> Assertions.assertThat(personRepository.size()).isEqualTo(6));
* </pre>
* or
* <pre>
* await().untilAsserted(() -> assertEquals(6, personRepository.size()));
* </pre>
* <p> </p>
* This method is intended to benefit from lambda expressions introduced in Java 8. It allows to use standard AssertJ/FEST Assert assertions
* (by the way also standard JUnit/TestNG assertions) to test asynchronous calls and systems.
* <p> </p>
* {@link java.lang.AssertionError} instances thrown by the supplier are treated as an assertion failure and proper error message is propagated on timeout.
* Other exceptions are rethrown immediately as an execution errors.
* <p> </p>
* Why technically it is completely valid to use plain Runnable class in Java 7 code, the resulting expression is very verbose and can decrease
* the readability of the test case, e.g.
* <p> </p>
* <pre>
* await().untilAsserted(new Runnable() {
* public void run() {
* Assertions.assertThat(personRepository.size()).isEqualTo(6);
* }
* });
* </pre>
* <p> </p>
* <b>NOTE:</b><br>
* Be <i>VERY</i> careful so that you're not using this method incorrectly in languages (like Kotlin and Groovy) that doesn't
* disambiguate between a {@link ThrowingRunnable} that doesn't return anything (void) and {@link Callable} that returns a value.
* For example in Kotlin you can do like this:
* <p> </p>
* <pre>
* await().untilAsserted { true == false }
* </pre>
* and the compiler won't complain with an error (as is the case in Java). If you were to execute this test in Kotlin it'll pass!
*
* @param assertion the supplier that is responsible for executing the assertion and throwing AssertionError on failure.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
* @since 1.6.0
*/
public void untilAsserted(final ThrowingRunnable assertion) {
until(new AssertionCondition(assertion, generateConditionSettings()));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @return a {@link java.lang.Integer} object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public Integer untilAtomic(final AtomicInteger atomic, final Matcher<? super Integer> matcher) {
return until(new CallableHamcrestCondition<Integer>(new Callable<Integer>() {
public Integer call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @return a {@link java.lang.Long} object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public Long untilAtomic(final AtomicLong atomic, final Matcher<? super Long> matcher) {
return until(new CallableHamcrestCondition<Long>(new Callable<Long>() {
public Long call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void untilAtomic(final AtomicBoolean atomic, final Matcher<? super Boolean> matcher) {
until(new CallableHamcrestCondition<Boolean>(new Callable<Boolean>() {
public Boolean call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a Atomic boolean becomes true.
*
* @param atomic the atomic variable
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void untilTrue(final AtomicBoolean atomic) {
untilAtomic(atomic, anyOf(is(Boolean.TRUE), is(true)));
}
/**
* Await until a Atomic boolean becomes false.
*
* @param atomic the atomic variable
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void untilFalse(final AtomicBoolean atomic) {
untilAtomic(atomic, anyOf(is(Boolean.FALSE), is(false)));
}
/**
* Await until a Atomic variable has a value matching the specified
* {@link org.hamcrest.Matcher}. E.g.
* <p> </p>
* <pre>
* await().untilAtomic(myAtomic, is(greaterThan(2)));
* </pre>
*
* @param atomic the atomic variable
* @param matcher the matcher The hamcrest matcher that checks whether the
* condition is fulfilled.
* @param <V> a V object.
* @return a V object.
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public <V> V untilAtomic(final AtomicReference<V> atomic, final Matcher<? super V> matcher) {
return until(new CallableHamcrestCondition<V>(new Callable<V>() {
public V call() {
return atomic.get();
}
}, matcher, generateConditionSettings()));
}
/**
* Await until a {@link java.util.concurrent.Callable} returns <code>true</code>. This is method
* is not as generic as the other variants of "until" but it allows for a
* more precise and in some cases even more english-like syntax. E.g.
* <p> </p>
* <pre>
* await().until(numberOfPersonsIsEqualToThree());
* </pre>
* <p> </p>
* where "numberOfPersonsIsEqualToThree()" returns a standard
* {@link java.util.concurrent.Callable} of type {@link java.lang.Boolean}:
* <p> </p>
* <pre>
* private Callable<Boolean> numberOfPersons() {
* return new Callable<Boolean>() {
* public Boolean call() {
* return personRepository.size() == 3;
* }
* };
* }
* </pre>
*
* @param conditionEvaluator the condition evaluator
* @throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.
*/
public void until(Callable<Boolean> conditionEvaluator) {
until(new CallableCondition(conditionEvaluator, generateConditionSettings()));
}
private ConditionSettings generateConditionSettings() {
Duration actualPollDelay = definePollDelay(pollDelay, pollInterval);
if (actualPollDelay.isForever()) {
throw new IllegalArgumentException("Cannot delay polling forever");
}
Duration timeout = timeoutConstraint.getMaxWaitTime();
final long timeoutInMS = timeout.getValueInMS();
if (!timeout.isForever() && timeoutInMS <= actualPollDelay.getValueInMS()) {
throw new IllegalStateException(String.format("Timeout (%s %s) must be greater than the poll delay (%s %s).",
timeout.getValue(), timeout.getTimeUnitAsString(), actualPollDelay.getValue(), actualPollDelay.getTimeUnitAsString()));
} else if ((!actualPollDelay.isForever() && !timeout.isForever()) && timeoutInMS <= actualPollDelay.getValueInMS()) {
throw new IllegalStateException(String.format("Timeout (%s %s) must be greater than the poll delay (%s %s).",
timeout.getValue(), timeout.getTimeUnitAsString(), actualPollDelay.getValue(), actualPollDelay.getTimeUnitAsString()));
}
ExecutorLifecycle executorLifecycle;
if (this.executorLifecycle == null) {
executorLifecycle = ExecutorLifecycle.withNormalCleanupBehavior(new Supplier<ExecutorService>() {
@Override
public ExecutorService get() {
return InternalExecutorServiceFactory.create(new BiFunction<Runnable, String, Thread>() {
@Override
public Thread apply(Runnable r, String threadName) {
return new Thread(Thread.currentThread().getThreadGroup(), r, threadName);
}
}, alias);
}
});
} else {
executorLifecycle = this.executorLifecycle;
}
return new ConditionSettings(alias, catchUncaughtExceptions, timeoutConstraint, pollInterval, actualPollDelay,
conditionEvaluationListener, exceptionsIgnorer, executorLifecycle);
}
private <T> T until(Condition<T> condition) {
return condition.await();
}
/**
* Ensures backward compatibility (especially that poll delay is the same as poll interval for fixed poll interval).
* It also make sure that poll delay is {@link Duration#ZERO} for all other poll intervals if poll delay was not explicitly
* defined. If poll delay was explicitly defined the it will just be returned.
*
* @param pollDelay The poll delay
* @param pollInterval The chosen (or default) poll interval
* @return The poll delay to use
*/
private Duration definePollDelay(Duration pollDelay, PollInterval pollInterval) {
final Duration pollDelayToUse;
// If a poll delay is null then a poll delay has not been explicitly defined by the user
if (pollDelay == null) {
if (pollInterval != null && pollInterval instanceof FixedPollInterval) {
pollDelayToUse = pollInterval.next(1, Duration.ZERO); // Will return same poll delay as poll interval
} else {
pollDelayToUse = Duration.ZERO; // Default poll delay for non-fixed poll intervals
}
} else {
// Poll delay was explicitly defined, use it!
pollDelayToUse = pollDelay;
}
return pollDelayToUse;
}
}
| ConditionFactory: fix typo in javadoc (#133)
| awaitility/src/main/java/org/awaitility/core/ConditionFactory.java | ConditionFactory: fix typo in javadoc (#133) | <ide><path>waitility/src/main/java/org/awaitility/core/ConditionFactory.java
<ide> * {@link java.lang.AssertionError} instances thrown by the supplier are treated as an assertion failure and proper error message is propagated on timeout.
<ide> * Other exceptions are rethrown immediately as an execution errors.
<ide> * <p> </p>
<del> * Why technically it is completely valid to use plain Runnable class in Java 7 code, the resulting expression is very verbose and can decrease
<add> * While technically it is completely valid to use plain Runnable class in Java 7 code, the resulting expression is very verbose and can decrease
<ide> * the readability of the test case, e.g.
<ide> * <p> </p>
<ide> * <pre> |
|
Java | mit | 2e22073472ff4d7d06332c88acb80dc4ec709527 | 0 | sunjiesh/JavaShowcase,sunjiesh/thirdpartydemo,sunjiesh/ThirdService,sunjiesh/thirdpartydemo | package cn.com.sunjiesh.thirdpartdemo.service;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.sunjiesh.thirdpartdemo.common.WechatEventClickMessageEventkeyEnum;
import cn.com.sunjiesh.thirdpartdemo.dao.RedisWechatMessageDao;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalImageMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalLinkMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalLocationMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalShortvideoMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalVideoMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalVoiceMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventClickMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventLocationMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventLocationSelectMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventPicCommonMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventPicPhotoOrAlbumMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventPicSysphotoMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventScanMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventScancodeCommonMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventSubscribeMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventViewMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventWeixinMessage;
import cn.com.sunjiesh.wechat.helper.WechatMessageConvertDocumentHelper;
import cn.com.sunjiesh.wechat.model.request.message.WechatNormalTextMessageRequest;
import cn.com.sunjiesh.wechat.model.response.message.WechatReceiveReplayImageMessageResponse;
import cn.com.sunjiesh.wechat.model.response.message.WechatReceiveReplayTextMessageResponse;
import cn.com.sunjiesh.wechat.service.AbstractWechatMessageReceiveService;
import cn.com.sunjiesh.wechat.service.IWechatMessageReceiveProcessService;
import cn.com.sunjiesh.xcutils.common.base.ServiceException;
@Service
public class CustomMessageReceiveService extends AbstractWechatMessageReceiveService {
private static final String LAST_IMAGE_MESSAGE_MEDIA_ID = "lastImageMessageMediaId";
private static final String LAST_VOICE_MESSAGE_MEDIA_ID = "lastVoiceMessageMediaId";
private static final Logger LOGGER = LoggerFactory.getLogger(CustomMessageReceiveService.class);
@Autowired
private IWechatMessageReceiveProcessService messageReceiveProcessService;
@Autowired
private RedisWechatMessageDao redisWechatMessageDao;
@Override
protected Document messageReceive(Document doc4j) throws ServiceException {
LOGGER.info("Call CustomMessageReceiveService.messageReceive(Document doc4j)方法");
return super.messageReceive(doc4j);
}
@Override
protected Document messageReceive(WechatReceiveEventLocationSelectMessage wechatMessage) {
try {
return messageReceiveProcessService.messageReceive(wechatMessage);
} catch (ServiceException ex) {
LOGGER.error(ex.getMessage(),ex);
}
return null;
}
@Override
protected Document messageRecive(WechatNormalTextMessageRequest textMessage) {
String responseToUserName=textMessage.getFromUserName();
String responseFromUserName=textMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalImageMessage imageMessage) {
String responseToUserName=imageMessage.getFromUserName();
String responseFromUserName=imageMessage.getToUserName();
String mediaId=imageMessage.getMediaId();
redisWechatMessageDao.save(LAST_IMAGE_MESSAGE_MEDIA_ID, mediaId);
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("图片已经上传,midiaId为="+mediaId);
return WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
}
@Override
protected Document messageRecive(WechatReceiveNormalVoiceMessage voiceMessage) {
String responseToUserName=voiceMessage.getFromUserName();
String responseFromUserName=voiceMessage.getToUserName();
String mediaId=voiceMessage.getMediaId();
redisWechatMessageDao.save(LAST_VOICE_MESSAGE_MEDIA_ID, mediaId);
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("语音已经上传,midiaId为="+mediaId);
return WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
}
@Override
protected Document messageRecive(WechatReceiveNormalVideoMessage videoMessage) {
String responseToUserName=videoMessage.getFromUserName();
String responseFromUserName=videoMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalShortvideoMessage shortVodeoMessage) {
String responseToUserName=shortVodeoMessage.getFromUserName();
String responseFromUserName=shortVodeoMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalLocationMessage locationMessage) {
String responseToUserName=locationMessage.getFromUserName();
String responseFromUserName=locationMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalLinkMessage linkMessage) {
String responseToUserName=linkMessage.getFromUserName();
String responseFromUserName=linkMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventClickMessage clickMessage) {
//返回对象
Document respDoc=null;
final String eventKey=clickMessage.getEventKey();
final String responseToUserName = clickMessage.getFromUserName();
final String responseFromUserName = clickMessage.getToUserName();
LOGGER.debug("EventKey="+eventKey);
WechatEventClickMessageEventkeyEnum eventKeyEnum=WechatEventClickMessageEventkeyEnum.valueOf(eventKey);
switch(eventKeyEnum){
case GetTextMessage:{
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("Hello,This is a test text message.\n你好!這是一條測試文本消息");
respDoc=WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
};break;
case GetImageMessage:{
String mediaId=redisWechatMessageDao.get(LAST_IMAGE_MESSAGE_MEDIA_ID);
if(StringUtils.isEmpty(mediaId)){
LOGGER.warn("没有找到用户上传的图片,请上传一张图片之后再试");
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("没有找到用户上传的图片,请上传一张图片之后再试");
respDoc=WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
}else{
WechatReceiveReplayImageMessageResponse imageMessageResponse=new WechatReceiveReplayImageMessageResponse(responseToUserName, responseFromUserName);
imageMessageResponse.setMediaId(mediaId);
respDoc=WechatMessageConvertDocumentHelper.imageMessageResponseToDocumnet(imageMessageResponse);
}
};break;
default:{
respDoc=respError(responseToUserName, responseFromUserName);
}
}
return respDoc;
}
@Override
protected Document messageRecive(WechatReceiveEventLocationMessage locationMessage) {
String responseToUserName=locationMessage.getFromUserName();
String responseFromUserName=locationMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventScanMessage scanMessage) {
String responseToUserName=scanMessage.getFromUserName();
String responseFromUserName=scanMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventSubscribeMessage subscribeMessage) {
String responseToUserName=subscribeMessage.getFromUserName();
String responseFromUserName=subscribeMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventViewMessage viewMessage) {
String responseToUserName=viewMessage.getFromUserName();
String responseFromUserName=viewMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventScancodeCommonMessage scanCodePushMessage) {
String responseToUserName=scanCodePushMessage.getFromUserName();
String responseFromUserName=scanCodePushMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventWeixinMessage picPhotoOrAlbumEventMessage) {
String responseToUserName=picPhotoOrAlbumEventMessage.getFromUserName();
String responseFromUserName=picPhotoOrAlbumEventMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventPicSysphotoMessage picSysphotoMessage) {
String responseToUserName=picSysphotoMessage.getFromUserName();
String responseFromUserName=picSysphotoMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventPicPhotoOrAlbumMessage picPhotoOrAlbumEventMessage) {
String responseToUserName=picPhotoOrAlbumEventMessage.getFromUserName();
String responseFromUserName=picPhotoOrAlbumEventMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventPicCommonMessage wechatMessage) {
String responseToUserName=wechatMessage.getFromUserName();
String responseFromUserName=wechatMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
/**
* 错误消息返回
* @param responseToUserName
* @param responseFromUserName
* @return
*/
protected Document respError(String responseToUserName, String responseFromUserName) {
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("暂不支持");
return WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
}
}
| thirdpartydemo-web/src/main/java/cn/com/sunjiesh/thirdpartdemo/service/CustomMessageReceiveService.java | package cn.com.sunjiesh.thirdpartdemo.service;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.sunjiesh.thirdpartdemo.common.WechatEventClickMessageEventkeyEnum;
import cn.com.sunjiesh.thirdpartdemo.dao.RedisWechatAccessTokenDao;
import cn.com.sunjiesh.thirdpartdemo.dao.RedisWechatMessageDao;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalImageMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalLinkMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalLocationMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalShortvideoMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalVideoMessage;
import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalVoiceMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventClickMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventLocationMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventLocationSelectMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventPicCommonMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventPicPhotoOrAlbumMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventPicSysphotoMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventScanMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventScancodeCommonMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventSubscribeMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventViewMessage;
import cn.com.sunjiesh.wechat.entity.message.event.WechatReceiveEventWeixinMessage;
import cn.com.sunjiesh.wechat.helper.WechatMessageConvertDocumentHelper;
import cn.com.sunjiesh.wechat.model.request.message.WechatNormalTextMessageRequest;
import cn.com.sunjiesh.wechat.model.response.message.WechatReceiveReplayImageMessageResponse;
import cn.com.sunjiesh.wechat.model.response.message.WechatReceiveReplayTextMessageResponse;
import cn.com.sunjiesh.wechat.service.AbstractWechatMessageReceiveService;
import cn.com.sunjiesh.wechat.service.IWechatMessageReceiveProcessService;
import cn.com.sunjiesh.xcutils.common.base.ServiceException;
@Service
public class CustomMessageReceiveService extends AbstractWechatMessageReceiveService {
private static final String LAST_IMAGE_MESSAGE_MEDIA_ID = "lastImageMessageMediaId";
private static final Logger LOGGER = LoggerFactory.getLogger(CustomMessageReceiveService.class);
@Autowired
private IWechatMessageReceiveProcessService messageReceiveProcessService;
@Autowired
private RedisWechatMessageDao redisWechatMessageDao;
@Override
protected Document messageReceive(Document doc4j) throws ServiceException {
LOGGER.info("Call CustomMessageReceiveService.messageReceive(Document doc4j)方法");
return super.messageReceive(doc4j);
}
@Override
protected Document messageReceive(WechatReceiveEventLocationSelectMessage wechatMessage) {
try {
return messageReceiveProcessService.messageReceive(wechatMessage);
} catch (ServiceException ex) {
LOGGER.error(ex.getMessage(),ex);
}
return null;
}
@Override
protected Document messageRecive(WechatNormalTextMessageRequest textMessage) {
String responseToUserName=textMessage.getFromUserName();
String responseFromUserName=textMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalImageMessage imageMessage) {
String responseToUserName=imageMessage.getFromUserName();
String responseFromUserName=imageMessage.getToUserName();
String mediaId=imageMessage.getMediaId();
redisWechatMessageDao.save(LAST_IMAGE_MESSAGE_MEDIA_ID, mediaId);
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalVoiceMessage voiceMessage) {
String responseToUserName=voiceMessage.getFromUserName();
String responseFromUserName=voiceMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalVideoMessage videoMessage) {
String responseToUserName=videoMessage.getFromUserName();
String responseFromUserName=videoMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalShortvideoMessage shortVodeoMessage) {
String responseToUserName=shortVodeoMessage.getFromUserName();
String responseFromUserName=shortVodeoMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalLocationMessage locationMessage) {
String responseToUserName=locationMessage.getFromUserName();
String responseFromUserName=locationMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveNormalLinkMessage linkMessage) {
String responseToUserName=linkMessage.getFromUserName();
String responseFromUserName=linkMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventClickMessage clickMessage) {
//返回对象
Document respDoc=null;
final String eventKey=clickMessage.getEventKey();
final String responseToUserName = clickMessage.getFromUserName();
final String responseFromUserName = clickMessage.getToUserName();
LOGGER.debug("EventKey="+eventKey);
WechatEventClickMessageEventkeyEnum eventKeyEnum=WechatEventClickMessageEventkeyEnum.valueOf(eventKey);
switch(eventKeyEnum){
case GetTextMessage:{
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("Hello,This is a test text message.\n你好!這是一條測試文本消息");
respDoc=WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
};break;
case GetImageMessage:{
String mediaId=redisWechatMessageDao.get(LAST_IMAGE_MESSAGE_MEDIA_ID);
if(StringUtils.isEmpty(mediaId)){
LOGGER.warn("没有找到用户上传的图片,请上传一张图片之后再试");
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("没有找到用户上传的图片,请上传一张图片之后再试");
respDoc=WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
}else{
WechatReceiveReplayImageMessageResponse imageMessageResponse=new WechatReceiveReplayImageMessageResponse(responseToUserName, responseFromUserName);
imageMessageResponse.setMediaId(mediaId);
respDoc=WechatMessageConvertDocumentHelper.imageMessageResponseToDocumnet(imageMessageResponse);
}
};break;
default:{
respDoc=respError(responseToUserName, responseFromUserName);
}
}
return respDoc;
}
@Override
protected Document messageRecive(WechatReceiveEventLocationMessage locationMessage) {
String responseToUserName=locationMessage.getFromUserName();
String responseFromUserName=locationMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventScanMessage scanMessage) {
String responseToUserName=scanMessage.getFromUserName();
String responseFromUserName=scanMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventSubscribeMessage subscribeMessage) {
String responseToUserName=subscribeMessage.getFromUserName();
String responseFromUserName=subscribeMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventViewMessage viewMessage) {
String responseToUserName=viewMessage.getFromUserName();
String responseFromUserName=viewMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventScancodeCommonMessage scanCodePushMessage) {
String responseToUserName=scanCodePushMessage.getFromUserName();
String responseFromUserName=scanCodePushMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventWeixinMessage picPhotoOrAlbumEventMessage) {
String responseToUserName=picPhotoOrAlbumEventMessage.getFromUserName();
String responseFromUserName=picPhotoOrAlbumEventMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventPicSysphotoMessage picSysphotoMessage) {
String responseToUserName=picSysphotoMessage.getFromUserName();
String responseFromUserName=picSysphotoMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventPicPhotoOrAlbumMessage picPhotoOrAlbumEventMessage) {
String responseToUserName=picPhotoOrAlbumEventMessage.getFromUserName();
String responseFromUserName=picPhotoOrAlbumEventMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
@Override
protected Document messageRecive(WechatReceiveEventPicCommonMessage wechatMessage) {
String responseToUserName=wechatMessage.getFromUserName();
String responseFromUserName=wechatMessage.getToUserName();
return respError(responseToUserName, responseFromUserName);
}
/**
* 错误消息返回
* @param responseToUserName
* @param responseFromUserName
* @return
*/
protected Document respError(String responseToUserName, String responseFromUserName) {
WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
textMessageResponse.setContent("暂不支持");
return WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
}
}
| 上传语音事件处理 | thirdpartydemo-web/src/main/java/cn/com/sunjiesh/thirdpartdemo/service/CustomMessageReceiveService.java | 上传语音事件处理 | <ide><path>hirdpartydemo-web/src/main/java/cn/com/sunjiesh/thirdpartdemo/service/CustomMessageReceiveService.java
<ide> import org.springframework.stereotype.Service;
<ide>
<ide> import cn.com.sunjiesh.thirdpartdemo.common.WechatEventClickMessageEventkeyEnum;
<del>import cn.com.sunjiesh.thirdpartdemo.dao.RedisWechatAccessTokenDao;
<ide> import cn.com.sunjiesh.thirdpartdemo.dao.RedisWechatMessageDao;
<ide> import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalImageMessage;
<ide> import cn.com.sunjiesh.wechat.entity.message.WechatReceiveNormalLinkMessage;
<ide> public class CustomMessageReceiveService extends AbstractWechatMessageReceiveService {
<ide>
<ide> private static final String LAST_IMAGE_MESSAGE_MEDIA_ID = "lastImageMessageMediaId";
<add>
<add> private static final String LAST_VOICE_MESSAGE_MEDIA_ID = "lastVoiceMessageMediaId";
<ide>
<ide> private static final Logger LOGGER = LoggerFactory.getLogger(CustomMessageReceiveService.class);
<ide>
<ide> String responseFromUserName=imageMessage.getToUserName();
<ide> String mediaId=imageMessage.getMediaId();
<ide> redisWechatMessageDao.save(LAST_IMAGE_MESSAGE_MEDIA_ID, mediaId);
<del> return respError(responseToUserName, responseFromUserName);
<add>
<add> WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
<add> textMessageResponse.setContent("图片已经上传,midiaId为="+mediaId);
<add> return WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
<ide> }
<ide>
<ide> @Override
<ide> protected Document messageRecive(WechatReceiveNormalVoiceMessage voiceMessage) {
<ide> String responseToUserName=voiceMessage.getFromUserName();
<ide> String responseFromUserName=voiceMessage.getToUserName();
<del> return respError(responseToUserName, responseFromUserName);
<add> String mediaId=voiceMessage.getMediaId();
<add> redisWechatMessageDao.save(LAST_VOICE_MESSAGE_MEDIA_ID, mediaId);
<add> WechatReceiveReplayTextMessageResponse textMessageResponse=new WechatReceiveReplayTextMessageResponse(responseToUserName, responseFromUserName);
<add> textMessageResponse.setContent("语音已经上传,midiaId为="+mediaId);
<add> return WechatMessageConvertDocumentHelper.textMessageResponseToDocument(textMessageResponse);
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | 10123f8038732662bd2fd3022fe4b3a65bbe4c4a | 0 | skynxt/SkyNxt.github.io,skynxt/SkyNxt.github.io | // The MIT License (MIT)
// Copyright (c) 2015 SkyNxt.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
var SkyNxt = (function(SkyNxt, $, undefined) {
SkyNxt.DIRECTORY = 'SkyNxt';
SkyNxt.SUB_DIRECTORY = 'user';
SkyNxt.USER_FILE = 'skynxt.user';
SkyNxt.JSON_FILE_DATA = 'undefined';
SkyNxt.FILE_ENTRY = 'undefined';
SkyNxt.PEER_SETTINGS = 'peerSettings';
SkyNxt.PEER_SETTING_AUTO = 'auto';
SkyNxt.PEER_SETTING_IP_PORT = '';
SkyNxt.UI_THEME = 'uiTheme';
SkyNxt.UI_THEME_LIGHT = 'a';
SkyNxt.UI_THEME_DARK = 'b';
SkyNxt.TRUSTED_PEERS = 'trustedPeers';
SkyNxt.HTTP_NODE = 'http://';
SkyNxt.HTTPS_NODE = 'https://';
SkyNxt.USER_SETTING_COLLECTION = 'user';
SkyNxt.usersettings = new loki('user.settings');
SkyNxt.fileSystem = 'undefined';
SkyNxt.SAVED_UI_THEME = "";
SkyNxt.initFileSystem = function(fileSystem) {
SkyNxt.fileSystem = fileSystem;
SkyNxt.fileSystem.root.getDirectory(SkyNxt.DIRECTORY, { create: false }, //try finding SkyNxt directory if it already exists
function(dirEntry)
{
dirEntry.getDirectory(SkyNxt.SUB_DIRECTORY, { create: false },
function(fileEntry)
{
fileEntry.getFile(SkyNxt.USER_FILE, { create: false }, createRead, fail)
}, fail);
},
createUserFile
);
}
function createUserFile()
{
SkyNxt.fileSystem.root.getDirectory(SkyNxt.DIRECTORY, {create: true}, //Create SkyNxt directory if it fails to find it
function(dirEntry)
{
dirEntry.getDirectory(SkyNxt.SUB_DIRECTORY, {create: true},
function(fileEntry)
{
fileEntry.getFile(SkyNxt.USER_FILE, {create: true, exclusive: false}, firstWrite, fail)
}, fail);
}, fail);
}
function createRead(fileEntry) {
if(SkyNxt.FILE_ENTRY == 'undefined')
{
SkyNxt.FILE_ENTRY = fileEntry;
}
fileEntry.file(readAsText, fail);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
SkyNxt.usersettings.loadJSON(evt.target.result);
var userdbs = SkyNxt.usersettings.getCollection(SkyNxt.USER_SETTING_COLLECTION);
var uiTheme = userdbs.findOne({'key' : SkyNxt.UI_THEME});
SkyNxt.SAVED_UI_THEME = uiTheme.value;
$("#" + SkyNxt.SAVED_UI_THEME).prop("checked", true);
changeTheme(String(SkyNxt.SAVED_UI_THEME));
var trustedPeerdata = userdbs.findOne({'key' : SkyNxt.TRUSTED_PEERS});
SkyNxt.PEER_IP = trustedPeerdata.value.split(',');
if(String(SkyNxt.PEER_IP[0]) == String(SkyNxt.HTTPS_NODE) || String(SkyNxt.PEER_IP[0]) == String(SkyNxt.HTTP_NODE))
{
$("#nodeIP").val(String(SkyNxt.PEER_IP[1]));
$("#port").val(String(SkyNxt.PEER_IP[2]));
SkyNxt.ADDRESS = SkyNxt.PEER_IP[0] + SkyNxt.PEER_IP[1] + ":" + SkyNxt.PEER_IP[2];
$("#radio-choice-2").prop("checked", true);
}
else
{
$("#ipGrid").hide();
$("#nodeIPBtn").hide();
SkyNxt.getPeer();
}
};
reader.readAsText(file);
}
SkyNxt.getPeer = function()
{
var max = SkyNxt.PEER_IP.length;
var min = 0;
var rand = Math.floor(Math.random() * (max - min + 1)) + min;
SkyNxt.ADDRESS = SkyNxt.PEER_IP[rand] + ":" + SkyNxt.PORT;
}
function firstWrite(fileEntry)
{
SkyNxt.discover();
var userdbs = SkyNxt.usersettings.addCollection(SkyNxt.USER_SETTING_COLLECTION);
userdbs.insert({key:SkyNxt.PEER_SETTINGS, value:SkyNxt.PEER_SETTING_AUTO});
userdbs.insert({key:SkyNxt.UI_THEME, value:SkyNxt.UI_THEME_LIGHT});
var trustedPeerList = "";
for(j = 1; j <= SkyNxt.trustedpeersdb.data.length; j++)
{
var data = SkyNxt.trustedpeersdb.get(j);
var ip = String(data.ip_peer);
trustedPeerList = ip + "," + trustedPeerList;
}
userdbs.insert({key:SkyNxt.TRUSTED_PEERS, value:trustedPeerList});
SkyNxt.createWrite(fileEntry);
}
SkyNxt.createWrite = function(fileEntry) {
if(SkyNxt.FILE_ENTRY == 'undefined')
{
SkyNxt.FILE_ENTRY = fileEntry;
}
SkyNxt.JSON_FILE_DATA = SkyNxt.usersettings.serialize();
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
};
if(SkyNxt.JSON_FILE_DATA != 'undefined')
writer.write(SkyNxt.JSON_FILE_DATA);
}
function fail(error) {
console.log(error.code);
}
return SkyNxt;
}(SkyNxt || {}, jQuery)); | www/js/ui/file.js | // The MIT License (MIT)
// Copyright (c) 2015 SkyNxt.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
var SkyNxt = (function(SkyNxt, $, undefined) {
SkyNxt.DIRECTORY = 'SkyNxt';
SkyNxt.SUB_DIRECTORY = 'user';
SkyNxt.USER_FILE = 'skynxt.user';
SkyNxt.JSON_FILE_DATA = 'undefined';
SkyNxt.FILE_ENTRY = 'undefined';
SkyNxt.PEER_SETTINGS = 'peerSettings';
SkyNxt.PEER_SETTING_AUTO = 'auto';
SkyNxt.PEER_SETTING_IP_PORT = '';
SkyNxt.UI_THEME = 'uiTheme';
SkyNxt.UI_THEME_LIGHT = 'a';
SkyNxt.UI_THEME_DARK = 'b';
SkyNxt.TRUSTED_PEERS = 'trustedPeers';
SkyNxt.HTTP_NODE = 'http://';
SkyNxt.HTTPS_NODE = 'https://';
SkyNxt.USER_SETTING_COLLECTION = 'user';
SkyNxt.usersettings = new loki('user.settings');
SkyNxt.fileSystem = 'undefined';
SkyNxt.SAVED_UI_THEME = "";
SkyNxt.initFileSystem = function(fileSystem) {
SkyNxt.fileSystem = fileSystem;
SkyNxt.fileSystem.root.getDirectory(SkyNxt.DIRECTORY, { create: false }, //try finding SkyNxt directory if it already exists
function(dirEntry)
{
dirEntry.getDirectory(SkyNxt.SUB_DIRECTORY, { create: false },
function(fileEntry)
{
fileEntry.getFile(SkyNxt.USER_FILE, { create: false }, createRead, fail)
}, fail);
},
createUserFile
);
}
function createUserFile()
{
SkyNxt.fileSystem.root.getDirectory(SkyNxt.DIRECTORY, {create: true}, //Create SkyNxt directory if it fails to find it
function(dirEntry)
{
dirEntry.getDirectory(SkyNxt.SUB_DIRECTORY, {create: true},
function(fileEntry)
{
fileEntry.getFile(SkyNxt.USER_FILE, {create: true, exclusive: false}, firstWrite, fail)
}, fail);
}, fail);
}
function createRead(fileEntry) {
if(SkyNxt.FILE_ENTRY == 'undefined')
{
SkyNxt.FILE_ENTRY = fileEntry;
}
fileEntry.file(readAsText, fail);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
SkyNxt.usersettings.loadJSON(evt.target.result);
var userdbs = SkyNxt.usersettings.getCollection(SkyNxt.USER_SETTING_COLLECTION);
var uiTheme = userdbs.findOne({'key' : SkyNxt.UI_THEME});
SkyNxt.SAVED_UI_THEME = uiTheme.value;
$("#" + SkyNxt.SAVED_UI_THEME).prop("checked", true);
changeTheme(String(SkyNxt.SAVED_UI_THEME));
var trustedPeerdata = userdbs.findOne({'key' : SkyNxt.TRUSTED_PEERS});
SkyNxt.PEER_IP = trustedPeerdata.value.split(',');
if(String(SkyNxt.PEER_IP[0]) == String(SkyNxt.HTTPS_NODE) || String(SkyNxt.PEER_IP[0]) == String(SkyNxt.HTTP_NODE))
{
$("#nodeIP").val(String(SkyNxt.PEER_IP[1]));
$("#port").val(String(SkyNxt.PEER_IP[2]));
SkyNxt.ADDRESS = SkyNxt.PEER_IP[0] + SkyNxt.PEER_IP[1] + ":" + SkyNxt.PEER_IP[2];
$("#radio-choice-2").prop("checked", true);
}
else
{
$("#ipGrid").hide();
$("#nodeIPBtn").hide();
SkyNxt.getPeer();
}
};
reader.readAsText(file);
}
SkyNxt.getPeer = function()
{
var max = SkyNxt.PEER_IP.length;
var min = 0;
var rand = Math.floor(Math.random() * (max - min + 1)) + min;
SkyNxt.ADDRESS = SkyNxt.PEER_IP[rand] + ":" + SkyNxt.PORT;
}
function firstWrite(fileEntry)
{
SkyNxt.discover();
var userdbs = SkyNxt.usersettings.addCollection(SkyNxt.USER_SETTING_COLLECTION);
userdbs.insert({key:SkyNxt.PEER_SETTINGS, value:SkyNxt.PEER_SETTING_AUTO});
userdbs.insert({key:SkyNxt.UI_THEME, value:SkyNxt.UI_THEME_LIGHT});
var trustedPeerList = "";
for(j = 1; j <= SkyNxt.trustedpeersdb.data.length; j++)
{
var data = SkyNxt.trustedpeersdb.get(j);
var ip = String(data.ip_peer);
trustedPeerList = ip + "," + trustedPeerList;
}
SkyNxt.PEER_IP = trustedPeerList.split(',');
SkyNxt.getPeer();
userdbs.insert({key:SkyNxt.TRUSTED_PEERS, value:trustedPeerList});
SkyNxt.createWrite(fileEntry);
}
SkyNxt.createWrite = function(fileEntry) {
if(SkyNxt.FILE_ENTRY == 'undefined')
{
SkyNxt.FILE_ENTRY = fileEntry;
}
SkyNxt.JSON_FILE_DATA = SkyNxt.usersettings.serialize();
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
};
if(SkyNxt.JSON_FILE_DATA != 'undefined')
writer.write(SkyNxt.JSON_FILE_DATA);
}
function fail(error) {
console.log(error.code);
}
return SkyNxt;
}(SkyNxt || {}, jQuery)); | modifying build config file, bug fix
| www/js/ui/file.js | modifying build config file, bug fix | <ide><path>ww/js/ui/file.js
<ide> var ip = String(data.ip_peer);
<ide> trustedPeerList = ip + "," + trustedPeerList;
<ide> }
<del> SkyNxt.PEER_IP = trustedPeerList.split(',');
<del> SkyNxt.getPeer();
<ide> userdbs.insert({key:SkyNxt.TRUSTED_PEERS, value:trustedPeerList});
<ide> SkyNxt.createWrite(fileEntry);
<ide> } |
|
JavaScript | mpl-2.0 | dfb9229d061f350206c9ce54e07363870c47a598 | 0 | mozilla/splice,ncloudioj/splice,ncloudioj/splice,ncloudioj/splice,mozilla/splice,oyiptong/splice,oyiptong/splice,ncloudioj/splice,mozilla/splice,mozilla/splice,oyiptong/splice,oyiptong/splice | import fetch from 'isomorphic-fetch';
let apiUrl;
if (typeof __DEVELOPMENT__ !== 'undefined' && __DEVELOPMENT__ === true) {
apiUrl = __DEVAPI__;
} else {
apiUrl = __LIVEAPI__;
}
export const REQUEST_CREATE_CAMPAIGN = 'REQUEST_CREATE_CAMPAIGN';
export const RECEIVE_CREATE_CAMPAIGN = 'RECEIVE_CREATE_CAMPAIGN';
export const REQUEST_UPDATE_CAMPAIGN = 'REQUEST_UPDATE_CAMPAIGN';
export const RECEIVE_UPDATE_CAMPAIGN = 'RECEIVE_UPDATE_CAMPAIGN';
export const REQUEST_CAMPAIGNS = 'REQUEST_CAMPAIGNS';
export const RECEIVE_CAMPAIGNS = 'RECEIVE_CAMPAIGNS';
export const REQUEST_CAMPAIGN = 'REQUEST_CAMPAIGN';
export const RECEIVE_CAMPAIGN = 'RECEIVE_CAMPAIGN';
export function requestCreateCampaign() {
return {type: REQUEST_CREATE_CAMPAIGN};
}
export function receiveCreateCampaign(json) {
return {
type: RECEIVE_CREATE_CAMPAIGN,
json: json
};
}
export function requestUpdateCampaign() {
return {type: REQUEST_UPDATE_CAMPAIGN};
}
export function receiveUpdateCampaign(json) {
return {
type: RECEIVE_UPDATE_CAMPAIGN,
json: json
};
}
export function requestCampaign() {
return {type: REQUEST_CAMPAIGN};
}
export function receiveCampaign(json) {
return {
type: RECEIVE_CAMPAIGN,
json: json
};
}
export function requestCampaigns() {
return {type: REQUEST_CAMPAIGNS};
}
export function receiveCampaigns(json) {
return {
type: RECEIVE_CAMPAIGNS,
json: json
};
}
export function createCampaign(data) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestCreateCampaign());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: data
})
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveCreateCampaign(json));
resolve(json);
})
);
};
}
export function updateCampaign(campaignId, data) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestUpdateCampaign());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns/' + campaignId, {
method: 'put',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: data
})
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveUpdateCampaign(json.result));
resolve(json);
})
);
};
}
export function fetchCampaign(campaignId) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestCampaign());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns/' + campaignId)
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveCampaign(json));
resolve(json);
}));
};
}
export function fetchCampaigns(accountId = null) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestCampaigns());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns' + '?account_id=' + accountId)
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveCampaigns(json));
resolve(json);
}));
};
} | front_end/src/actions/Campaigns/CampaignActions.js | import fetch from 'isomorphic-fetch';
let apiUrl;
if (typeof __DEVELOPMENT__ !== 'undefined' && __DEVELOPMENT__ === true) {
apiUrl = __DEVAPI__;
} else {
apiUrl = __LIVEAPI__;
}
export const REQUEST_CREATE_CAMPAIGN = 'REQUEST_CREATE_CAMPAIGN';
export const RECEIVE_CREATE_CAMPAIGN = 'RECEIVE_CREATE_CAMPAIGN';
export const REQUEST_UPDATE_CAMPAIGN = 'REQUEST_UPDATE_CAMPAIGN';
export const RECEIVE_UPDATE_CAMPAIGN = 'RECEIVE_UPDATE_CAMPAIGN';
export const REQUEST_CAMPAIGNS = 'REQUEST_CAMPAIGNS';
export const RECEIVE_CAMPAIGNS = 'RECEIVE_CAMPAIGNS';
export const REQUEST_CAMPAIGN = 'REQUEST_CAMPAIGN';
export const RECEIVE_CAMPAIGN = 'RECEIVE_CAMPAIGN';
export function requestCreateCampaign() {
return {type: REQUEST_CREATE_CAMPAIGN};
}
export function receiveCreateCampaign(json) {
return {
type: RECEIVE_CREATE_CAMPAIGN,
json: json
};
}
export function requestUpdateCampaign() {
return {type: REQUEST_UPDATE_CAMPAIGN};
}
export function receiveUpdateCampaign(json) {
return {
type: RECEIVE_UPDATE_CAMPAIGN,
json: json
};
}
export function requestCampaign() {
return {type: REQUEST_CAMPAIGN};
}
export function receiveCampaign(json) {
return {
type: RECEIVE_CAMPAIGN,
details: json
};
}
export function requestCampaigns() {
return {type: REQUEST_CAMPAIGNS};
}
export function receiveCampaigns(json) {
return {
type: RECEIVE_CAMPAIGNS,
rows: json
};
}
export function createCampaign(data) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestCreateCampaign());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: data
})
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveCreateCampaign(json));
resolve(json);
})
);
};
}
export function updateCampaign(campaignId, data) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestUpdateCampaign());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns/' + campaignId, {
method: 'put',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: data
})
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveUpdateCampaign(json.result));
resolve(json);
})
);
};
}
export function fetchCampaign(campaignId) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestCampaign());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns/' + campaignId)
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveCampaign(json));
resolve(json);
}));
};
}
export function fetchCampaigns(accountId = null) {
// thunk middleware knows how to handle functions
return function next(dispatch) {
dispatch(requestCampaigns());
// Return a promise to wait for
return fetch(apiUrl + '/api/campaigns' + '?account_id=' + accountId)
.then(response => response.json())
.then(json => new Promise(resolve => {
dispatch(receiveCampaigns(json));
resolve(json);
}));
};
} | Reorganized Actions and Reducers and tests 2
| front_end/src/actions/Campaigns/CampaignActions.js | Reorganized Actions and Reducers and tests 2 | <ide><path>ront_end/src/actions/Campaigns/CampaignActions.js
<ide> export function receiveCampaign(json) {
<ide> return {
<ide> type: RECEIVE_CAMPAIGN,
<del> details: json
<add> json: json
<ide> };
<ide> }
<ide>
<ide> export function receiveCampaigns(json) {
<ide> return {
<ide> type: RECEIVE_CAMPAIGNS,
<del> rows: json
<add> json: json
<ide> };
<ide> }
<ide> |
|
Java | apache-2.0 | 5d1499e91e6a4b92cca3db115cdbdf2469008b4c | 0 | bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.block;
import com.facebook.presto.tuple.Tuple;
import com.facebook.presto.tuple.TupleInfo;
import com.facebook.presto.tuple.TupleInfo.Type;
import com.google.common.base.Function;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import io.airlift.slice.Slice;
import org.testng.Assert;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static com.facebook.presto.block.BlockIterables.createBlockIterable;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public final class BlockAssertions
{
private BlockAssertions() {}
public static Object getOnlyValue(Block block)
{
assertEquals(block.getPositionCount(), 1, "Block positions");
BlockCursor cursor = block.cursor();
Assert.assertTrue(cursor.advanceNextPosition());
Object value = cursor.getTuple().getObjectValue();
Assert.assertFalse(cursor.advanceNextPosition());
return value;
}
public static void assertBlocksEquals(BlockIterable actual, BlockIterable expected)
{
Iterator<Block> expectedIterator = expected.iterator();
for (Block actualBlock : actual) {
assertTrue(expectedIterator.hasNext());
Block expectedBlock = expectedIterator.next();
assertBlockEquals(actualBlock, expectedBlock);
}
assertFalse(expectedIterator.hasNext());
}
public static List<Object> toValues(BlockIterable blocks)
{
List<Object> values = new ArrayList<>();
for (Block block : blocks) {
BlockCursor cursor = block.cursor();
while (cursor.advanceNextPosition()) {
values.add(cursor.getTuple().getObjectValue());
}
}
return Collections.unmodifiableList(values);
}
public static List<Object> toValues(Block block)
{
BlockCursor cursor = block.cursor();
return toValues(cursor);
}
public static List<Object> toValues(BlockCursor cursor)
{
List<Object> values = new ArrayList<>();
while (cursor.advanceNextPosition()) {
values.add(cursor.getTuple().getObjectValue());
}
return Collections.unmodifiableList(values);
}
public static void assertBlockEquals(Block actual, Block expected)
{
Assert.assertEquals(actual.getTupleInfo(), expected.getTupleInfo());
assertCursorsEquals(actual.cursor(), expected.cursor());
}
public static void assertCursorsEquals(BlockCursor actualCursor, BlockCursor expectedCursor)
{
Assert.assertEquals(actualCursor.getTupleInfo(), expectedCursor.getTupleInfo());
while (advanceAllCursorsToNextPosition(actualCursor, expectedCursor)) {
assertEquals(actualCursor.getTuple(), expectedCursor.getTuple());
}
assertTrue(actualCursor.isFinished());
assertTrue(expectedCursor.isFinished());
}
public static void assertBlockEqualsIgnoreOrder(Block actual, Block expected)
{
Assert.assertEquals(actual.getTupleInfo(), expected.getTupleInfo());
List<Tuple> actualTuples = toTuplesList(actual);
List<Tuple> expectedTuples = toTuplesList(expected);
assertEqualsIgnoreOrder(actualTuples, expectedTuples);
}
public static List<Tuple> toTuplesList(Block block)
{
ImmutableList.Builder<Tuple> tuples = ImmutableList.builder();
BlockCursor actualCursor = block.cursor();
while (actualCursor.advanceNextPosition()) {
tuples.add(actualCursor.getTuple());
}
return tuples.build();
}
public static boolean advanceAllCursorsToNextPosition(BlockCursor... cursors)
{
boolean allAdvanced = true;
for (BlockCursor cursor : cursors) {
allAdvanced = cursor.advanceNextPosition() && allAdvanced;
}
return allAdvanced;
}
public static Iterable<Long> createLongSequence(long start, long end)
{
return ContiguousSet.create(Range.closedOpen(start, end), DiscreteDomain.longs());
}
public static Iterable<Double> createDoubleSequence(long start, long end)
{
return Iterables.transform(createLongSequence(start, end), new Function<Long, Double>()
{
@Override
public Double apply(Long input)
{
return (double) input;
}
});
}
public static Iterable<String> createStringSequence(long start, long end)
{
return Iterables.transform(createLongSequence(start, end), new Function<Long, String>()
{
@Override
public String apply(Long input)
{
return String.valueOf(input);
}
});
}
public static Iterable<Long> createLongNullSequence(int count)
{
Long[] values = new Long[count];
Arrays.fill(values, null);
return Arrays.asList(values);
}
public static Iterable<Double> createDoubleNullSequence(int count)
{
Double[] values = new Double[count];
Arrays.fill(values, null);
return Arrays.asList(values);
}
public static Iterable<String> createStringNullSequence(int count)
{
String[] values = new String[count];
Arrays.fill(values, null);
return Arrays.asList(values);
}
public static Block createStringsBlock(String... values)
{
checkNotNull(values, "varargs 'values' is null");
return createStringsBlock(Arrays.asList(values));
}
public static Block createStringsBlock(Iterable<String> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_VARBINARY);
for (String value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value.getBytes(UTF_8));
}
}
return builder.build();
}
public static BlockIterable createStringsBlockIterable(@Nullable String... values)
{
return BlockIterables.createBlockIterable(createStringsBlock(values));
}
public static Block createStringSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_VARBINARY);
for (int i = start; i < end; i++) {
builder.append(String.valueOf(i));
}
return builder.build();
}
public static Block createBooleansBlock(Boolean... values)
{
checkNotNull(values, "varargs 'values' is null");
return createBooleansBlock(Arrays.asList(values));
}
public static Block createBooleansBlock(Boolean value, int count)
{
return createBooleansBlock(Collections.nCopies(count, value));
}
public static Block createBooleansBlock(Iterable<Boolean> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_BOOLEAN);
for (Boolean value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value);
}
}
return builder.build();
}
// This method makes it easy to create blocks without having to add an L to every value
public static Block createLongsBlock(int... values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_LONG);
for (int value : values) {
builder.append((long) value);
}
return builder.build();
}
public static Block createLongsBlock(Long... values)
{
checkNotNull(values, "varargs 'values' is null");
return createLongsBlock(Arrays.asList(values));
}
public static Block createLongsBlock(Iterable<Long> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_LONG);
for (Long value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value);
}
}
return builder.build();
}
public static BlockIterable createLongsBlockIterable(int... values)
{
return BlockIterables.createBlockIterable(createLongsBlock(values));
}
public static BlockIterable createLongsBlockIterable(@Nullable Long... values)
{
return BlockIterables.createBlockIterable(createLongsBlock(values));
}
public static Block createLongSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_LONG);
for (int i = start; i < end; i++) {
builder.append(i);
}
return builder.build();
}
public static Block createBooleanSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_BOOLEAN);
for (int i = start; i < end; i++) {
builder.append(i % 2 == 0);
}
return builder.build();
}
public static Block createDoublesBlock(Double... values)
{
checkNotNull(values, "varargs 'values' is null");
return createDoublesBlock(Arrays.asList(values));
}
public static Block createDoublesBlock(Iterable<Double> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_DOUBLE);
for (Double value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value);
}
}
return builder.build();
}
public static BlockIterable createDoublesBlockIterable(@Nullable Double... values)
{
return createBlockIterable(createDoublesBlock(values));
}
public static Block createDoubleSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_DOUBLE);
for (int i = start; i < end; i++) {
builder.append((double) i);
}
return builder.build();
}
public static BlockIterableBuilder blockIterableBuilder(Type type)
{
return new BlockIterableBuilder(new TupleInfo(type));
}
public static class BlockIterableBuilder
{
private final List<Block> blocks = new ArrayList<>();
private BlockBuilder blockBuilder;
private BlockIterableBuilder(TupleInfo tupleInfo)
{
blockBuilder = new BlockBuilder(tupleInfo);
}
public BlockIterableBuilder append(Tuple tuple)
{
blockBuilder.append(tuple);
return this;
}
public BlockIterableBuilder append(Slice value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder append(double value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder append(long value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder append(String value)
{
blockBuilder.append(value.getBytes(UTF_8));
return this;
}
public BlockIterableBuilder append(byte[] value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder appendNull()
{
blockBuilder.appendNull();
return this;
}
public BlockIterableBuilder newBlock()
{
if (!blockBuilder.isEmpty()) {
Block block = blockBuilder.build();
blocks.add(block);
blockBuilder = new BlockBuilder(block.getTupleInfo());
}
return this;
}
public BlockIterable build()
{
newBlock();
return createBlockIterable(blocks);
}
}
}
| presto-main/src/test/java/com/facebook/presto/block/BlockAssertions.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.block;
import com.facebook.presto.tuple.Tuple;
import com.facebook.presto.tuple.TupleInfo;
import com.facebook.presto.tuple.TupleInfo.Type;
import com.google.common.base.Function;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import io.airlift.slice.Slice;
import org.testng.Assert;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static com.facebook.presto.block.BlockIterables.createBlockIterable;
import static com.google.common.base.Charsets.UTF_8;
import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public final class BlockAssertions
{
private BlockAssertions() {}
public static Object getOnlyValue(Block block)
{
assertEquals(block.getPositionCount(), 1, "Block positions");
BlockCursor cursor = block.cursor();
Assert.assertTrue(cursor.advanceNextPosition());
Object value = cursor.getTuple().getObjectValue();
Assert.assertFalse(cursor.advanceNextPosition());
return value;
}
public static void assertBlocksEquals(BlockIterable actual, BlockIterable expected)
{
Iterator<Block> expectedIterator = expected.iterator();
for (Block actualBlock : actual) {
assertTrue(expectedIterator.hasNext());
Block expectedBlock = expectedIterator.next();
assertBlockEquals(actualBlock, expectedBlock);
}
assertFalse(expectedIterator.hasNext());
}
public static List<Object> toValues(BlockIterable blocks)
{
List<Object> values = new ArrayList<>();
for (Block block : blocks) {
BlockCursor cursor = block.cursor();
while (cursor.advanceNextPosition()) {
values.add(cursor.getTuple().getObjectValue());
}
}
return Collections.unmodifiableList(values);
}
public static List<Object> toValues(Block block)
{
BlockCursor cursor = block.cursor();
return toValues(cursor);
}
public static List<Object> toValues(BlockCursor cursor)
{
List<Object> values = new ArrayList<>();
while (cursor.advanceNextPosition()) {
values.add(cursor.getTuple().getObjectValue());
}
return Collections.unmodifiableList(values);
}
public static void assertBlockEquals(Block actual, Block expected)
{
Assert.assertEquals(actual.getTupleInfo(), expected.getTupleInfo());
assertCursorsEquals(actual.cursor(), expected.cursor());
}
public static void assertCursorsEquals(BlockCursor actualCursor, BlockCursor expectedCursor)
{
Assert.assertEquals(actualCursor.getTupleInfo(), expectedCursor.getTupleInfo());
while (advanceAllCursorsToNextPosition(actualCursor, expectedCursor)) {
assertEquals(actualCursor.getTuple(), expectedCursor.getTuple());
}
assertTrue(actualCursor.isFinished());
assertTrue(expectedCursor.isFinished());
}
public static void assertBlockEqualsIgnoreOrder(Block actual, Block expected)
{
Assert.assertEquals(actual.getTupleInfo(), expected.getTupleInfo());
List<Tuple> actualTuples = toTuplesList(actual);
List<Tuple> expectedTuples = toTuplesList(expected);
assertEqualsIgnoreOrder(actualTuples, expectedTuples);
}
public static List<Tuple> toTuplesList(Block block)
{
ImmutableList.Builder<Tuple> tuples = ImmutableList.builder();
BlockCursor actualCursor = block.cursor();
while (actualCursor.advanceNextPosition()) {
tuples.add(actualCursor.getTuple());
}
return tuples.build();
}
public static boolean advanceAllCursorsToNextPosition(BlockCursor... cursors)
{
boolean allAdvanced = true;
for (BlockCursor cursor : cursors) {
allAdvanced = cursor.advanceNextPosition() && allAdvanced;
}
return allAdvanced;
}
public static Iterable<Long> createLongSequence(long start, long end)
{
return ContiguousSet.create(Range.closedOpen(start, end), DiscreteDomain.longs());
}
public static Iterable<Double> createDoubleSequence(long start, long end)
{
return Iterables.transform(createLongSequence(start, end), new Function<Long, Double>()
{
@Override
public Double apply(Long input)
{
return (double) input;
}
});
}
public static Iterable<String> createStringSequence(long start, long end)
{
return Iterables.transform(createLongSequence(start, end), new Function<Long, String>()
{
@Override
public String apply(Long input)
{
return String.valueOf(input);
}
});
}
public static Iterable<Long> createLongNullSequence(int count)
{
Long[] values = new Long[count];
Arrays.fill(values, null);
return Arrays.asList(values);
}
public static Iterable<Double> createDoubleNullSequence(int count)
{
Double[] values = new Double[count];
Arrays.fill(values, null);
return Arrays.asList(values);
}
public static Iterable<String> createStringNullSequence(int count)
{
String[] values = new String[count];
Arrays.fill(values, null);
return Arrays.asList(values);
}
public static Block createStringsBlock(@Nullable String... values)
{
return createStringsBlock(Arrays.asList(values));
}
public static Block createStringsBlock(Iterable<String> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_VARBINARY);
for (String value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value.getBytes(UTF_8));
}
}
return builder.build();
}
public static BlockIterable createStringsBlockIterable(@Nullable String... values)
{
return BlockIterables.createBlockIterable(createStringsBlock(values));
}
public static Block createStringSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_VARBINARY);
for (int i = start; i < end; i++) {
builder.append(String.valueOf(i));
}
return builder.build();
}
public static Block createBooleansBlock(@Nullable Boolean... values)
{
return createBooleansBlock(Arrays.asList(values));
}
public static Block createBooleansBlock(Boolean value, int count)
{
return createBooleansBlock(Collections.nCopies(count, value));
}
public static Block createBooleansBlock(Iterable<Boolean> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_BOOLEAN);
for (Boolean value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value);
}
}
return builder.build();
}
// This method makes it easy to create blocks without having to add an L to every value
public static Block createLongsBlock(int... values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_LONG);
for (int value : values) {
builder.append((long) value);
}
return builder.build();
}
public static Block createLongsBlock(@Nullable Long... values)
{
return createLongsBlock(Arrays.asList(values));
}
public static Block createLongsBlock(Iterable<Long> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_LONG);
for (Long value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value);
}
}
return builder.build();
}
public static BlockIterable createLongsBlockIterable(int... values)
{
return BlockIterables.createBlockIterable(createLongsBlock(values));
}
public static BlockIterable createLongsBlockIterable(@Nullable Long... values)
{
return BlockIterables.createBlockIterable(createLongsBlock(values));
}
public static Block createLongSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_LONG);
for (int i = start; i < end; i++) {
builder.append(i);
}
return builder.build();
}
public static Block createBooleanSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_BOOLEAN);
for (int i = start; i < end; i++) {
builder.append(i % 2 == 0);
}
return builder.build();
}
public static Block createDoublesBlock(@Nullable Double... values)
{
return createDoublesBlock(Arrays.asList(values));
}
public static Block createDoublesBlock(Iterable<Double> values)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_DOUBLE);
for (Double value : values) {
if (value == null) {
builder.appendNull();
}
else {
builder.append(value);
}
}
return builder.build();
}
public static BlockIterable createDoublesBlockIterable(@Nullable Double... values)
{
return createBlockIterable(createDoublesBlock(values));
}
public static Block createDoubleSequenceBlock(int start, int end)
{
BlockBuilder builder = new BlockBuilder(TupleInfo.SINGLE_DOUBLE);
for (int i = start; i < end; i++) {
builder.append((double) i);
}
return builder.build();
}
public static BlockIterableBuilder blockIterableBuilder(Type type)
{
return new BlockIterableBuilder(new TupleInfo(type));
}
public static class BlockIterableBuilder
{
private final List<Block> blocks = new ArrayList<>();
private BlockBuilder blockBuilder;
private BlockIterableBuilder(TupleInfo tupleInfo)
{
blockBuilder = new BlockBuilder(tupleInfo);
}
public BlockIterableBuilder append(Tuple tuple)
{
blockBuilder.append(tuple);
return this;
}
public BlockIterableBuilder append(Slice value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder append(double value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder append(long value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder append(String value)
{
blockBuilder.append(value.getBytes(UTF_8));
return this;
}
public BlockIterableBuilder append(byte[] value)
{
blockBuilder.append(value);
return this;
}
public BlockIterableBuilder appendNull()
{
blockBuilder.appendNull();
return this;
}
public BlockIterableBuilder newBlock()
{
if (!blockBuilder.isEmpty()) {
Block block = blockBuilder.build();
blocks.add(block);
blockBuilder = new BlockBuilder(block.getTupleInfo());
}
return this;
}
public BlockIterable build()
{
newBlock();
return createBlockIterable(blocks);
}
}
}
| Add null checks to create*Block
Make the errors more explicit for calls like this, which do not do what the caller expects due to varargs semantics in Java:
createStringsBlock(null)
Also, remove the @Nullable annotation as it's ambiguous: does it refer to the varargs parameter or to each of the varargs elements.
| presto-main/src/test/java/com/facebook/presto/block/BlockAssertions.java | Add null checks to create*Block | <ide><path>resto-main/src/test/java/com/facebook/presto/block/BlockAssertions.java
<ide>
<ide> import static com.facebook.presto.block.BlockIterables.createBlockIterable;
<ide> import static com.google.common.base.Charsets.UTF_8;
<add>import static com.google.common.base.Preconditions.checkNotNull;
<ide> import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder;
<ide> import static org.testng.Assert.assertEquals;
<ide> import static org.testng.Assert.assertFalse;
<ide> return Arrays.asList(values);
<ide> }
<ide>
<del> public static Block createStringsBlock(@Nullable String... values)
<del> {
<add> public static Block createStringsBlock(String... values)
<add> {
<add> checkNotNull(values, "varargs 'values' is null");
<add>
<ide> return createStringsBlock(Arrays.asList(values));
<ide> }
<ide>
<ide> return builder.build();
<ide> }
<ide>
<del> public static Block createBooleansBlock(@Nullable Boolean... values)
<del> {
<add> public static Block createBooleansBlock(Boolean... values)
<add> {
<add> checkNotNull(values, "varargs 'values' is null");
<add>
<ide> return createBooleansBlock(Arrays.asList(values));
<ide> }
<ide>
<ide> return builder.build();
<ide> }
<ide>
<del> public static Block createLongsBlock(@Nullable Long... values)
<del> {
<add> public static Block createLongsBlock(Long... values)
<add> {
<add> checkNotNull(values, "varargs 'values' is null");
<add>
<ide> return createLongsBlock(Arrays.asList(values));
<ide> }
<ide>
<ide> return builder.build();
<ide> }
<ide>
<del> public static Block createDoublesBlock(@Nullable Double... values)
<del> {
<add> public static Block createDoublesBlock(Double... values)
<add> {
<add> checkNotNull(values, "varargs 'values' is null");
<add>
<ide> return createDoublesBlock(Arrays.asList(values));
<ide> }
<ide> |
|
Java | apache-2.0 | 9a3ce4159e8589353b9d3a306f9a6b9a7df4f246 | 0 | MartinMSPedersen/levelup-java-examples,wq19880601/java-util-examples,leveluplunch/levelup-java-examples,karlthepagan/levelup-java-examples | package com.levelup.java.guava;
import static org.junit.Assert.assertNotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* BiMap allows you have a set of entries that you can easily inverse the keys/values
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/examples/guava-bimap-example/'>Guava BiMap Example</a>
*/
public class BiMapExample {
private static final Logger logger = Logger.getLogger(BiMapExample.class);
@Test
public void bidirectional_map_with_guava () {
BiMap<String, String> dialectConverterForWisconsinites =
HashBiMap.create();
dialectConverterForWisconsinites.put("bratwurst", "brat");
dialectConverterForWisconsinites.put("drinking fountain", "bubbler");
dialectConverterForWisconsinites.put("that", "dat");
dialectConverterForWisconsinites.put("alright", "iet");
dialectConverterForWisconsinites.put("soda", "pop");
BiMap<String, String> dialectConverterForEveryoneElse = dialectConverterForWisconsinites.inverse();
logger.info(dialectConverterForEveryoneElse);
assertNotNull(dialectConverterForEveryoneElse.get("brat"));
}
@Test
public void bidirectional_map_with_java () {
Map<String,String> dialectConverterForWisconsinites = new HashMap<String,String>();
dialectConverterForWisconsinites.put("bratwurst", "brat");
dialectConverterForWisconsinites.put("drinking fountain", "bubbler");
dialectConverterForWisconsinites.put("that", "dat");
dialectConverterForWisconsinites.put("alright", "iet");
dialectConverterForWisconsinites.put("soda", "pop");
Map<String,String> dialectConverterForEveryoneElse = new HashMap<String,String>();
for (Entry<String,String> entry: dialectConverterForWisconsinites.entrySet()) {
dialectConverterForEveryoneElse.put(entry.getValue(), entry.getKey());
}
logger.info(dialectConverterForEveryoneElse);
assertNotNull(dialectConverterForEveryoneElse.get("brat"));
}
}
| src/test/java/com/levelup/java/guava/BiMapExample.java | package com.levelup.java.guava;
import static org.junit.Assert.assertNotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* BiMap allows you have a set of entries that you can easily inverse the keys/values
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/example/guava-bimap-example/'>Guava BiMap Example</a>
*/
public class BiMapExample {
private static final Logger logger = Logger.getLogger(BiMapExample.class);
@Test
public void bidirectional_map_with_guava () {
BiMap<String, String> dialectConverterForWisconsinites =
HashBiMap.create();
dialectConverterForWisconsinites.put("bratwurst", "brat");
dialectConverterForWisconsinites.put("drinking fountain", "bubbler");
dialectConverterForWisconsinites.put("that", "dat");
dialectConverterForWisconsinites.put("alright", "iet");
dialectConverterForWisconsinites.put("soda", "pop");
BiMap<String, String> dialectConverterForEveryoneElse = dialectConverterForWisconsinites.inverse();
logger.info(dialectConverterForEveryoneElse);
assertNotNull(dialectConverterForEveryoneElse.get("brat"));
}
@Test
public void bidirectional_map_with_java () {
Map<String,String> dialectConverterForWisconsinites = new HashMap<String,String>();
dialectConverterForWisconsinites.put("bratwurst", "brat");
dialectConverterForWisconsinites.put("drinking fountain", "bubbler");
dialectConverterForWisconsinites.put("that", "dat");
dialectConverterForWisconsinites.put("alright", "iet");
dialectConverterForWisconsinites.put("soda", "pop");
Map<String,String> dialectConverterForEveryoneElse = new HashMap<String,String>();
for (Entry<String,String> entry: dialectConverterForWisconsinites.entrySet()) {
dialectConverterForEveryoneElse.put(entry.getValue(), entry.getKey());
}
logger.info(dialectConverterForEveryoneElse);
assertNotNull(dialectConverterForEveryoneElse.get("brat"));
}
}
| fix url
| src/test/java/com/levelup/java/guava/BiMapExample.java | fix url | <ide><path>rc/test/java/com/levelup/java/guava/BiMapExample.java
<ide> * BiMap allows you have a set of entries that you can easily inverse the keys/values
<ide> *
<ide> * @author Justin Musgrove
<del> * @see <a href='http://www.leveluplunch.com/java/example/guava-bimap-example/'>Guava BiMap Example</a>
<add> * @see <a href='http://www.leveluplunch.com/java/examples/guava-bimap-example/'>Guava BiMap Example</a>
<ide> */
<ide> public class BiMapExample {
<ide> |
|
JavaScript | mit | 3fdd1bc3167b6df20ba2461ff0216f76b44dfab6 | 0 | mattyhead/retro-games,maryrosecook/retro-games,mattyhead/retro-games | ;(function() {
var BLOCK_SIZE = 10;
var Game = function(canvasId) {
var screen = document.getElementById(canvasId).getContext('2d');
this.size = { x: screen.canvas.width, y: screen.canvas.height };
this.center = { x: this.size.x / 2, y: this.size.y / 2 };
this.bodies = createWalls(this)
this.bodies = this.bodies.concat(new FoodBlock(this));
this.player = new Player(this);
var self = this;
var tick = function() {
self.update();
self.draw(screen);
requestAnimationFrame(tick);
};
tick();
};
Game.prototype = {
update: function() {
this.player.update();
reportCollisions(this.bodies);
},
draw: function(screen) {
screen.clearRect(0, 0, this.size.x, this.size.y);
for (var i = 0; i < this.bodies.length; i++) {
this.bodies[i].draw(screen);
}
},
addBody: function(body) {
this.bodies.push(body);
},
removeBody: function(body) {
var bodyIndex = this.bodies.indexOf(body);
if (bodyIndex !== -1) {
this.bodies.splice(bodyIndex, 1);
}
},
isSquareFree: function(center) {
return this.bodies.filter(function(b) {
return colliding(b, { center: center });
}).length === 0;
},
randomSquare: function() {
return {
x: Math.floor(this.size.x / BLOCK_SIZE * Math.random()) * BLOCK_SIZE + BLOCK_SIZE / 2,
y: Math.floor(this.size.y / BLOCK_SIZE * Math.random()) * BLOCK_SIZE + BLOCK_SIZE / 2
};
}
};
var WallBlock = function(game, center) {
this.game = game;
this.center = center;
this.size = { x: BLOCK_SIZE, y: BLOCK_SIZE };
};
WallBlock.prototype = {
draw: function(screen) {
drawRect(screen, this, "black");
}
};
var FoodBlock = function(game) {
this.game = game;
while (this.center === undefined) {
var center = this.game.randomSquare();
if (this.game.isSquareFree(center)) {
this.center = center;
}
}
this.size = { x: BLOCK_SIZE, y: BLOCK_SIZE };
};
FoodBlock.prototype = {
draw: function(screen) {
drawRect(screen, this, "green");
},
collision: function(otherBody) {
if (otherBody instanceof SnakeBlock) {
this.game.removeBody(this);
}
}
};
var SnakeBlock = function(game, player, center, direction) {
this.game = game;
this.player = player;
this.center = center;
this.size = { x: BLOCK_SIZE, y: BLOCK_SIZE };
this.direction = direction;
};
SnakeBlock.prototype = {
draw: function(screen) {
drawRect(screen, this, "black");
},
collision: function(otherBody) {
if (otherBody instanceof WallBlock || otherBody instanceof SnakeBlock) {
this.player.die();
} else if (otherBody instanceof FoodBlock) {
this.player.eat(otherBody);
}
}
};
var Player = function(game) {
this.game = game;
this.keyboarder = new Keyboarder();
var head = new SnakeBlock(this.game,
this,
{ x: this.game.center.x, y: this.game.center.y },
{ x: 1, y: 0 });
this.game.addBody(head);
this.blocks = [head];
this.lastMove = 0;
};
Player.prototype = {
update: function() {
this.handleKeyboard();
var now = new Date().getTime();
if (now > this.lastMove + 100) {
this.move();
this.lastMove = now;
}
},
move: function() {
var head = this.blocks[0];
moveBlock(head, head.direction);
var prevBlock = head;
for (var i = 1; i < this.blocks.length; i++) {
moveBlock(this.blocks[i], prevBlock.direction);
prevBlock = this.blocks[i];
}
},
handleKeyboard: function() {
var head = this.blocks[0];
if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT) &&
head.direction.x !== 1) {
head.direction.x = -1;
head.direction.y = 0;
} else if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT) &&
head.direction.x !== -1) {
head.direction.x = 1;
head.direction.y = 0;
}
if (this.keyboarder.isDown(this.keyboarder.KEYS.UP) &&
head.direction.y !== 1) {
head.direction.y = -1;
head.direction.x = 0;
} else if (this.keyboarder.isDown(this.keyboarder.KEYS.DOWN) &&
head.direction.y !== -1) {
head.direction.y = 1;
head.direction.x = 0;
}
},
eat: function(foodBlock) {
},
die: function() {
for (var i = 0; i < this.blocks.length; i++) {
this.game.removeBody(this.blocks[i]);
}
}
};
var moveBlock = function(block, direction) {
block.center.x += direction.x * BLOCK_SIZE;
block.center.y += direction.y * BLOCK_SIZE;
};
var Keyboarder = function() {
var keyState = {};
window.addEventListener('keydown', function(e) {
keyState[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
keyState[e.keyCode] = false;
});
this.isDown = function(keyCode) {
return keyState[keyCode] === true;
};
this.KEYS = { LEFT: 37, RIGHT: 39, UP: 38, DOWN: 40 };
};
var colliding = function(b1, b2) {
return b1 !== b2 &&
b1.center.x === b2.center.x && b1.center.y === b2.center.y;
};
var reportCollisions = function(bodies) {
var collisions = [];
for (var i = 0; i < bodies.length; i++) {
for (var j = i + 1; j < bodies.length; j++) {
if (colliding(bodies[i], bodies[j])) {
collisions.push([bodies[i], bodies[j]]);
}
}
}
for (var i = 0; i < collisions.length; i++) {
if (collisions[i][0].collision !== undefined) {
collisions[i][0].collision(collisions[i][1]);
}
if (collisions[i][1].collision !== undefined) {
collisions[i][1].collision(collisions[i][0]);
}
}
};
var createWalls = function(game) {
var walls = [];
// top
for (var x = BLOCK_SIZE / 2; x < game.size.x; x += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: x, y: BLOCK_SIZE / 2 }));
}
// left
for (var y = BLOCK_SIZE / 2 + BLOCK_SIZE; y < game.size.y - BLOCK_SIZE; y += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: BLOCK_SIZE / 2, y: y }));
}
// right
for (var y = BLOCK_SIZE / 2 + BLOCK_SIZE; y < game.size.y - BLOCK_SIZE; y += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: game.size.x - BLOCK_SIZE / 2, y: y }));
}
// bottom
for (var x = BLOCK_SIZE / 2; x < game.size.x; x += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: x, y: game.size.y - BLOCK_SIZE / 2 }));
}
return walls;
};
var drawRect = function(screen, body, color) {
screen.fillStyle = color;
screen.fillRect(body.center.x - body.size.x / 2, body.center.y - body.size.y / 2,
body.size.x, body.size.y);
};
window.addEventListener('load', function() {
new Game("screen");
});
})(this);
| snake/snake.js | ;(function() {
var BLOCK_SIZE = 10;
var Game = function(canvasId) {
var screen = document.getElementById(canvasId).getContext('2d');
this.size = { x: screen.canvas.width, y: screen.canvas.height };
this.center = { x: this.size.x / 2, y: this.size.y / 2 };
this.bodies = createWalls(this)
this.bodies = this.bodies.concat(new FoodBlock(this));
this.player = new Player(this);
var self = this;
var tick = function() {
self.update();
self.draw(screen);
requestAnimationFrame(tick);
};
tick();
};
Game.prototype = {
update: function() {
this.player.update();
reportCollisions(this.bodies);
},
draw: function(screen) {
screen.clearRect(0, 0, this.size.x, this.size.y);
for (var i = 0; i < this.bodies.length; i++) {
this.bodies[i].draw(screen);
}
},
addBody: function(body) {
this.bodies.push(body);
},
removeBody: function(body) {
var bodyIndex = this.bodies.indexOf(body);
if (bodyIndex !== -1) {
this.bodies.splice(bodyIndex, 1);
}
},
isSquareFree: function(center) {
return this.bodies.filter(function(b) {
return colliding(b, { center: center });
}).length === 0;
},
randomSquare: function() {
return {
x: Math.floor(this.size.x / BLOCK_SIZE * Math.random()) * BLOCK_SIZE + BLOCK_SIZE / 2,
y: Math.floor(this.size.y / BLOCK_SIZE * Math.random()) * BLOCK_SIZE + BLOCK_SIZE / 2
};
}
};
var WallBlock = function(game, center) {
this.game = game;
this.center = center;
this.size = { x: BLOCK_SIZE, y: BLOCK_SIZE };
};
WallBlock.prototype = {
draw: function(screen) {
drawRect(screen, this, "black");
}
};
var FoodBlock = function(game) {
this.game = game;
while (this.center === undefined) {
var center = this.game.randomSquare();
if (this.game.isSquareFree(center)) {
this.center = center;
}
}
this.size = { x: BLOCK_SIZE, y: BLOCK_SIZE };
};
FoodBlock.prototype = {
draw: function(screen) {
drawRect(screen, this, "green");
}
};
var SnakeBlock = function(game, player, center, direction) {
this.game = game;
this.player = player;
this.center = center;
this.size = { x: BLOCK_SIZE, y: BLOCK_SIZE };
this.direction = direction;
};
SnakeBlock.prototype = {
draw: function(screen) {
drawRect(screen, this, "black");
},
collision: function(otherBody) {
if (otherBody instanceof WallBlock || otherBody instanceof SnakeBlock) {
this.player.die();
} else if (otherBody instanceof FoodBlock) {
this.player.eat(otherBody);
}
}
};
var Player = function(game) {
this.game = game;
this.keyboarder = new Keyboarder();
var head = new SnakeBlock(this.game,
this,
{ x: this.game.center.x, y: this.game.center.y },
{ x: 1, y: 0 });
this.game.addBody(head);
this.blocks = [head];
this.lastMove = 0;
};
Player.prototype = {
update: function() {
this.handleKeyboard();
var now = new Date().getTime();
if (now > this.lastMove + 100) {
this.move();
this.lastMove = now;
}
},
move: function() {
var head = this.blocks[0];
moveBlock(head, head.direction);
var prevBlock = head;
for (var i = 1; i < this.blocks.length; i++) {
moveBlock(this.blocks[i], prevBlock.direction);
prevBlock = this.blocks[i];
}
},
handleKeyboard: function() {
var head = this.blocks[0];
if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT) &&
head.direction.x !== 1) {
head.direction.x = -1;
head.direction.y = 0;
} else if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT) &&
head.direction.x !== -1) {
head.direction.x = 1;
head.direction.y = 0;
}
if (this.keyboarder.isDown(this.keyboarder.KEYS.UP) &&
head.direction.y !== 1) {
head.direction.y = -1;
head.direction.x = 0;
} else if (this.keyboarder.isDown(this.keyboarder.KEYS.DOWN) &&
head.direction.y !== -1) {
head.direction.y = 1;
head.direction.x = 0;
}
},
eat: function(foodBlock) {
},
die: function() {
for (var i = 0; i < this.blocks.length; i++) {
this.game.removeBody(this.blocks[i]);
}
}
};
var moveBlock = function(block, direction) {
block.center.x += direction.x * BLOCK_SIZE;
block.center.y += direction.y * BLOCK_SIZE;
};
var Keyboarder = function() {
var keyState = {};
window.addEventListener('keydown', function(e) {
keyState[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
keyState[e.keyCode] = false;
});
this.isDown = function(keyCode) {
return keyState[keyCode] === true;
};
this.KEYS = { LEFT: 37, RIGHT: 39, UP: 38, DOWN: 40 };
};
var colliding = function(b1, b2) {
return b1 !== b2 &&
b1.center.x === b2.center.x && b1.center.y === b2.center.y;
};
var reportCollisions = function(bodies) {
var collisions = [];
for (var i = 0; i < bodies.length; i++) {
for (var j = i + 1; j < bodies.length; j++) {
if (colliding(bodies[i], bodies[j])) {
collisions.push([bodies[i], bodies[j]]);
}
}
}
for (var i = 0; i < collisions.length; i++) {
if (collisions[i][0].collision !== undefined) {
collisions[i][0].collision(collisions[i][1]);
}
if (collisions[i][1].collision !== undefined) {
collisions[i][1].collision(collisions[i][0]);
}
}
};
var createWalls = function(game) {
var walls = [];
// top
for (var x = BLOCK_SIZE / 2; x < game.size.x; x += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: x, y: BLOCK_SIZE / 2 }));
}
// left
for (var y = BLOCK_SIZE / 2 + BLOCK_SIZE; y < game.size.y - BLOCK_SIZE; y += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: BLOCK_SIZE / 2, y: y }));
}
// right
for (var y = BLOCK_SIZE / 2 + BLOCK_SIZE; y < game.size.y - BLOCK_SIZE; y += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: game.size.x - BLOCK_SIZE / 2, y: y }));
}
// bottom
for (var x = BLOCK_SIZE / 2; x < game.size.x; x += BLOCK_SIZE) {
walls.push(new WallBlock(game, { x: x, y: game.size.y - BLOCK_SIZE / 2 }));
}
return walls;
};
var drawRect = function(screen, body, color) {
screen.fillStyle = color;
screen.fillRect(body.center.x - body.size.x / 2, body.center.y - body.size.y / 2,
body.size.x, body.size.y);
};
window.addEventListener('load', function() {
new Game("screen");
});
})(this);
| Allow eating of food | snake/snake.js | Allow eating of food | <ide><path>nake/snake.js
<ide> FoodBlock.prototype = {
<ide> draw: function(screen) {
<ide> drawRect(screen, this, "green");
<add> },
<add>
<add> collision: function(otherBody) {
<add> if (otherBody instanceof SnakeBlock) {
<add> this.game.removeBody(this);
<add> }
<ide> }
<ide> };
<ide> |
|
JavaScript | mit | 1b7fece9f50cc6c3856b6d2dca2c7206d2c12047 | 0 | valentingalea/vinyl-shelf-finder,valentingalea/vinyl-shelf-finder,valentingalea/vinyl-shelf-finder | //
// Config
//
const UserAgent = 'vinyl-shelf-finder/1.0';
const User = 'valentingalea';
const ALL = 0; // id of main folder
const thumb_size = 150;
const max_results = 10;
const port = 8080;
//
// Debug
//
const stringifyObject = require('stringify-object');
function pretty(data) {
return "<pre>" + stringifyObject(data) + "</pre>";
}
//
// Discogs API
//
var Discogs = require('disconnect').Client;
var db = new Discogs(UserAgent).database();
var my_col = new Discogs(UserAgent).user().collection();
var json_col = [];
var total_count = 0;
//
// Discogs requests cache
//
console.log("Loading cache...");
var flatCache = require('flat-cache');
const cache_file = 'discogs';
function get_cache_dir() {
return __dirname + '/cache/';
}
function init_cache() {
return flatCache.load(cache_file, get_cache_dir());
}
var cache = init_cache();
//
// Search
//
var fuseJs = require("fuse.js");
var searcher = undefined;
function init_search() {
console.log("Indexing...");
var options = {
keys: [ 'basic_information.title', 'basic_information.artists.name' ],
threshold: 0.15
};
searcher = new fuseJs(json_col, options);
}
//
// Express REST server
//
var express = require('express');
var app = express();
function get_pub_dir() {
return __dirname + '/public/';
}
app.use(express.static(get_pub_dir()));
var fs = require('fs');
var request = require('request');
// always have this ready
const templ_file = fs.readFileSync(get_pub_dir() + 'results.template.html', 'utf8');
app.get('/', function (req, res) {
res.sendFile('index.html', { root: get_pub_dir() });
});
app.get('/search', function (req, res) {
console.log("Search request: " + req.query.q);
var found = [];
if (!req.query.q || req.query.q === "") {
// if not search string, get a random one
var index = Math.round(Math.random() * total_count);
found = [ json_col[index] ];
} else {
// special search commands
if (req.query.q.indexOf('shelf:') > -1 || req.query.q.indexOf('s:') > -1) {
var shelf_id = req.query.q.split(':')[1];
for (var i = 0; i < json_col.length; i++) {
var entry = json_col[i];
if (typeof entry.notes === 'undefined') {
console.log(`Warning: found entry with no shelf info: ${entry.id} (${entry.basic_information.title})`);
continue;
}
var id_def = entry.notes.filter(function (n) { return n.field_id == 3; });
if (id_def.length > 0) {
var id = parseInt(id_def[0].value, 10);
if (id == shelf_id) {
found.push(entry);
}
}
}
// sort by left to right order in
// the fields are guaranteed to be there because we just constructed this
found.sort(function (a, b) {
var f = function (n) { return n.field_id == 4; };
var _a = a.notes.filter(f)[0];
var _b = b.notes.filter(f)[0];
return parseInt(_a.value) - parseInt(_b.value);
});
} else {
// normal string search
found = searcher.search(req.query.q);
}
}
var send_release_to_client = function (input, entry) {
var html = input;
html = html.replace("${size}", thumb_size);
html = html.replace('${entry.title}', entry.basic_information.title);
html = html.replace("${entry.artists}", entry.basic_information.artists[0].name);
html = html.replace("${entry.cover}", entry.basic_information.cover_image);
html = html.replace("${btn.find}", "https://www.discogs.com/release/" + entry.id);
html = html.replace("${btn.play}", entry.id);
return html;
};
var prepare_cover_img = function (entry) {
var id = entry.id;
var img_local = "img_cache/" + id + ".jpg";
var img_file_name = get_pub_dir() + img_local;
if (fs.existsSync(img_file_name)) {
entry.basic_information.cover_image = img_local;
} else {
console.log("Caching cover image for release " + id + "...");
var options = {
url: entry.basic_information.cover_image,
headers: {
'User-Agent': UserAgent
}
};
try {
request(options).pipe(fs.createWriteStream(img_file_name));
} catch (err) {
console.log("Download failed: " + err);
}
};
};
var client_str = "";
for (var i = 0; i < found.length; i++) {
prepare_cover_img(found[i]);
client_str += send_release_to_client(templ_file, found[i]);
// cut short to not overload with requests
// TODO: pagination support
if (i > max_results) break;
}
res.send(client_str);
});
app.get('/all', function (req, res) {
res.send(pretty(json_col));
});
app.get('/test', function (req, res) {
res.send(UserAgent);
});
app.get('/detail/:id(\\d+)', function (req, res) {
db.getRelease(req.params.id, function(err, data){
if (err) {
es.send(pretty(err));
return;
}
res.send(pretty(data));
});
});
app.get('/play/:id(\\d+)', function (req, res) {
db.getRelease(req.params.id, function(err, data){
if (err) {
res.send(pretty(err));
return;
}
// from https://stackoverflow.com/a/17098372/5760
var parse_duration = function (str) {
var parts = str.match(/^(\d*:)?(\d*)$/);
if (parts) {
var min = parseInt(parts[1], 10) || 0;
var sec = parseInt(parts[2], 10) || 0;
return min * 60 + sec;
} else {
return 0;
}
};
var main_artist = data.artists[0].name;
var main_album = data.title;
var track_data = data.tracklist;
var tracklist = [];
var play_time = Math.floor(Date.now() / 1000);
for (var i = 0; i < track_data.length; i++) {
var t = track_data[i];
if ((t.position === '') || (t.type_ != 'track')) continue;
// https://www.last.fm/api/show/track.scrobble
var track_scrobble = {
artist: (typeof t.artists === "undefined" ?
main_artist :
t.artists[0].name),
track: t.title,
timestamp: play_time,
album: main_album,
trackNumber: t.position
};
play_time += parse_duration(t.duration);
tracklist.push(track_scrobble);
}
var side = function (S) {
return tracklist.filter(function (i) {
return i.trackNumber.indexOf(S) >= 0;
});
};
var radio_data = [
{ label: 'All tracks', data: tracklist, value: '*' },
{ label: 'Side A', data: side('A'), value: 'A' },
{ label: 'Side B', data: side('B'), value: 'B' },
{ label: 'Side C', data: side('C'), value: 'C' },
{ label: 'Side D', data: side('D'), value: 'D' },
{ label: 'Track...', data: [{}], value: '?'}
];
var client_str = '<div class="btn-group" data-toggle="buttons">';
var radio_item = function (label, value, is_selected) {
var active = is_selected ? 'active' : '';
var checked = is_selected ? 'checked' : '';
return `<label class="btn btn-secondary ${active}">
<input type="radio" value="${value} ${checked}" autocomplete="off">${label}
</label>`;
};
for (var i = 0; i < radio_data.length; i++) {
var s = radio_data[i];
if (s.data.length > 0) {
client_str += radio_item(s.label, s.value, i === 0);
}
}
client_str += '</div>';
client_str += '<br><br><ol class="list-group">';
for (var i = 0; i < tracklist.length; i++) {
client_str += `<li class="list-group-item">${tracklist[i].track}</li>`;
}
client_str += '<ol>';
res.send(client_str);
});
});
//
// Main
//
console.log("Starting...");
var get_folder = my_col.getFolder(User, ALL);
const page_items = 100; // max API limit is 100
var page_count = 0;
var page_iter = 1;
function get_page(n) {
if (typeof cache.getKey(n) === "undefined") {
process.stdout.write('Downloading page ' + n + '...');
return my_col.getReleases(User, ALL, { page: n, per_page: page_items });
} else {
process.stdout.write('Readback cached page ' + n + '...');
return new Promise(function (resolve, reject) {
return resolve(cache.getKey(n));
});
}
}
function start_server(){
app.listen(port, function () {
console.log('Listening on ' + port + '...');
});
}
function async_loop() {
if (page_iter <= page_count) {
return get_page(page_iter).then(function (data) {
console.log("done");
var old_data = cache.getKey(page_iter);
if (typeof old_data === "undefined") {
cache.setKey(page_iter, data);
cache.save({noPrune: true});
console.log("Cached page " + page_iter);
}
json_col = json_col.concat(data.releases);
page_iter++;
async_loop();
}, function (err) {
console.log("During async_loop: " + err);
});
} else {
init_search();
start_server();
}
};
function get_cached_count() {
var old_count = cache.getKey('count');
if (typeof old_count === "undefined") {
return 0;
} else {
return old_count;
}
}
function start_loading() {
page_count = Math.round(total_count / page_items);
console.log("Found " + total_count + " records, retrieving all in " + page_count + " steps...");
async_loop();
}
// build the collection & then start server
get_folder
.then(function (data){
total_count = data.count;
var old_count = get_cached_count();
if (old_count != total_count) {
console.log("Cache invalidated!");
cache.destroy();
cache = init_cache();
//TODO: this is not ideal as it can corrupt the cache
// if the later retrievals fail
cache.setKey('count', total_count);
cache.save({noPrune: true});
}
start_loading();
}, function(err) {
console.log("discogs.getFolder failed: " + err);
if (get_cached_count() > 0) {
console.log("Offline mode!");
total_count = get_cached_count();
start_loading();
}
}); | app/app.js | //
// Config
//
const UserAgent = 'vinyl-shelf-finder/1.0';
const User = 'valentingalea';
const ALL = 0; // id of main folder
const thumb_size = 150;
const max_results = 10;
const port = 8080;
//
// Debug
//
const stringifyObject = require('stringify-object');
function pretty(data) {
return "<pre>" + stringifyObject(data) + "</pre>";
}
//
// Discogs API
//
var Discogs = require('disconnect').Client;
var db = new Discogs(UserAgent).database();
var my_col = new Discogs(UserAgent).user().collection();
var json_col = [];
var total_count = 0;
//
// Discogs requests cache
//
console.log("Loading cache...");
var flatCache = require('flat-cache');
const cache_file = 'discogs';
function get_cache_dir() {
return __dirname + '/cache/';
}
function init_cache() {
return flatCache.load(cache_file, get_cache_dir());
}
var cache = init_cache();
//
// Search
//
var fuseJs = require("fuse.js");
var searcher = undefined;
function init_search() {
console.log("Indexing...");
var options = {
keys: [ 'basic_information.title', 'basic_information.artists.name' ],
threshold: 0.15
};
searcher = new fuseJs(json_col, options);
}
//
// Express REST server
//
var express = require('express');
var app = express();
function get_pub_dir() {
return __dirname + '/public/';
}
app.use(express.static(get_pub_dir()));
var fs = require('fs');
var request = require('request');
// always have this ready
const templ_file = fs.readFileSync(get_pub_dir() + 'results.template.html', 'utf8');
app.get('/', function (req, res) {
res.sendFile('index.html', { root: get_pub_dir() });
});
app.get('/search', function (req, res) {
console.log("Search request: " + req.query.q);
var found = undefined;
if (!req.query.q || req.query.q === "") {
var index = Math.round(Math.random() * total_count);
found = [ json_col[index] ];
} else {
found = searcher.search(req.query.q);
}
var send_release_to_client = function (input, entry) {
var html = input;
html = html.replace("${size}", thumb_size);
html = html.replace('${entry.title}', entry.basic_information.title);
html = html.replace("${entry.artists}", entry.basic_information.artists[0].name);
html = html.replace("${entry.cover}", entry.basic_information.cover_image);
html = html.replace("${btn.find}", "https://www.discogs.com/release/" + entry.id);
html = html.replace("${btn.play}", entry.id);
return html;
};
var prepare_cover_img = function (entry) {
var id = entry.id;
var img_local = "img_cache/" + id + ".jpg";
var img_file_name = get_pub_dir() + img_local;
if (fs.existsSync(img_file_name)) {
entry.basic_information.cover_image = img_local;
} else {
console.log("Caching cover image for release " + id + "...");
var options = {
url: entry.basic_information.cover_image,
headers: {
'User-Agent': UserAgent
}
};
try {
request(options).pipe(fs.createWriteStream(img_file_name));
} catch (err) {
console.log("Download failed: " + err);
}
};
};
var client_str = "";
for (var i = 0; i < found.length; i++) {
prepare_cover_img(found[i]);
client_str += send_release_to_client(templ_file, found[i]);
// cut short to not overload with requests
// TODO: pagination support
if (i > max_results) break;
}
res.send(client_str);
});
app.get('/all', function (req, res) {
res.send(pretty(json_col));
});
app.get('/test', function (req, res) {
res.send(UserAgent);
});
app.get('/detail/:id(\\d+)', function (req, res) {
db.getRelease(req.params.id, function(err, data){
if (err) {
es.send(pretty(err));
return;
}
res.send(pretty(data));
});
});
app.get('/play/:id(\\d+)', function (req, res) {
db.getRelease(req.params.id, function(err, data){
if (err) {
res.send(pretty(err));
return;
}
// from https://stackoverflow.com/a/17098372/5760
var parse_duration = function (str) {
var parts = str.match(/^(\d*:)?(\d*)$/);
if (parts) {
var min = parseInt(parts[1], 10) || 0;
var sec = parseInt(parts[2], 10) || 0;
return min * 60 + sec;
} else {
return 0;
}
};
var main_artist = data.artists[0].name;
var main_album = data.title;
var track_data = data.tracklist;
var tracklist = [];
var play_time = Math.floor(Date.now() / 1000);
for (var i = 0; i < track_data.length; i++) {
var t = track_data[i];
if ((t.position === '') || (t.type_ != 'track')) continue;
// https://www.last.fm/api/show/track.scrobble
var track_scrobble = {
artist: (typeof t.artists === "undefined" ?
main_artist :
t.artists[0].name),
track: t.title,
timestamp: play_time,
album: main_album,
trackNumber: t.position
};
play_time += parse_duration(t.duration);
tracklist.push(track_scrobble);
}
var side = function (S) {
return tracklist.filter(function (i) {
return i.trackNumber.indexOf(S) >= 0;
});
};
var radio_data = [
{ label: 'All tracks', data: tracklist, value: '*' },
{ label: 'Side A', data: side('A'), value: 'A' },
{ label: 'Side B', data: side('B'), value: 'B' },
{ label: 'Side C', data: side('C'), value: 'C' },
{ label: 'Side D', data: side('D'), value: 'D' },
{ label: 'Track...', data: [{}], value: '?'}
];
var client_str = '<div class="btn-group" data-toggle="buttons">';
var radio_item = function (label, value, is_selected) {
var active = is_selected ? 'active' : '';
var checked = is_selected ? 'checked' : '';
return `<label class="btn btn-secondary ${active}">
<input type="radio" value="${value} ${checked}" autocomplete="off">${label}
</label>`;
};
for (var i = 0; i < radio_data.length; i++) {
var s = radio_data[i];
if (s.data.length > 0) {
client_str += radio_item(s.label, s.value, i === 0);
}
}
client_str += '</div>';
client_str += '<br><br><ol class="list-group">';
for (var i = 0; i < tracklist.length; i++) {
client_str += `<li class="list-group-item">${tracklist[i].track}</li>`;
}
client_str += '<ol>';
res.send(client_str);
});
});
//
// Main
//
console.log("Starting...");
var get_folder = my_col.getFolder(User, ALL);
const page_items = 100; // max API limit is 100
var page_count = 0;
var page_iter = 1;
function get_page(n) {
if (typeof cache.getKey(n) === "undefined") {
process.stdout.write('Downloading page ' + n + '...');
return my_col.getReleases(User, ALL, { page: n, per_page: page_items });
} else {
process.stdout.write('Readback cached page ' + n + '...');
return new Promise(function (resolve, reject) {
return resolve(cache.getKey(n));
});
}
}
function start_server(){
app.listen(port, function () {
console.log('Listening on ' + port + '...');
});
}
function async_loop() {
if (page_iter <= page_count) {
return get_page(page_iter).then(function (data) {
console.log("done");
var old_data = cache.getKey(page_iter);
if (typeof old_data === "undefined") {
cache.setKey(page_iter, data);
cache.save({noPrune: true});
console.log("Cached page " + page_iter);
}
json_col = json_col.concat(data.releases);
page_iter++;
async_loop();
}, function (err) {
console.log("During async_loop: " + err);
});
} else {
init_search();
start_server();
}
};
function get_cached_count() {
var old_count = cache.getKey('count');
if (typeof old_count === "undefined") {
return 0;
} else {
return old_count;
}
}
function start_loading() {
page_count = Math.round(total_count / page_items);
console.log("Found " + total_count + " records, retrieving all in " + page_count + " steps...");
async_loop();
}
// build the collection & then start server
get_folder
.then(function (data){
total_count = data.count;
var old_count = get_cached_count();
if (old_count != total_count) {
console.log("Cache invalidated!");
cache.destroy();
cache = init_cache();
//TODO: this is not ideal as it can corrupt the cache
// if the later retrievals fail
cache.setKey('count', total_count);
cache.save({noPrune: true});
}
start_loading();
}, function(err) {
console.log("discogs.getFolder failed: " + err);
if (get_cached_count() > 0) {
console.log("Offline mode!");
total_count = get_cached_count();
start_loading();
}
}); | special search method by shelf id
| app/app.js | special search method by shelf id | <ide><path>pp/app.js
<ide> app.get('/search', function (req, res) {
<ide> console.log("Search request: " + req.query.q);
<ide>
<del> var found = undefined;
<add> var found = [];
<ide> if (!req.query.q || req.query.q === "") {
<add> // if not search string, get a random one
<ide> var index = Math.round(Math.random() * total_count);
<ide> found = [ json_col[index] ];
<ide> } else {
<del> found = searcher.search(req.query.q);
<add> // special search commands
<add> if (req.query.q.indexOf('shelf:') > -1 || req.query.q.indexOf('s:') > -1) {
<add> var shelf_id = req.query.q.split(':')[1];
<add>
<add> for (var i = 0; i < json_col.length; i++) {
<add> var entry = json_col[i];
<add> if (typeof entry.notes === 'undefined') {
<add> console.log(`Warning: found entry with no shelf info: ${entry.id} (${entry.basic_information.title})`);
<add> continue;
<add> }
<add>
<add> var id_def = entry.notes.filter(function (n) { return n.field_id == 3; });
<add> if (id_def.length > 0) {
<add> var id = parseInt(id_def[0].value, 10);
<add> if (id == shelf_id) {
<add> found.push(entry);
<add> }
<add> }
<add> }
<add>
<add> // sort by left to right order in
<add> // the fields are guaranteed to be there because we just constructed this
<add> found.sort(function (a, b) {
<add> var f = function (n) { return n.field_id == 4; };
<add> var _a = a.notes.filter(f)[0];
<add> var _b = b.notes.filter(f)[0];
<add> return parseInt(_a.value) - parseInt(_b.value);
<add> });
<add> } else {
<add> // normal string search
<add> found = searcher.search(req.query.q);
<add> }
<ide> }
<ide>
<ide> var send_release_to_client = function (input, entry) {
<ide> var html = input;
<del>
<ide> html = html.replace("${size}", thumb_size);
<ide> html = html.replace('${entry.title}', entry.basic_information.title);
<ide> html = html.replace("${entry.artists}", entry.basic_information.artists[0].name);
<ide> html = html.replace("${entry.cover}", entry.basic_information.cover_image);
<ide> html = html.replace("${btn.find}", "https://www.discogs.com/release/" + entry.id);
<ide> html = html.replace("${btn.play}", entry.id);
<del>
<ide> return html;
<ide> };
<ide> |
|
Java | epl-1.0 | 9750c108aed6da3ec27092ddd67007cb004f3048 | 0 | rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1 |
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.script;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.ScriptContext;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IExpressionCollection;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
/**
*
*/
public class OLAPExpressionCompiler
{
/**
*
* @param cx
* @throws DataException
*/
public static void compile( ScriptContext cx, IBaseExpression expr ) throws DataException
{
if ( expr instanceof IConditionalExpression )
{
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getExpression( ) );
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getOperand1( ) );
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getOperand2( ) );
}
else if ( expr instanceof IScriptExpression )
{
prepareScriptExpression( cx, (IScriptExpression) expr );
}
}
/**
*
* @param cx
* @param expr1
* @throws DataException
*/
private static void prepareScriptExpression( ScriptContext cx,
IBaseExpression expr1 ) throws DataException
{
try {
if ( expr1 == null )
return;
if ( expr1 instanceof IScriptExpression )
{
String exprText = ( (IScriptExpression) expr1 ).getText( );
if( expr1.getHandle( ) != null )
expr1.setHandle( new OLAPExpressionHandler( cx.compile( expr1.getScriptId(), null, 0, exprText ) ) );
}
else if ( expr1 instanceof IExpressionCollection )
{
Object[] exprs = ( (IExpressionCollection) expr1 ).getExpressions( ).toArray( );
for ( int i = 0; i <exprs.length; i++ )
{
prepareScriptExpression( cx,
(IBaseExpression)exprs[i] );
}
}
}
catch (BirtException e)
{
throw DataException.wrap( e );
}
}
}
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/OLAPExpressionCompiler.java |
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.script;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.ScriptContext;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IExpressionCollection;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
/**
*
*/
public class OLAPExpressionCompiler
{
/**
*
* @param cx
* @throws DataException
*/
public static void compile( ScriptContext cx, IBaseExpression expr ) throws DataException
{
if ( expr instanceof IConditionalExpression )
{
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getExpression( ) );
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getOperand1( ) );
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getOperand2( ) );
}
else if ( expr instanceof IScriptExpression )
{
prepareScriptExpression( cx, (IScriptExpression) expr );
}
}
/**
*
* @param cx
* @param expr1
* @throws DataException
*/
private static void prepareScriptExpression( ScriptContext cx,
IBaseExpression expr1 ) throws DataException
{
try {
if ( expr1 == null )
return;
if ( expr1 instanceof IScriptExpression )
{
String exprText = ( (IScriptExpression) expr1 ).getText( );
expr1.setHandle( new OLAPExpressionHandler( cx.compile( expr1.getScriptId(), null, 0, exprText ) ) );
}
else if ( expr1 instanceof IExpressionCollection )
{
Object[] exprs = ( (IExpressionCollection) expr1 ).getExpressions( ).toArray( );
for ( int i = 0; i <exprs.length; i++ )
{
prepareScriptExpression( cx,
(IBaseExpression)exprs[i] );
}
}
}
catch (BirtException e)
{
throw DataException.wrap( e );
}
}
}
| An enhancement has been done to cache the compiled result during one query execution.[24552]
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/OLAPExpressionCompiler.java | An enhancement has been done to cache the compiled result during one query execution.[24552] | <ide><path>ata/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/OLAPExpressionCompiler.java
<ide> if ( expr1 instanceof IScriptExpression )
<ide> {
<ide> String exprText = ( (IScriptExpression) expr1 ).getText( );
<del> expr1.setHandle( new OLAPExpressionHandler( cx.compile( expr1.getScriptId(), null, 0, exprText ) ) );
<add> if( expr1.getHandle( ) != null )
<add> expr1.setHandle( new OLAPExpressionHandler( cx.compile( expr1.getScriptId(), null, 0, exprText ) ) );
<ide> }
<ide> else if ( expr1 instanceof IExpressionCollection )
<ide> { |
|
Java | apache-2.0 | 70458e0587a1bf86e78092b9863777e7a65f1876 | 0 | geosolutions-it/jai-ext,geosolutions-it/jai-ext | /* JAI-Ext - OpenSource Java Advanced Image Extensions Library
* http://www.geo-solutions.it/
* Copyright 2018 GeoSolutions
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.geosolutions.jaiext.shadedrelief;
import com.sun.media.jai.util.AreaOpPropertyGenerator;
import it.geosolutions.jaiext.range.Range;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import javax.media.jai.JAI;
import javax.media.jai.OperationDescriptorImpl;
import javax.media.jai.ParameterBlockJAI;
import javax.media.jai.PropertyGenerator;
import javax.media.jai.ROI;
import javax.media.jai.RenderedOp;
import javax.media.jai.registry.RenderedRegistryMode;
/**
* An <code>OperationDescriptor</code> describing the "ShadedRelief" operation.
*
*/
public class ShadedReliefDescriptor extends OperationDescriptorImpl {
public static final double DEFAULT_AZIMUTH = 315;
public static final double DEFAULT_ALTITUDE = 45;
public static final double DEFAULT_Z = 100000;
private static final double DEGREES_TO_METERS = 111120;
public static final double DEFAULT_SCALE = DEGREES_TO_METERS;
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/**
* The resource strings that provide the general documentation and specify the parameter list
* for a ShadedRelief operation.
*/
private static final String[][] resources = {
{"GlobalName", "ShadedRelief"},
{"LocalName", "ShadedRelief"},
{"Vendor", "it.geosolutions.jaiext"},
{"Description", "desc"},
{"Version", "1.0"},
{"DocURL", "Not Defined" },
{"arg0Desc", "Region of interest"},
{"arg1Desc", "Source NoData"},
{"arg2Desc", "Destination NoData"},
{"arg3Desc", "X resolution"},
{"arg4Desc", "Y resolution"},
{"arg5Desc", "Zeta factor"},
{"arg6Desc", "elevation unit to 2D unit scale ratio"},
{"arg7Desc", "altitude"},
{"arg8Desc", "azimuth"},
{"arg9Desc", "algorithm"}
};
/**
* The parameter names for the ShadedRelief operation.
*/
private static final String[] paramNames = {
"roi",
"srcNoData",
"dstNoData",
"resX",
"resY",
"zetaFactor",
"scale",
"altitude",
"azimuth",
"algorithm"
};
/**
* The parameter class types for the ShadedRelief operation.
*/
private static final Class[] paramClasses = {
javax.media.jai.ROI.class,
Range.class,
Double.class,
Double.class,
Double.class,
Double.class,
Double.class,
Double.class,
Double.class,
ShadedReliefAlgorithm.class
};
/**
* The parameter default values for the ShadedRelief operation.
*/
private static final Object[] paramDefaults = {
null,
null,
0d,
NO_PARAMETER_DEFAULT,
NO_PARAMETER_DEFAULT,
1d,
1d,
DEFAULT_ALTITUDE,
DEFAULT_AZIMUTH,
ShadedReliefAlgorithm.ZEVENBERGEN_THORNE_COMBINED
};
/** Constructor. */
public ShadedReliefDescriptor() {
super(resources, 1, paramClasses, paramNames, paramDefaults);
}
/**
* Returns an array of <code>PropertyGenerators</code> implementing property inheritance for the
* "ShadedRelief" operation.
*
* @return An array of property generators.
*/
public PropertyGenerator[] getPropertyGenerators() {
PropertyGenerator[] pg = new PropertyGenerator[1];
pg[0] = new AreaOpPropertyGenerator();
return pg;
}
/**
*
* @param altitude is the sun's angle of elevation above the horizon and ranges from 0 to 90 degrees. A value of 0 degrees indicates that the sun is on the horizon, that is, on the same horizontal plane as the frame of reference. A value of 90 degrees indicates that the sun is directly overhead.
* @param azimuth is the sun's relative position along the horizon (in degrees). This position is indicated by the angle of the sun measured clockwise from due north. An azimuth of 0 degrees indicates north, east is 90 degrees, south is 180 degrees, and west is 270 degrees.
* @return
*/
public static RenderedOp create(
RenderedImage source0,
ROI roi,
Range srcNoData,
double dstNoData,
double resX,
double resY,
double zetaFactor,
double scale,
double altitude,
double azimuth,
ShadedReliefAlgorithm algorithm,
RenderingHints hints) {
ParameterBlockJAI pb =
new ParameterBlockJAI("ShadedRelief", RenderedRegistryMode.MODE_NAME);
// Setting sources
pb.setSource("source0", source0);
// Setting params
pb.setParameter("roi", roi);
pb.setParameter("srcNoData", srcNoData);
pb.setParameter("dstNoData", dstNoData);
pb.setParameter("resX", resX);
pb.setParameter("resY", resY);
pb.setParameter("zetaFactor", zetaFactor);
pb.setParameter("scale", scale);
pb.setParameter("altitude", altitude);
pb.setParameter("azimuth", azimuth);
pb.setParameter("algorithm", algorithm);
return JAI.create("ShadedRelief", pb, hints);
}
}
| jt-shadedrelief/src/main/java/it/geosolutions/jaiext/shadedrelief/ShadedReliefDescriptor.java | /* JAI-Ext - OpenSource Java Advanced Image Extensions Library
* http://www.geo-solutions.it/
* Copyright 2018 GeoSolutions
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.geosolutions.jaiext.shadedrelief;
import com.sun.media.jai.util.AreaOpPropertyGenerator;
import it.geosolutions.jaiext.range.Range;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import javax.media.jai.JAI;
import javax.media.jai.OperationDescriptorImpl;
import javax.media.jai.ParameterBlockJAI;
import javax.media.jai.PropertyGenerator;
import javax.media.jai.ROI;
import javax.media.jai.RenderedOp;
import javax.media.jai.registry.RenderedRegistryMode;
/**
* An <code>OperationDescriptor</code> describing the "ShadedRelief" operation.
*
*/
public class ShadedReliefDescriptor extends OperationDescriptorImpl {
public static final double DEFAULT_AZIMUTH = 315;
public static final double DEFAULT_ALTITUDE = 45;
public static final double DEFAULT_Z = 100000;
private static final double DEGREES_TO_METERS = 111120;
public static final double DEFAULT_SCALE = DEGREES_TO_METERS;
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/**
* The resource strings that provide the general documentation and specify the parameter list
* for a ShadedRelief operation.
*/
private static final String[][] resources = {
{"GlobalName", "ShadedRelief"},
{"LocalName", "ShadedRelief"},
{"Vendor", "it.geosolutions.jaiext"},
{"Description", "desc"},
{"Version", "ver"},
{"arg0Desc", "Region of interest"},
{"arg1Desc", "Source NoData"},
{"arg2Desc", "Destination NoData"},
{"arg3Desc", "X resolution"},
{"arg4Desc", "Y resolution"},
{"arg5Desc", "Zeta factor"},
{"arg6Desc", "elevation unit to 2D unit scale ratio"},
{"arg7Desc", "altitude"},
{"arg8Desc", "azimuth"},
{"arg9Desc", "algorithm"}
};
/**
* The parameter names for the ShadedRelief operation.
*/
private static final String[] paramNames = {
"roi",
"srcNoData",
"dstNoData",
"resX",
"resY",
"zetaFactor",
"scale",
"altitude",
"azimuth",
"algorithm"
};
/**
* The parameter class types for the ShadedRelief operation.
*/
private static final Class[] paramClasses = {
javax.media.jai.ROI.class,
Range.class,
Double.class,
Double.class,
Double.class,
Double.class,
Double.class,
Double.class,
Double.class,
ShadedReliefAlgorithm.class
};
/**
* The parameter default values for the ShadedRelief operation.
*/
private static final Object[] paramDefaults = {
null,
null,
0d,
NO_PARAMETER_DEFAULT,
NO_PARAMETER_DEFAULT,
1d,
1d,
DEFAULT_ALTITUDE,
DEFAULT_AZIMUTH,
ShadedReliefAlgorithm.ZEVENBERGEN_THORNE_COMBINED
};
/** Constructor. */
public ShadedReliefDescriptor() {
super(resources, 1, paramClasses, paramNames, paramDefaults);
}
/**
* Returns an array of <code>PropertyGenerators</code> implementing property inheritance for the
* "ShadedRelief" operation.
*
* @return An array of property generators.
*/
public PropertyGenerator[] getPropertyGenerators() {
PropertyGenerator[] pg = new PropertyGenerator[1];
pg[0] = new AreaOpPropertyGenerator();
return pg;
}
/**
*
* @param altitude is the sun's angle of elevation above the horizon and ranges from 0 to 90 degrees. A value of 0 degrees indicates that the sun is on the horizon, that is, on the same horizontal plane as the frame of reference. A value of 90 degrees indicates that the sun is directly overhead.
* @param azimuth is the sun's relative position along the horizon (in degrees). This position is indicated by the angle of the sun measured clockwise from due north. An azimuth of 0 degrees indicates north, east is 90 degrees, south is 180 degrees, and west is 270 degrees.
* @return
*/
public static RenderedOp create(
RenderedImage source0,
ROI roi,
Range srcNoData,
double dstNoData,
double resX,
double resY,
double zetaFactor,
double scale,
double altitude,
double azimuth,
ShadedReliefAlgorithm algorithm,
RenderingHints hints) {
ParameterBlockJAI pb =
new ParameterBlockJAI("ShadedRelief", RenderedRegistryMode.MODE_NAME);
// Setting sources
pb.setSource("source0", source0);
// Setting params
pb.setParameter("roi", roi);
pb.setParameter("srcNoData", srcNoData);
pb.setParameter("dstNoData", dstNoData);
pb.setParameter("resX", resX);
pb.setParameter("resY", resY);
pb.setParameter("zetaFactor", zetaFactor);
pb.setParameter("scale", scale);
pb.setParameter("altitude", altitude);
pb.setParameter("azimuth", azimuth);
pb.setParameter("algorithm", algorithm);
return JAI.create("ShadedRelief", pb, hints);
}
}
| #184: add DocURL arg to ShadedReliefDescriptor
| jt-shadedrelief/src/main/java/it/geosolutions/jaiext/shadedrelief/ShadedReliefDescriptor.java | #184: add DocURL arg to ShadedReliefDescriptor | <ide><path>t-shadedrelief/src/main/java/it/geosolutions/jaiext/shadedrelief/ShadedReliefDescriptor.java
<ide> {"LocalName", "ShadedRelief"},
<ide> {"Vendor", "it.geosolutions.jaiext"},
<ide> {"Description", "desc"},
<del> {"Version", "ver"},
<add> {"Version", "1.0"},
<add> {"DocURL", "Not Defined" },
<ide> {"arg0Desc", "Region of interest"},
<ide> {"arg1Desc", "Source NoData"},
<ide> {"arg2Desc", "Destination NoData"}, |
|
Java | apache-2.0 | f1ee87db7f8c3b117550403c279e28884e5401c6 | 0 | droolsjbpm/drools,mswiderski/drools,droolsjbpm/drools,vinodkiran/drools,ngs-mtech/drools,manstis/drools,mswiderski/drools,psiroky/drools,HHzzhz/drools,droolsjbpm/drools,winklerm/drools,TonnyFeng/drools,kevinpeterson/drools,OnePaaS/drools,kedzie/drools-android,kedzie/drools-android,kedzie/drools-android,droolsjbpm/drools,manstis/drools,amckee23/drools,reynoldsm88/drools,ngs-mtech/drools,liupugong/drools,Buble1981/MyDroolsFork,kevinpeterson/drools,winklerm/drools,rajashekharmunthakewill/drools,reynoldsm88/drools,lanceleverich/drools,jomarko/drools,292388900/drools,lanceleverich/drools,ChallenHB/drools,amckee23/drools,pperboires/PocDrools,rajashekharmunthakewill/drools,manstis/drools,prabasn/drools,psiroky/drools,amckee23/drools,jiripetrlik/drools,pperboires/PocDrools,Buble1981/MyDroolsFork,rajashekharmunthakewill/drools,vinodkiran/drools,ThiagoGarciaAlves/drools,HHzzhz/drools,mrietveld/drools,droolsjbpm/drools,TonnyFeng/drools,ThiagoGarciaAlves/drools,mrietveld/drools,iambic69/drools,romartin/drools,ThomasLau/drools,Buble1981/MyDroolsFork,sotty/drools,iambic69/drools,jiripetrlik/drools,pperboires/PocDrools,292388900/drools,ThomasLau/drools,mrrodriguez/drools,pwachira/droolsexamples,kevinpeterson/drools,winklerm/drools,kedzie/drools-android,sutaakar/drools,sotty/drools,lanceleverich/drools,romartin/drools,292388900/drools,romartin/drools,mrrodriguez/drools,mrrodriguez/drools,sotty/drools,TonnyFeng/drools,Buble1981/MyDroolsFork,mrietveld/drools,kevinpeterson/drools,mrietveld/drools,yurloc/drools,iambic69/drools,reynoldsm88/drools,OnePaaS/drools,mrrodriguez/drools,HHzzhz/drools,ChallenHB/drools,jiripetrlik/drools,sotty/drools,jiripetrlik/drools,pperboires/PocDrools,amckee23/drools,ngs-mtech/drools,psiroky/drools,rajashekharmunthakewill/drools,ngs-mtech/drools,kevinpeterson/drools,jomarko/drools,sutaakar/drools,ThiagoGarciaAlves/drools,vinodkiran/drools,TonnyFeng/drools,ThomasLau/drools,OnePaaS/drools,ThomasLau/drools,liupugong/drools,manstis/drools,yurloc/drools,sutaakar/drools,jomarko/drools,mswiderski/drools,winklerm/drools,lanceleverich/drools,amckee23/drools,292388900/drools,mrrodriguez/drools,winklerm/drools,yurloc/drools,reynoldsm88/drools,OnePaaS/drools,sutaakar/drools,prabasn/drools,iambic69/drools,kedzie/drools-android,jomarko/drools,lanceleverich/drools,HHzzhz/drools,reynoldsm88/drools,OnePaaS/drools,romartin/drools,ngs-mtech/drools,ChallenHB/drools,ThiagoGarciaAlves/drools,ChallenHB/drools,vinodkiran/drools,sotty/drools,jiripetrlik/drools,jomarko/drools,liupugong/drools,liupugong/drools,mrietveld/drools,292388900/drools,yurloc/drools,ThomasLau/drools,romartin/drools,prabasn/drools,HHzzhz/drools,iambic69/drools,ChallenHB/drools,prabasn/drools,liupugong/drools,prabasn/drools,rajashekharmunthakewill/drools,manstis/drools,sutaakar/drools,vinodkiran/drools,TonnyFeng/drools,psiroky/drools,ThiagoGarciaAlves/drools,mswiderski/drools | package org.drools.common;
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.drools.conflict.DepthConflictResolver;
import org.drools.spi.Activation;
import org.drools.spi.AgendaGroup;
import org.drools.spi.ConflictResolver;
import org.drools.util.BinaryHeapQueue;
import org.drools.util.Iterator;
import org.drools.util.LinkedList;
import org.drools.util.LinkedListEntry;
import org.drools.util.PrimitiveLongMap;
import org.drools.util.Queueable;
import org.drools.util.LinkedList.LinkedListIterator;
/**
* <code>AgendaGroup</code> implementation that uses a <code>PriorityQueue</code> to prioritise the evaluation of added
* <code>ActivationQueue</code>s. The <code>AgendaGroup</code> also maintains a <code>Map</code> of <code>ActivationQueues</code>
* for requested salience values.
*
* @see PriorityQueue
* @see ActivationQueue
*
* @author <a href="mailto:[email protected]">Mark Proctor</a>
* @author <a href="mailto:[email protected]">Bob McWhirter</a>
*
*/
public class ArrayAgendaGroup
implements
InternalAgendaGroup {
private static final long serialVersionUID = 320L;
private final String name;
/** Items in the agenda. */
private LinkedList[] array;
private boolean active;
private int size;
private int index;
private int lastIndex;
/**
* Construct an <code>AgendaGroup</code> with the given name.
*
* @param name
* The <AgendaGroup> name.
*/
public ArrayAgendaGroup(final String name,
final InternalRuleBase ruleBase) {
this.name = name;
Integer integer = (Integer) ruleBase.getAgendaGroupRuleTotals().get( name );
if ( integer == null ) {
this.array = new LinkedList[0];
} else {
this.array = new LinkedList[integer.intValue()];
}
this.index = this.array.length-1;
this.lastIndex = 0;
}
/* (non-Javadoc)
* @see org.drools.spi.AgendaGroup#getName()
*/
public String getName() {
return this.name;
}
public void clear() {
this.array = new LinkedList[this.array.length];
}
/* (non-Javadoc)
* @see org.drools.spi.AgendaGroup#size()
*/
public int size() {
return this.size;
}
public void add(final Activation activation) {
AgendaItem item = (AgendaItem) activation;
this.size++;
int seq = item.getSequenence();
if ( seq < this.index ) {
this.index = seq;
}
if ( seq > this.lastIndex ) {
this.lastIndex = seq;
}
LinkedList list = this.array[seq];
if ( list == null ) {
list = new LinkedList();
this.array[item.getSequenence()] = list;
}
list.add( new LinkedListEntry( activation ) );
}
public Activation getNext() {
Activation activation = null;
while ( this.index <= lastIndex ) {
LinkedList list = this.array[this.index];
if ( list != null ) {
activation = (Activation) ((LinkedListEntry)list.removeFirst()).getObject();
if ( list.isEmpty()) {
this.array[this.index++] = null;
}
this.size--;
break;
}
this.index++;
}
return (Activation) activation;
}
public boolean isActive() {
return this.active;
}
public void setActive(final boolean activate) {
this.active = activate;
}
/**
* Iterates a PriorityQueue removing empty entries until it finds a populated entry and return true,
* otherwise it returns false;
*
* @param priorityQueue
* @return
*/
public boolean isEmpty() {
return this.size == 0;
}
public Activation[] getActivations() {
Activation[] activations = new Activation[this.size];
int j = 0;
for ( int i = 0; i < this.array.length; i++ ) {;
LinkedList list = this.array[i];
if ( list != null ) {
Iterator it = list.iterator();
Activation activation = ( Activation ) ((LinkedListEntry)it.next()).getObject();
while ( activation != null) {
activations[j++] = activation;
activation = ( Activation ) it.next();
}
}
}
return activations;
}
public Activation[] getQueue() {
return getActivations();
}
public String toString() {
return "AgendaGroup '" + this.name + "'";
}
public boolean equal(final Object object) {
if ( (object == null) || !(object instanceof ArrayAgendaGroup) ) {
return false;
}
if ( ((ArrayAgendaGroup) object).name.equals( this.name ) ) {
return true;
}
return false;
}
public int hashCode() {
return this.name.hashCode();
}
}
| drools-core/src/main/java/org/drools/common/ArrayAgendaGroup.java | package org.drools.common;
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.drools.conflict.DepthConflictResolver;
import org.drools.spi.Activation;
import org.drools.spi.AgendaGroup;
import org.drools.spi.ConflictResolver;
import org.drools.util.BinaryHeapQueue;
import org.drools.util.Iterator;
import org.drools.util.LinkedList;
import org.drools.util.LinkedListEntry;
import org.drools.util.PrimitiveLongMap;
import org.drools.util.Queueable;
import org.drools.util.LinkedList.LinkedListIterator;
/**
* <code>AgendaGroup</code> implementation that uses a <code>PriorityQueue</code> to prioritise the evaluation of added
* <code>ActivationQueue</code>s. The <code>AgendaGroup</code> also maintains a <code>Map</code> of <code>ActivationQueues</code>
* for requested salience values.
*
* @see PriorityQueue
* @see ActivationQueue
*
* @author <a href="mailto:[email protected]">Mark Proctor</a>
* @author <a href="mailto:[email protected]">Bob McWhirter</a>
*
*/
public class ArrayAgendaGroup
implements
InternalAgendaGroup {
private static final long serialVersionUID = 320L;
private final String name;
/** Items in the agenda. */
private LinkedList[] array;
private boolean active;
private int size;
private int index;
/**
* Construct an <code>AgendaGroup</code> with the given name.
*
* @param name
* The <AgendaGroup> name.
*/
public ArrayAgendaGroup(final String name,
final InternalRuleBase ruleBase) {
this.name = name;
Integer integer = (Integer) ruleBase.getAgendaGroupRuleTotals().get( name );
if ( integer == null ) {
this.array = new LinkedList[0];
} else {
this.array = new LinkedList[integer.intValue()];
}
}
/* (non-Javadoc)
* @see org.drools.spi.AgendaGroup#getName()
*/
public String getName() {
return this.name;
}
public void clear() {
this.array = new LinkedList[this.array.length];
}
/* (non-Javadoc)
* @see org.drools.spi.AgendaGroup#size()
*/
public int size() {
return this.size;
}
public void add(final Activation activation) {
AgendaItem item = (AgendaItem) activation;
this.size++;
LinkedList list = this.array[item.getSequenence()];
if ( list == null ) {
list = new LinkedList();
this.array[item.getSequenence()] = list;
}
list.add( new LinkedListEntry( activation ) );
}
public Activation getNext() {
Activation activation = null;
int length = this.array.length;
while ( this.index < length ) {
LinkedList list = this.array[this.index];
if ( list != null ) {
activation = (Activation) ((LinkedListEntry)list.removeFirst()).getObject();
if ( list.isEmpty()) {
this.array[this.index++] = null;
}
this.size--;
break;
}
this.index++;
}
return (Activation) activation;
}
public boolean isActive() {
return this.active;
}
public void setActive(final boolean activate) {
this.active = activate;
}
/**
* Iterates a PriorityQueue removing empty entries until it finds a populated entry and return true,
* otherwise it returns false;
*
* @param priorityQueue
* @return
*/
public boolean isEmpty() {
return this.size == 0;
}
public Activation[] getActivations() {
Activation[] activations = new Activation[this.size];
int j = 0;
for ( int i = 0; i < this.array.length; i++ ) {;
LinkedList list = this.array[i];
if ( list != null ) {
Iterator it = list.iterator();
Activation activation = ( Activation ) ((LinkedListEntry)it.next()).getObject();
while ( activation != null) {
activations[j++] = activation;
activation = ( Activation ) it.next();
}
}
}
return activations;
}
public Activation[] getQueue() {
return getActivations();
}
public String toString() {
return "AgendaGroup '" + this.name + "'";
}
public boolean equal(final Object object) {
if ( (object == null) || !(object instanceof ArrayAgendaGroup) ) {
return false;
}
if ( ((ArrayAgendaGroup) object).name.equals( this.name ) ) {
return true;
}
return false;
}
public int hashCode() {
return this.name.hashCode();
}
}
| JBRULES-947 sequential rete
-add performance enhancement to reduce iteration range, be tracking first and last populated elements.
git-svn-id: a243bed356d289ca0d1b6d299a0597bdc4ecaa09@12990 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70
| drools-core/src/main/java/org/drools/common/ArrayAgendaGroup.java | JBRULES-947 sequential rete -add performance enhancement to reduce iteration range, be tracking first and last populated elements. | <ide><path>rools-core/src/main/java/org/drools/common/ArrayAgendaGroup.java
<ide>
<ide> private int index;
<ide>
<add> private int lastIndex;
<add>
<ide> /**
<ide> * Construct an <code>AgendaGroup</code> with the given name.
<ide> *
<ide> final InternalRuleBase ruleBase) {
<ide> this.name = name;
<ide> Integer integer = (Integer) ruleBase.getAgendaGroupRuleTotals().get( name );
<add>
<ide> if ( integer == null ) {
<ide> this.array = new LinkedList[0];
<ide> } else {
<ide> this.array = new LinkedList[integer.intValue()];
<ide> }
<del>
<add>
<add> this.index = this.array.length-1;
<add> this.lastIndex = 0;
<ide> }
<ide>
<ide> /* (non-Javadoc)
<ide> public void add(final Activation activation) {
<ide> AgendaItem item = (AgendaItem) activation;
<ide> this.size++;
<del>
<del> LinkedList list = this.array[item.getSequenence()];
<add> int seq = item.getSequenence();
<add>
<add> if ( seq < this.index ) {
<add> this.index = seq;
<add> }
<add>
<add> if ( seq > this.lastIndex ) {
<add> this.lastIndex = seq;
<add> }
<add>
<add> LinkedList list = this.array[seq];
<ide> if ( list == null ) {
<ide> list = new LinkedList();
<ide> this.array[item.getSequenence()] = list;
<ide>
<ide> public Activation getNext() {
<ide> Activation activation = null;
<del> int length = this.array.length;
<del> while ( this.index < length ) {
<add> while ( this.index <= lastIndex ) {
<ide> LinkedList list = this.array[this.index];
<ide> if ( list != null ) {
<ide> activation = (Activation) ((LinkedListEntry)list.removeFirst()).getObject(); |
|
JavaScript | bsd-3-clause | 843f70cdbac61ddbc19706039a6381eec8e476f4 | 0 | CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb | 'use strict';
const RATE_LIMIT_ENDPOINTS_GROUPS = {
ANONYMOUS: 'anonymous',
STATIC: 'static',
STATIC_NAMED: 'static_named',
DATAVIEW: 'dataview',
DATAVIEW_SEARCH: 'dataview_search',
ANALYSIS: 'analysis',
TILE: 'tile',
ATTRIBUTES: 'attributes',
NAMED_LIST: 'named_list',
NAMED_CREATE: 'named_create',
NAMED_GET: 'named_get',
NAMED: 'named',
NAMED_UPDATE: 'named_update',
NAMED_DELETE: 'named_delete',
NAMED_TILES: 'named_tiles'
};
function rateLimit(userLimitsApi, endpointGroup = null) {
if (isRateLimitEnabled(endpointGroup)) {
return function rateLimitDisabledMiddleware(req, res, next) { next(); };
}
return function rateLimitMiddleware(req, res, next) {
userLimitsApi.getRateLimit(res.locals.user, endpointGroup, function (err, userRateLimit) {
if (err) {
return next(err);
}
if (!userRateLimit) {
return next();
}
const [isBlocked, limit, remaining, retry, reset] = userRateLimit;
res.set({
'X-Rate-Limit-Limit': limit,
'X-Rate-Limit-Remaining': remaining,
'X-Rate-Limit-Retry-After': retry,
'X-Rate-Limit-Reset': reset
});
if (isBlocked) {
const rateLimitError = new Error('You are over the limits.');
rateLimitError.http_status = 429;
return next(rateLimitError);
}
return next();
});
};
}
function isRateLimitEnabled(endpointGroup) {
return global.environment.enabledFeatures.rateLimitsEnabled &&
endpointGroup &&
global.environment.enabledFeatures.rateLimitsByEndpoint[endpointGroup];
}
module.exports = rateLimit;
module.exports.RATE_LIMIT_ENDPOINTS_GROUPS = RATE_LIMIT_ENDPOINTS_GROUPS;
| lib/cartodb/middleware/rate-limit.js | 'use strict';
const RATE_LIMIT_ENDPOINTS_GROUPS = {
ANONYMOUS: 'anonymous',
STATIC: 'static',
STATIC_NAMED: 'static_named',
DATAVIEW: 'dataview',
DATAVIEW_SEARCH: 'dataview_search',
ANALYSIS: 'analysis',
TILE: 'tile',
ATTRIBUTES: 'attributes',
NAMED_LIST: 'named_list',
NAMED_CREATE: 'named_create',
NAMED_GET: 'named_get',
NAMED: 'named',
NAMED_UPDATE: 'named_update',
NAMED_DELETE: 'named_delete',
NAMED_TILES: 'named_tiles'
};
function rateLimitFn(userLimitsApi, endpointGroup = null) {
if (isRateLimitEnabled(endpointGroup)) {
return function rateLimitDisabledMiddleware(req, res, next) { next(); };
}
return function rateLimitMiddleware(req, res, next) {
userLimitsApi.getRateLimit(res.locals.user, endpointGroup, function (err, rateLimit) {
if (err) {
return next(err);
}
if (!rateLimit) {
return next();
}
const [isBlocked, limit, remaining, retry, reset] = rateLimit;
res.set({
'X-Rate-Limit-Limit': limit,
'X-Rate-Limit-Remaining': remaining,
'X-Rate-Limit-Retry-After': retry,
'X-Rate-Limit-Reset': reset
});
if (isBlocked) {
const rateLimitError = new Error('You are over the limits.');
rateLimitError.http_status = 429;
return next(rateLimitError);
}
return next();
});
};
}
function isRateLimitEnabled(endpointGroup) {
return global.environment.enabledFeatures.rateLimitsEnabled &&
endpointGroup &&
global.environment.enabledFeatures.rateLimitsByEndpoint[endpointGroup];
}
module.exports = rateLimitFn;
module.exports.RATE_LIMIT_ENDPOINTS_GROUPS = RATE_LIMIT_ENDPOINTS_GROUPS;
| interchange var and middlewware names
| lib/cartodb/middleware/rate-limit.js | interchange var and middlewware names | <ide><path>ib/cartodb/middleware/rate-limit.js
<ide> NAMED_TILES: 'named_tiles'
<ide> };
<ide>
<del>function rateLimitFn(userLimitsApi, endpointGroup = null) {
<add>function rateLimit(userLimitsApi, endpointGroup = null) {
<ide> if (isRateLimitEnabled(endpointGroup)) {
<ide> return function rateLimitDisabledMiddleware(req, res, next) { next(); };
<ide> }
<ide>
<ide> return function rateLimitMiddleware(req, res, next) {
<del> userLimitsApi.getRateLimit(res.locals.user, endpointGroup, function (err, rateLimit) {
<add> userLimitsApi.getRateLimit(res.locals.user, endpointGroup, function (err, userRateLimit) {
<ide> if (err) {
<ide> return next(err);
<ide> }
<ide>
<del> if (!rateLimit) {
<add> if (!userRateLimit) {
<ide> return next();
<ide> }
<ide>
<del> const [isBlocked, limit, remaining, retry, reset] = rateLimit;
<add> const [isBlocked, limit, remaining, retry, reset] = userRateLimit;
<ide>
<ide> res.set({
<ide> 'X-Rate-Limit-Limit': limit,
<ide> global.environment.enabledFeatures.rateLimitsByEndpoint[endpointGroup];
<ide> }
<ide>
<del>module.exports = rateLimitFn;
<add>module.exports = rateLimit;
<ide> module.exports.RATE_LIMIT_ENDPOINTS_GROUPS = RATE_LIMIT_ENDPOINTS_GROUPS; |
|
Java | apache-2.0 | d880d515c7f7cd31659e289209b393e6dd0f59ca | 0 | jpodeszwik/mifos,AArhin/head,maduhu/head,AArhin/head,maduhu/head,maduhu/head,maduhu/head,AArhin/head,AArhin/head,jpodeszwik/mifos,AArhin/head,maduhu/head,jpodeszwik/mifos,jpodeszwik/mifos | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.test.acceptance.questionnaire;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mifos.test.acceptance.framework.AppLauncher;
import org.mifos.test.acceptance.framework.HomePage;
import org.mifos.test.acceptance.framework.MifosPage;
import org.mifos.test.acceptance.framework.UiTestCaseBase;
import org.mifos.test.acceptance.framework.admin.AdminPage;
import org.mifos.test.acceptance.framework.admin.DefineNewOfficePage;
import org.mifos.test.acceptance.framework.admin.ManageRolePage;
import org.mifos.test.acceptance.framework.admin.ViewRolesPage;
import org.mifos.test.acceptance.framework.client.ClientCloseReason;
import org.mifos.test.acceptance.framework.client.ClientStatus;
import org.mifos.test.acceptance.framework.client.ClientViewChangeLogPage;
import org.mifos.test.acceptance.framework.client.ClientViewDetailsPage;
import org.mifos.test.acceptance.framework.client.CreateClientEnterPersonalDataPage;
import org.mifos.test.acceptance.framework.client.QuestionGroup;
import org.mifos.test.acceptance.framework.customer.CustomerChangeStatusPage;
import org.mifos.test.acceptance.framework.group.EditCustomerStatusParameters;
import org.mifos.test.acceptance.framework.loan.QuestionResponseParameters;
import org.mifos.test.acceptance.framework.office.CreateOfficePreviewDataPage;
import org.mifos.test.acceptance.framework.office.OfficeParameters;
import org.mifos.test.acceptance.framework.office.OfficeViewDetailsPage;
import org.mifos.test.acceptance.framework.questionnaire.AttachQuestionGroupParameters;
import org.mifos.test.acceptance.framework.questionnaire.Choice;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionGroupPage;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionGroupParameters;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionPage;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionParameters;
import org.mifos.test.acceptance.framework.questionnaire.EditQuestionGroupPage;
import org.mifos.test.acceptance.framework.questionnaire.EditQuestionPage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionDetailPage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionGroupDetailPage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionGroupResponsePage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionResponsePage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionnairePage;
import org.mifos.test.acceptance.framework.questionnaire.ViewAllQuestionGroupsPage;
import org.mifos.test.acceptance.framework.questionnaire.ViewAllQuestionsPage;
import org.mifos.test.acceptance.framework.questionnaire.ViewQuestionResponseDetailPage;
import org.mifos.test.acceptance.framework.testhelpers.ClientTestHelper;
import org.mifos.test.acceptance.framework.testhelpers.OfficeHelper;
import org.mifos.test.acceptance.framework.testhelpers.QuestionGroupTestHelper;
import org.mifos.test.acceptance.util.StringUtil;
import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static java.util.Arrays.*; //NOPMD
import static org.apache.commons.lang.ArrayUtils.*; //NOPMD
import static org.junit.Assert.*; //NOPMD
@ContextConfiguration(locations = {"classpath:ui-test-context.xml"})
@SuppressWarnings("PMD.CyclomaticComplexity")
@Test(singleThreaded = true, groups = {"client", "acceptance", "ui", "no_db_unit"})
public class QuestionGroupTest extends UiTestCaseBase {
private AppLauncher appLauncher;
private OfficeHelper officeHelper;
private QuestionGroupTestHelper questionGroupTestHelper;
private ClientTestHelper clientTestHelper;
private String qgTitle1, qgTitle2, qgTitle3, qgTitle4;
private String qTitle1, qTitle2, qTitle3, qTitle4, qTitle5;
private static final String TITLE_MISSING = "Please specify Question Group title.";
private static final String APPLIES_TO_MISSING = "Please choose a valid 'Applies To' value.";
private static final String SECTION_MISSING = "Please add at least one section.";
private static final String QUESTION_MISSING = "Section should have at least one question.";
public static final String APPLIES_TO_CREATE_CLIENT = "Create Client";
public static final String SECTION_DEFAULT = "Default";
private static final String SECTION_MISC = "Misc";
private static final int CREATE_OFFICE_QUESTION_GROUP_ID = 12;
private static final String CLIENT = "WeeklyClient Wednesday";
private Map<Integer, QuestionGroup> questionGroupInstancesOfClient;
private static final List<String> charactersList = new ArrayList<String>(Arrays.asList("عربية", "有", "òèßñ"));
private static final String noNumber = "qwerty";
private static final List<String> EMPTY_LIST = new ArrayList<String>();
private static final List<String> QUESTIONS_LIST = new ArrayList<String>(Arrays.asList("QGForViewClientCentreGroupLoan",
"ViewCenterQG", "QGForCreateSavingsAccount", "QGForViewSavings", "QGForCreateLoan1", "QGForCreateLoan2", "QGForLoanApproval",
"QGForApproveLoan1", "QGForApproveLoan2", "QGForDisburseLoan1", "QGForDisburseLoan2"));
private static final Map<String, String> QUESTIONS = new HashMap<String, String>();
private static final String ADMIN_ROLE = "Admin";
private static final String QUESTION_PERMISSION_ID = "9_6_0";
private static final String QUESTION_PERMISSION_HEADER = "Can edit ";
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
super.setUp();
officeHelper = new OfficeHelper(selenium);
appLauncher = new AppLauncher(selenium);
questionGroupTestHelper = new QuestionGroupTestHelper(selenium);
clientTestHelper = new ClientTestHelper(selenium);
questionGroupInstancesOfClient = new HashMap<Integer, QuestionGroup>();
qgTitle1 = "QuestionGroup1";
qgTitle2 = "QuestionGroup2";
qgTitle3 = "QuestionGroup3";
qgTitle4 = "QuestionGroup4";
qTitle1 = "Question1";
qTitle2 = "Question2";
qTitle3 = "Question3";
qTitle4 = "Question4";
qTitle5 = "Question5";
QUESTIONS.put("TextQuestionTest", CreateQuestionParameters.TYPE_FREE_TEXT);
QUESTIONS.put("DateQuestionTest", CreateQuestionParameters.TYPE_DATE);
QUESTIONS.put("NumberQuestionTest", CreateQuestionParameters.TYPE_NUMBER);
QUESTIONS.put("MultiSelectQuestionTest", CreateQuestionParameters.TYPE_MULTI_SELECT);
QUESTIONS.put("SingleSelectQuestionTest", CreateQuestionParameters.TYPE_SINGLE_SELECT);
QUESTIONS.put("SmartSelectQuestionTest", CreateQuestionParameters.TYPE_SMART_SELECT);
}
@AfterMethod
public void logOut() {
(new MifosPage(selenium)).logout();
}
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void createQuestionGroup() throws Exception {
try {
AdminPage adminPage = createQuestions(qTitle1, qTitle2, qTitle3);
CreateQuestionGroupPage createQuestionGroupPage = getCreateQuestionGroupPage(adminPage);
testMissingMandatoryInputs(createQuestionGroupPage);
testCreateQuestionGroup(createQuestionGroupPage, qgTitle1, APPLIES_TO_CREATE_CLIENT, true, SECTION_DEFAULT, asList(qTitle1, qTitle2), asList(qTitle3), qTitle4);
testShouldAllowDuplicateTitlesForQuestionGroup();
testCancelCreateQuestionGroup(getCreateQuestionGroupPage(new AdminPage(selenium)));
testViewQuestionGroups();
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle1);
questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle2);
questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle3);
}
}
@Test(enabled = true)
public void checkQuestionGroupPermission() {
AdminPage adminPage = getAdminPage();
CreateQuestionGroupPage createQuestionGroupPage = getCreateQuestionGroupPage(adminPage);
CreateQuestionGroupParameters parameters = new CreateQuestionGroupParameters();
parameters.setTitle(qgTitle4);
parameters.setAppliesTo(APPLIES_TO_CREATE_CLIENT);
parameters.setAnswerEditable(true);
for (String question : asList(qTitle1, qTitle2)) {
parameters.addExistingQuestion(SECTION_DEFAULT, question);
}
for (String section : parameters.getExistingQuestions().keySet()) {
createQuestionGroupPage.addExistingQuestion(section, parameters.getExistingQuestions().get(section));
}
createQuestionGroupPage.submit(parameters);
ViewRolesPage rolesPage = adminPage.navigateToViewRolesPage();
ManageRolePage manageRolePage = rolesPage.navigateToManageRolePage(ADMIN_ROLE);
manageRolePage.verifyPermissionText(QUESTION_PERMISSION_ID, QUESTION_PERMISSION_HEADER + qgTitle4);
manageRolePage.disablePermission(QUESTION_PERMISSION_ID);
manageRolePage.submitAndGotoViewRolesPage();
adminPage = getAdminPage();
Assert.assertTrue(adminPage.navigateToViewAllQuestionGroups().navigateToQuestionGroupDetailPage(qgTitle4).isAccessDeniedDisplayed());
//set question group on inactive
adminPage.navigateBack();
adminPage.navigateToAdminPageUsingHeaderTab();
manageRolePage = adminPage.navigateToViewRolesPage().navigateToManageRolePage(ADMIN_ROLE);
manageRolePage.verifyPermissionText(QUESTION_PERMISSION_ID, QUESTION_PERMISSION_HEADER + qgTitle4);
manageRolePage.enablePermission(QUESTION_PERMISSION_ID);
manageRolePage.submitAndGotoViewRolesPage().navigateToAdminPage().navigateToViewAllQuestionGroups().navigateToQuestionGroupDetailPage(qgTitle4);
questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle4);
}
/**
* Verify that user is able to edit the defined Question Groups
* and create Office with edited Question Group
* http://mifosforge.jira.com/browse/MIFOSTEST-666
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void editQuestionGroupsForCreateOffice() throws Exception {
//When
ViewAllQuestionGroupsPage viewAllQuestionGroupsPage = questionGroupTestHelper.navigateToViewQuestionGroups(QUESTIONS_LIST);
String oldTitle = "CreateOffice";
EditQuestionGroupPage editQuestionGroupPage = viewAllQuestionGroupsPage.navigateToQuestionGroupDetailPage(oldTitle).navigateToEditPage();
editQuestionGroupPage.moveSectionUp("Misc");
editQuestionGroupPage.moveQuestionUp(9);
editQuestionGroupPage.moveQuestionDown(2);
String newTitle = "CreateOfficeQG";
QuestionGroupDetailPage questionGroupDetailPage = editQuestionGroupPage.editQuestionGroup(false, newTitle, "Create Office", Collections.<String>emptyList());
//Then
questionGroupDetailPage.verifyOrderQuestions(asList("MultiSelect", "Date", "FreeText"), 4);
questionGroupDetailPage.verifyOrderSections(asList("Misc", "Default"));
questionGroupDetailPage.verifyMandatoryQuestions(Arrays.asList("FreeText"), "Misc");
questionGroupDetailPage.verifyMandatoryQuestions(EMPTY_LIST, "Default");
questionGroupDetailPage.verifyTitle(newTitle);
questionGroupTestHelper.markQuestionGroupAsActive(newTitle);
createOfficeWithQuestionGroup();
questionGroupTestHelper.markQuestionGroupAsInactive(newTitle);
//When
viewAllQuestionGroupsPage = questionGroupDetailPage.navigateToViewQuestionGroupsPage();
//Then
viewAllQuestionGroupsPage.verifyInactiveQuestions(0, 0);
}
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private void createOfficeWithQuestionGroup() throws Exception {
//When
QuestionResponsePage questionResponsePage = officeHelper.navigateToQuestionResponsePage(getOfficeParameters("MyOfficeDHMFT", "DHM"));
QuestionResponseParameters initialResponse = getResponse("123");
QuestionResponseParameters updatedResponse = getResponse("1234");
CreateOfficePreviewDataPage createOfficePreviewDataPage = questionGroupTestHelper.createOfficeWithQuestionGroup(questionResponsePage, initialResponse, updatedResponse);
assertTextFoundOnPage("This office name already exist");
DefineNewOfficePage defineNewOfficePage = createOfficePreviewDataPage.editOfficeInformation();
defineNewOfficePage.setOfficeName("TestOffice");
defineNewOfficePage.setOfficeShortName("TO");
defineNewOfficePage.preview();
defineNewOfficePage.next();
OfficeViewDetailsPage officeViewDetailsPage = createOfficePreviewDataPage.submit().navigateToOfficeViewDetailsPage();
ViewQuestionResponseDetailPage viewQuestionResponseDetailPage = officeViewDetailsPage.navigateToViewAdditionalInformation();
viewQuestionResponseDetailPage.verifyQuestionPresent("FreeText", "1234");
officeViewDetailsPage = viewQuestionResponseDetailPage.navigateToDetailsPage();
String newQuestion = "Text";
addQuestion(newQuestion, "Default", CREATE_OFFICE_QUESTION_GROUP_ID);
String questionToDeactivate = "FreeText";
questionGroupTestHelper.markQuestionAsInactive(questionToDeactivate);
questionResponsePage = officeHelper.navigateToQuestionResponsePage(getOfficeParameters("TestOffice2", "TO2"));
//Then
questionResponsePage.verifyQuestionsDoesnotappear(new String[]{questionToDeactivate});
questionResponsePage.verifyQuestionsExists(new String[]{newQuestion});
officeHelper.verifyQuestionPresent("TestOffice", "Text", "");
}
/**
* Verifying that Change Log for Question Groups has an appropriate format
* http://mifosforge.jira.com/browse/MIFOSTEST-667
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void testChangeLog() throws Exception {
String questionGroup = "CreateClientQG-1";
try {
questionGroupTestHelper.markQuestionAsActive("FreeText");
questionGroupTestHelper.markQuestionGroupAsActive(questionGroup);
//Given
ClientViewDetailsPage clientViewDetailsPage = clientTestHelper.navigateToClientViewDetailsPage(CLIENT);
//When
clientViewDetailsPage = clientTestHelper.editQuestionGroupResponses(
clientViewDetailsPage, "0", "details[0].sectionDetails[0].questions[0].value", "qwert"
);
//Then
ClientViewChangeLogPage clientViewChangeLogPage = clientViewDetailsPage.navigateToClientViewChangeLog();
clientViewChangeLogPage.verifyChangeLog(asList("CreateClientQG-1/Misc/FreeText"),
asList("-"), asList("qwert"), asList("mifos"), 2);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(questionGroup);
}
}
private void addQuestion(String newQuestion, String section, int questionGroupId) {
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.addExistingQuestion(section, newQuestion);
questionGroupTestHelper.addQuestionsToQuestionGroup(questionGroupId, createQuestionGroupParameters.getExistingQuestions());
}
private OfficeParameters getOfficeParameters(String name, String shortName) {
OfficeParameters officeParameters = new OfficeParameters();
officeParameters.setOfficeName(name);
officeParameters.setOfficeType(OfficeParameters.REGIONAL_OFFICE);
officeParameters.setParentOffice("Head Office(Mifos HO )");
officeParameters.setShortName(shortName);
return officeParameters;
}
private QuestionResponseParameters getResponse(String answer) {
QuestionResponseParameters initialResponse = new QuestionResponseParameters();
initialResponse.addTextAnswer("questionGroups[0].sectionDetails[0].questions[2].value", answer);
return initialResponse;
}
/**
* Creating and editing Questions
* http://mifosforge.jira.com/browse/MIFOSTEST-700
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void createAndEditQuestionsTest() throws Exception {
//When
testValidationAddQuestion();
CreateQuestionPage createQuestionPage = questionGroupTestHelper.navigateToCreateQuestionPage();
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setText("TextQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_FREE_TEXT);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("DateQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_DATE);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("NumberQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_NUMBER);
createQuestionParameters.setNumericMin(1);
createQuestionParameters.setNumericMax(10);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("MultiSelectQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_MULTI_SELECT);
List<Choice> choices = new ArrayList<Choice>();
Choice c = new Choice("choice 1", EMPTY_LIST);
choices.add(c);
c = new Choice("choice 2", EMPTY_LIST);
choices.add(c);
c = new Choice("choice 3", EMPTY_LIST);
choices.add(c);
createQuestionParameters.setChoices(choices);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("SingleSelectQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_SINGLE_SELECT);
createQuestionParameters.setChoices(choices);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("SmartSelectQuestionTest");
createQuestionParameters.setChoices(choices);
createQuestionParameters.setType(CreateQuestionParameters.TYPE_SMART_SELECT);
createQuestionPage.addQuestion(createQuestionParameters);
AdminPage adminPage = createQuestionPage.submitQuestions();
ViewAllQuestionsPage viewAllQuestionsPage = adminPage.navigateToViewAllQuestions();
//Then
viewAllQuestionsPage.verifyQuestions(QUESTIONS.keySet());
//When
c = new Choice("answerChoice1", EMPTY_LIST);
choices.add(c);
c = new Choice("answerChoice3", EMPTY_LIST);
choices.add(c);
for (String question : QUESTIONS.keySet()) {
QuestionDetailPage questionDetailPage = viewAllQuestionsPage.navigateToQuestionDetail(question);
EditQuestionPage editQuestionPage = questionDetailPage.navigateToEditQuestionPage();
createQuestionParameters.setText("");
editQuestionPage.tryUpdate(createQuestionParameters);
//Then
editQuestionPage.verifyTextPresent("Please specify the question", "No text <Please specify the question> present on the page");
questionDetailPage = editQuestionPage.cancelEdit();
//When
editQuestionPage = questionDetailPage.navigateToEditQuestionPage();
for (String characters : charactersList) {
editQuestionPage.setQuestionName(characters);
editQuestionPage.verifyQuestionName(characters);
}
if ("NumberQuestionTest".equals(question)) {
editQuestionPage.setNumberQuestion(noNumber, noNumber);
editQuestionPage.verifyNumberQuestion("", "");
editQuestionPage.setNumberQuestion("", "");
} else if ("MultiSelectQuestionTest".equals(question) || "SingleSelectQuestionTest".equals(question)) {
editQuestionPage.addAnswerChoices(asList("answerChoice1", "answerChoice2", "answerChoice3"));
editQuestionPage.removeAnswerChoice("4");
} else if ("SmartSelectQuestionTest".equals(question)) {
editQuestionPage.addSmartAnswerChoices(asList("answerChoice1", "answerChoice2", "answerChoice3"));
editQuestionPage.removeAnswerChoice("4");
}
editQuestionPage.setQuestionName(question + "Edit");
questionDetailPage = editQuestionPage.deactivate();
//Then
questionDetailPage.verifyQuestionTitle(question + "Edit");
if ("MultiSelectQuestionTest".equals(question) || "SingleSelectQuestionTest".equals(question) || "SmartSelectQuestionTest".equals(question)) {
questionDetailPage.assertForChoices(QUESTIONS.get(question), choices);
}
viewAllQuestionsPage = questionDetailPage.navigateToViewAllQuestionsPage();
}
}
/**
* Attaching a Question Group to Multiple flows
* http://mifosforge.jira.com/browse/MIFOSTEST-701
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void attachingQuestionGroupToMultipleFlowsTest() throws Exception {
String newClient = "Joe701 Doe701";
questionGroupTestHelper.markQuestionGroupAsInactive("CreateOffice");
createClient("Joe701","Doe701");
//When
testValidationAddQuestionGroup();
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
questions.add("Date");
questions.add("Number");
questions.add("Text");
sectionQuestions.put("Sec Test", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setAnswerEditable(true);
String testQuestionGroup = "TestQuestionGroup";
createQuestionGroupParameters.setTitle(testQuestionGroup);
createQuestionGroupParameters.setAppliesTo("View Client");
createQuestionGroupParameters.setAppliesTo("Close Client");
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
try {
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
Map<String, String> answers = new HashMap<String, String>();
answers.put("Text", "Test - Text");
answers.put("Number", "2");
answers.put("Date", "11/11/2009");
ClientViewDetailsPage clientViewDetailsPage = questionGroupTestHelper.attachQuestionGroup(newClient, testQuestionGroup, asList("Sec Test"), answers);
CustomerChangeStatusPage customerChangeStatusPage = clientViewDetailsPage.navigateToCustomerChangeStatusPage();
EditCustomerStatusParameters customerStatusParameters = new EditCustomerStatusParameters();
customerStatusParameters.setNote("TEST");
customerStatusParameters.setClientStatus(ClientStatus.CLOSED);
customerStatusParameters.setClientCloseReason(ClientCloseReason.TRANSFERRED);
QuestionResponsePage questionResponsePage = customerChangeStatusPage.changeStatusAndNavigateToQuestionResponsePage(customerStatusParameters);
//Then
questionResponsePage.verifyQuestionsExists(questions.toArray(new String[questions.size()]));
//When
clientViewDetailsPage = questionResponsePage.cancel();
ViewQuestionResponseDetailPage viewQuestionResponseDetailPage = clientViewDetailsPage.navigateToViewAdditionalInformationPage();
//Then
viewQuestionResponseDetailPage.verifyQuestionsDoesnotappear(questions.toArray(new String[questions.size()]));
clientViewDetailsPage = viewQuestionResponseDetailPage.navigateToClientViewDetailsPage();
answers = new HashMap<String, String>();
answers.put("Text", "Test - Text - Edit");
answers.put("Number", "22");
questionGroupInstancesOfClient = clientViewDetailsPage.getQuestionGroupInstances();
questionGroupTestHelper.editResponses(clientViewDetailsPage, latestInstanceId(questionGroupInstancesOfClient), answers);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(testQuestionGroup);
questionGroupTestHelper.markQuestionGroupAsInactive("CreateOffice");
}
}
private void createClient(String firstName, String lastName) {
String groupName = "group1";
CreateClientEnterPersonalDataPage.SubmitFormParameters clientParams = new CreateClientEnterPersonalDataPage.SubmitFormParameters();
clientParams.setSalutation(CreateClientEnterPersonalDataPage.SubmitFormParameters.MRS);
clientParams.setFirstName(firstName);
clientParams.setLastName(lastName);
clientParams.setDateOfBirthDD("22");
clientParams.setDateOfBirthMM("06");
clientParams.setDateOfBirthYYYY("1987");
clientParams.setGender(CreateClientEnterPersonalDataPage.SubmitFormParameters.MALE);
clientParams.setPovertyStatus(CreateClientEnterPersonalDataPage.SubmitFormParameters.NOT_POOR);
clientParams.setSpouseNameType(CreateClientEnterPersonalDataPage.SubmitFormParameters.FATHER);
clientParams.setSpouseFirstName("fatherNameTest");
clientParams.setSpouseLastName("fatherLastNameTest");
clientTestHelper.createNewClient(groupName, clientParams);
clientTestHelper.activateClient(firstName + " " + lastName);
}
@Test(enabled=true)
//http://mifosforge.jira.com/browse/MIFOSTEST-660
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void verifyAttachingQuestionGroupToGroup() throws Exception {
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
String title = "TestQuestionGroup" + StringUtil.getRandomString(6);
questions.add("Date");
questions.add("question 3");
questions.add("question 4");
sectionQuestions.put("Sec 1", questions);
questions = new ArrayList<String>();
questions.add("DateQuestion");
questions.add("Number");
questions.add("question 1");
questions.add("Text");
sectionQuestions.put("Sec 2", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setAnswerEditable(true);
createQuestionGroupParameters.setAppliesTo("View Group");
createQuestionGroupParameters.setTitle(title);
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
AttachQuestionGroupParameters attachParams = new AttachQuestionGroupParameters();
attachParams.setTarget("Default Group");
attachParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachParams.addTextResponse("Date", "09/02/2011");
attachParams.addCheckResponse("question 4", "yes");
attachParams.addTextResponse("DateQuestion", "19/02/2011");
attachParams.addTextResponse("question 3", "25/02/2011");
attachParams.addTextResponse("Number", "60");
attachParams.addTextResponse("question 1", "tekst tekst");
attachParams.addTextResponse("Text", "ale alo olu");
AttachQuestionGroupParameters attachErrorParams = new AttachQuestionGroupParameters();
attachErrorParams.setTarget("Default Group");
attachErrorParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachErrorParams.addTextResponse("Number", "sdfsdf");
attachErrorParams.addTextResponse("question 3", "25/02/2011");
attachErrorParams.addCheckResponse("question 4", "yes");
attachErrorParams.addError("Please specify a number for Number.");
//When
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
questionGroupTestHelper.verifyErrorsWhileAttachingQuestionGroupToGroup(attachErrorParams);
questionGroupTestHelper.attachQuestionGroupToGroup(attachParams);
attachParams.addTextResponse("Number", "20");
attachParams.addTextResponse("question 3", "21/02/2011");
//Then
questionGroupTestHelper.editQuestionGroupResponsesInGroup(attachParams);
questionGroupTestHelper.markQuestionGroupAsInactive(title);
}
@Test(enabled=true)
//http://mifosforge.jira.com/browse/MIFOSTEST-662
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void verifyAttachingQuestionGroupToLoan() throws Exception {
String title = "TestQuestionGroup" + StringUtil.getRandomString(6);
try {
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
questions.add("question 4");
questions.add("question 3");
questions.add("Date");
sectionQuestions.put("Sec 1", questions);
questions = new ArrayList<String>();
questions.add("question 1");
questions.add("Number");
questions.add("DateQuestion");
questions.add("Text");
sectionQuestions.put("Sec 2", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setAppliesTo("View Loan");
createQuestionGroupParameters.setAnswerEditable(true);
createQuestionGroupParameters.setTitle(title);
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
AttachQuestionGroupParameters attachParams = new AttachQuestionGroupParameters();
attachParams.setTarget("000100000000012");
attachParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachParams.addCheckResponse("question 4", "yes");
attachParams.addTextResponse("Date", "09/02/2011");
attachParams.addTextResponse("DateQuestion", "19/02/2011");
attachParams.addTextResponse("question 3", "25/02/2011");
attachParams.addTextResponse("question 1", "tekst tekst");
attachParams.addTextResponse("Text", "ale alo olu");
attachParams.addTextResponse("Number", "60");
AttachQuestionGroupParameters attachErrorParams = new AttachQuestionGroupParameters();
attachErrorParams.setTarget("000100000000012");
attachErrorParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachErrorParams.addError("Please specify a number for Number.");
attachErrorParams.addTextResponse("Number", "sdfsdf");
attachErrorParams.addTextResponse("question 3", "25/02/2011");
attachErrorParams.addCheckResponse("question 4", "yes");
//When
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
questionGroupTestHelper.verifyErrorsWhileAttachingQuestionGroupToLoan(attachErrorParams);
questionGroupTestHelper.attachQuestionGroupToLoan(attachParams);
attachParams.addTextResponse("Number", "20");
attachParams.addTextResponse("question 3", "21/02/2011");
//Then
questionGroupTestHelper.editQuestionGroupResponsesInLoan(attachParams);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(title);
}
}
@Test(enabled=true)
//http://mifosforge.jira.com/browse/MIFOSTEST-680
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void verifyAttachingQuestionGroupToViewClient() throws Exception {
String title = "TestQuestionGroup" + StringUtil.getRandomString(6);
try {
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
questions.add("Date");
questions.add("question 4");
questions.add("question 3");
sectionQuestions.put("Sec 1", questions);
questions = new ArrayList<String>();
questions.add("Number");
questions.add("DateQuestion");
questions.add("question 1");
questions.add("Text");
sectionQuestions.put("Sec 2", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
createQuestionGroupParameters.setAnswerEditable(true);
createQuestionGroupParameters.setAppliesTo("View Client");
createQuestionGroupParameters.setTitle(title);
AttachQuestionGroupParameters attachParams = new AttachQuestionGroupParameters();
attachParams.setTarget("0002-000000003");
attachParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachParams.addTextResponse("Number", "60");
attachParams.addTextResponse("question 1", "tekst tekst");
attachParams.addCheckResponse("question 4", "yes");
attachParams.addTextResponse("question 3", "25/02/2011");
attachParams.addTextResponse("Date", "09/02/2011");
attachParams.addTextResponse("DateQuestion", "19/02/2011");
attachParams.addTextResponse("Text", "ale alo olu");
AttachQuestionGroupParameters attachErrorParams = new AttachQuestionGroupParameters();
attachErrorParams.setTarget("0002-000000003");
attachErrorParams.addError("Please specify a number for Number.");
attachErrorParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachErrorParams.addTextResponse("Number", "sdfsdf");
attachErrorParams.addCheckResponse("question 4", "yes");
attachErrorParams.addTextResponse("question 3", "25/02/2011");
//When
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
questionGroupTestHelper.verifyErrorsWhileAttachingQuestionGroupToClient(attachErrorParams);
questionGroupTestHelper.attachQuestionGroupToClient(attachParams);
attachParams.addTextResponse("Number", "20");
attachParams.addTextResponse("question 3", "21/02/2011");
//Then
questionGroupTestHelper.editQuestionGroupResponsesInClient(attachParams);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(title);
}
}
private void testValidationAddQuestionGroup() {
questionGroupTestHelper.validatePageBlankMandatoryField();
questionGroupTestHelper.validateQuestionGroupTitle(charactersList);
}
private void testValidationAddQuestion() {
CreateQuestionPage createQuestionPage = questionGroupTestHelper.navigateToCreateQuestionPage();
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setText("");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_FREE_TEXT);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionPage.verifyTextPresent("Please specify the question", "No text <Please specify the question> present on the page");
createQuestionPage.verifySubmitButtonStatus("true");
createQuestionPage.cancelQuestion();
createQuestionPage = questionGroupTestHelper.navigateToCreateQuestionPage();
createQuestionPage.setNumberQuestion("NumberQuestion", noNumber, noNumber);
createQuestionPage.verifyNumberQuestion("", "");
createQuestionPage.setNumberQuestion("NumberQuestion", "", "");
for (int i = 0; i < charactersList.size(); i++) {
createQuestionParameters.setText(charactersList.get(i));
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionPage.verifyQuestionPresent(createQuestionParameters, i + 1);
}
}
private void testViewQuestionGroups() {
ViewAllQuestionGroupsPage viewQuestionGroupsPage = getViewQuestionGroupsPage(new AdminPage(selenium));
testViewQuestionGroups(viewQuestionGroupsPage);
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle1, SECTION_DEFAULT, asList(qTitle1, qTitle2), asList(qTitle1));
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle1, SECTION_MISC, asList(qTitle4), EMPTY_LIST);
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle2, SECTION_MISC, asList(qTitle1, qTitle3), asList(qTitle1));
testEditQuestionGroupDetail(viewQuestionGroupsPage.navigateToQuestionGroupDetailPage(qgTitle2));
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle3, SECTION_MISC, asList(qTitle1, qTitle3), asList(qTitle1));
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle3, "New Section", asList(qTitle4), EMPTY_LIST);
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle3, "Hello World", asList(qTitle5), EMPTY_LIST);
}
private void testEditQuestionGroupDetail(QuestionGroupDetailPage questionGroupDetailPage) {
EditQuestionGroupPage editQuestionGroupPage = questionGroupDetailPage.navigateToEditPage();
editQuestionGroupPage.setTitle(qgTitle3);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.addExistingQuestion("New Section", qTitle4);
for (String section : createQuestionGroupParameters.getExistingQuestions().keySet()) {
editQuestionGroupPage.addExistingQuestion(section, createQuestionGroupParameters.getExistingQuestions().get(section));
}
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setType("Free Text");
createQuestionParameters.setText(qTitle5);
editQuestionGroupPage.setSection("Hello World");
editQuestionGroupPage.addNewQuestion(createQuestionParameters);
editQuestionGroupPage.submit();
questionGroupDetailPage.verifyPage();
questionGroupDetailPage.navigateToViewQuestionGroupsPage();
}
private AdminPage createQuestions(String... qTitles) {
CreateQuestionPage createQuestionPage = getAdminPage().navigateToCreateQuestionPage();
CreateQuestionParameters parameters = new CreateQuestionParameters();
for (String qTitle : qTitles) {
parameters.setText(qTitle);
parameters.setType("Free Text");
createQuestionPage.addQuestion(parameters);
}
return createQuestionPage.submitQuestions().verifyPage();
}
private void testMissingMandatoryInputs(CreateQuestionGroupPage createQuestionGroupPage) {
CreateQuestionGroupParameters parameters = new CreateQuestionGroupParameters();
createQuestionGroupPage.submit(parameters);
assertTextFoundOnPage(TITLE_MISSING);
assertTextFoundOnPage(APPLIES_TO_MISSING);
assertTextFoundOnPage(SECTION_MISSING);
createQuestionGroupPage.addEmptySection("Empty Section");
for (String section : parameters.getExistingQuestions().keySet()) {
createQuestionGroupPage.addExistingQuestion(section, parameters.getExistingQuestions().get(section));
}
assertTextFoundOnPage(QUESTION_MISSING);
}
private void testCancelCreateQuestionGroup(CreateQuestionGroupPage createQuestionGroupPage) {
createQuestionGroupPage.cancel();
assertPage(AdminPage.PAGE_ID);
}
private void testQuestionGroupDetail(ViewAllQuestionGroupsPage viewAllQuestionGroupsPage, String title,
String sectionName, List<String> questions, List<String> mandatoryQuestions) {
QuestionGroupDetailPage questionGroupDetailPage = navigateToQuestionGroupDetailPage(viewAllQuestionGroupsPage, title);
testQuestionGroupDetail(questionGroupDetailPage, title, sectionName, questions, mandatoryQuestions);
questionGroupDetailPage.navigateToViewQuestionGroupsPage().verifyPage();
}
private QuestionGroupDetailPage navigateToQuestionGroupDetailPage(ViewAllQuestionGroupsPage viewAllQuestionGroupsPage, String title) {
QuestionGroupDetailPage questionGroupDetailPage = viewAllQuestionGroupsPage.navigateToQuestionGroupDetailPage(title);
questionGroupDetailPage.verifyPage();
return questionGroupDetailPage;
}
private void testQuestionGroupDetail(QuestionGroupDetailPage questionGroupDetailPage, String title, String sectionName,
List<String> questions, List<String> mandatoryQuestions) {
assertEquals(title, questionGroupDetailPage.getTitle());
assertEquals(APPLIES_TO_CREATE_CLIENT, questionGroupDetailPage.getAppliesTo());
assertTrue(questionGroupDetailPage.getSections().contains(sectionName));
assertEquals(questions, questionGroupDetailPage.getSectionsQuestions(sectionName));
assertEquals(mandatoryQuestions, questionGroupDetailPage.getMandatoryQuestions(sectionName));
}
private CreateQuestionGroupPage getCreateQuestionGroupPage(AdminPage adminPage) {
return adminPage.navigateToCreateQuestionGroupPage();
}
private void testViewQuestionGroups(ViewAllQuestionGroupsPage viewQuestionGroupsPage) {
String[] questionGroups = viewQuestionGroupsPage.getAllQuestionGroups();
Assert.assertTrue(contains(questionGroups, qgTitle1));
Assert.assertTrue(contains(questionGroups, qgTitle2));
Assert.assertTrue(indexOf(questionGroups, qgTitle2, indexOf(questionGroups, qgTitle1, 0)) > 0);
}
private ViewAllQuestionGroupsPage getViewQuestionGroupsPage(AdminPage adminPage) {
return adminPage.navigateToViewAllQuestionGroups().verifyPage();
}
private AdminPage getAdminPage() {
HomePage homePage = appLauncher.launchMifos().loginSuccessfullyUsingDefaultCredentials();
return homePage.navigateToAdminPage().verifyPage();
}
private void testShouldAllowDuplicateTitlesForQuestionGroup() {
testCreateQuestionGroup(getCreateQuestionGroupPage(new AdminPage(selenium)), qgTitle2, APPLIES_TO_CREATE_CLIENT, false, "", asList(qTitle1, qTitle3), asList(qTitle2), null);
testCreateQuestionGroup(getCreateQuestionGroupPage(new AdminPage(selenium)), qgTitle2, APPLIES_TO_CREATE_CLIENT, false, "Hello", asList(qTitle2), asList(qTitle1, qTitle3), null);
}
private void testCreateQuestionGroup(CreateQuestionGroupPage createQuestionGroupPage, String title, String appliesTo, boolean isAnswerEditable,
String sectionName, List<String> questionsToSelect, List<String> questionsNotToSelect, String questionToAdd) {
CreateQuestionGroupParameters parameters = new CreateQuestionGroupParameters();
parameters.setTitle(title);
parameters.setAppliesTo(appliesTo);
parameters.setAnswerEditable(isAnswerEditable);
for (String question : questionsToSelect) {
parameters.addExistingQuestion(sectionName, question);
}
for (String section : parameters.getExistingQuestions().keySet()) {
createQuestionGroupPage.addExistingQuestion(section, parameters.getExistingQuestions().get(section));
}
createQuestionGroupPage.markEveryOtherQuestionsMandatory(questionsToSelect);
assertTrue(createQuestionGroupPage.getAvailableQuestions().containsAll(questionsNotToSelect));
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setType("Free Text");
createQuestionParameters.setText(questionToAdd);
createQuestionGroupPage.setSection(SECTION_MISC);
if (questionToAdd != null) {
createQuestionGroupPage.addNewQuestion(createQuestionParameters);
}
createQuestionGroupPage.submit(parameters);
assertPage(AdminPage.PAGE_ID);
}
private Integer latestInstanceId(Map<Integer, QuestionGroup> questionGroups) {
Set<Integer> keys = questionGroups.keySet();
return Collections.max(keys);
}
private void editResponses(ClientViewDetailsPage clientViewDetailsPage, int id, Map<String,String> answers) {
QuestionGroupResponsePage questionGroupResponsePage = clientViewDetailsPage.navigateToQuestionGroupResponsePage(id);
QuestionnairePage questionnairePage = questionGroupResponsePage.navigateToEditResponses();
for(String question: answers.keySet()) {
questionnairePage.setResponse(question, answers.get(question));
}
ClientViewDetailsPage clientViewDetailsPage2 = (ClientViewDetailsPage)questionnairePage.submit();
Assert.assertEquals(clientViewDetailsPage2.getQuestionGroupInstances().get(id).getName(), "TestQuestionGroup");
}
}
| acceptanceTests/src/test/java/org/mifos/test/acceptance/questionnaire/QuestionGroupTest.java | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.test.acceptance.questionnaire;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mifos.test.acceptance.framework.AppLauncher;
import org.mifos.test.acceptance.framework.HomePage;
import org.mifos.test.acceptance.framework.MifosPage;
import org.mifos.test.acceptance.framework.UiTestCaseBase;
import org.mifos.test.acceptance.framework.admin.AdminPage;
import org.mifos.test.acceptance.framework.admin.DefineNewOfficePage;
import org.mifos.test.acceptance.framework.admin.ManageRolePage;
import org.mifos.test.acceptance.framework.admin.ViewRolesPage;
import org.mifos.test.acceptance.framework.client.ClientCloseReason;
import org.mifos.test.acceptance.framework.client.ClientStatus;
import org.mifos.test.acceptance.framework.client.ClientViewChangeLogPage;
import org.mifos.test.acceptance.framework.client.ClientViewDetailsPage;
import org.mifos.test.acceptance.framework.client.CreateClientEnterPersonalDataPage;
import org.mifos.test.acceptance.framework.client.QuestionGroup;
import org.mifos.test.acceptance.framework.customer.CustomerChangeStatusPage;
import org.mifos.test.acceptance.framework.group.EditCustomerStatusParameters;
import org.mifos.test.acceptance.framework.loan.QuestionResponseParameters;
import org.mifos.test.acceptance.framework.office.CreateOfficePreviewDataPage;
import org.mifos.test.acceptance.framework.office.OfficeParameters;
import org.mifos.test.acceptance.framework.office.OfficeViewDetailsPage;
import org.mifos.test.acceptance.framework.questionnaire.AttachQuestionGroupParameters;
import org.mifos.test.acceptance.framework.questionnaire.Choice;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionGroupPage;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionGroupParameters;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionPage;
import org.mifos.test.acceptance.framework.questionnaire.CreateQuestionParameters;
import org.mifos.test.acceptance.framework.questionnaire.EditQuestionGroupPage;
import org.mifos.test.acceptance.framework.questionnaire.EditQuestionPage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionDetailPage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionGroupDetailPage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionGroupResponsePage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionResponsePage;
import org.mifos.test.acceptance.framework.questionnaire.QuestionnairePage;
import org.mifos.test.acceptance.framework.questionnaire.ViewAllQuestionGroupsPage;
import org.mifos.test.acceptance.framework.questionnaire.ViewAllQuestionsPage;
import org.mifos.test.acceptance.framework.questionnaire.ViewQuestionResponseDetailPage;
import org.mifos.test.acceptance.framework.testhelpers.ClientTestHelper;
import org.mifos.test.acceptance.framework.testhelpers.OfficeHelper;
import org.mifos.test.acceptance.framework.testhelpers.QuestionGroupTestHelper;
import org.mifos.test.acceptance.util.StringUtil;
import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static java.util.Arrays.*; //NOPMD
import static org.apache.commons.lang.ArrayUtils.*; //NOPMD
import static org.junit.Assert.*; //NOPMD
@ContextConfiguration(locations = {"classpath:ui-test-context.xml"})
@SuppressWarnings("PMD.CyclomaticComplexity")
@Test(singleThreaded = true, groups = {"client", "acceptance", "ui", "no_db_unit"})
public class QuestionGroupTest extends UiTestCaseBase {
private AppLauncher appLauncher;
private OfficeHelper officeHelper;
private QuestionGroupTestHelper questionGroupTestHelper;
private ClientTestHelper clientTestHelper;
private String qgTitle1, qgTitle2, qgTitle3, qgTitle4;
private String qTitle1, qTitle2, qTitle3, qTitle4, qTitle5;
private static final String TITLE_MISSING = "Please specify Question Group title.";
private static final String APPLIES_TO_MISSING = "Please choose a valid 'Applies To' value.";
private static final String SECTION_MISSING = "Please add at least one section.";
private static final String QUESTION_MISSING = "Section should have at least one question.";
public static final String APPLIES_TO_CREATE_CLIENT = "Create Client";
public static final String SECTION_DEFAULT = "Default";
private static final String SECTION_MISC = "Misc";
private static final int CREATE_OFFICE_QUESTION_GROUP_ID = 12;
private static final String CLIENT = "WeeklyClient Wednesday";
private Map<Integer, QuestionGroup> questionGroupInstancesOfClient;
private static final List<String> charactersList = new ArrayList<String>(Arrays.asList("عربية", "有", "òèßñ"));
private static final String noNumber = "qwerty";
private static final List<String> EMPTY_LIST = new ArrayList<String>();
private static final List<String> QUESTIONS_LIST = new ArrayList<String>(Arrays.asList("QGForViewClientCentreGroupLoan",
"ViewCenterQG", "QGForCreateSavingsAccount", "QGForViewSavings", "QGForCreateLoan1", "QGForCreateLoan2", "QGForLoanApproval",
"QGForApproveLoan1", "QGForApproveLoan2", "QGForDisburseLoan1", "QGForDisburseLoan2"));
private static final Map<String, String> QUESTIONS = new HashMap<String, String>();
private static final String ADMIN_ROLE = "Admin";
private static final String QUESTION_PERMISSION_ID = "9_6_0";
private static final String QUESTION_PERMISSION_HEADER = "Can edit ";
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
super.setUp();
officeHelper = new OfficeHelper(selenium);
appLauncher = new AppLauncher(selenium);
questionGroupTestHelper = new QuestionGroupTestHelper(selenium);
clientTestHelper = new ClientTestHelper(selenium);
questionGroupInstancesOfClient = new HashMap<Integer, QuestionGroup>();
qgTitle1 = "QuestionGroup1";
qgTitle2 = "QuestionGroup2";
qgTitle3 = "QuestionGroup3";
qgTitle4 = "QuestionGroup4";
qTitle1 = "Question1";
qTitle2 = "Question2";
qTitle3 = "Question3";
qTitle4 = "Question4";
qTitle5 = "Question5";
QUESTIONS.put("TextQuestionTest", CreateQuestionParameters.TYPE_FREE_TEXT);
QUESTIONS.put("DateQuestionTest", CreateQuestionParameters.TYPE_DATE);
QUESTIONS.put("NumberQuestionTest", CreateQuestionParameters.TYPE_NUMBER);
QUESTIONS.put("MultiSelectQuestionTest", CreateQuestionParameters.TYPE_MULTI_SELECT);
QUESTIONS.put("SingleSelectQuestionTest", CreateQuestionParameters.TYPE_SINGLE_SELECT);
QUESTIONS.put("SmartSelectQuestionTest", CreateQuestionParameters.TYPE_SMART_SELECT);
}
@AfterMethod
public void logOut() {
(new MifosPage(selenium)).logout();
}
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void createQuestionGroup() throws Exception {
try {
AdminPage adminPage = createQuestions(qTitle1, qTitle2, qTitle3);
CreateQuestionGroupPage createQuestionGroupPage = getCreateQuestionGroupPage(adminPage);
testMissingMandatoryInputs(createQuestionGroupPage);
testCreateQuestionGroup(createQuestionGroupPage, qgTitle1, APPLIES_TO_CREATE_CLIENT, true, SECTION_DEFAULT, asList(qTitle1, qTitle2), asList(qTitle3), qTitle4);
testShouldAllowDuplicateTitlesForQuestionGroup();
testCancelCreateQuestionGroup(getCreateQuestionGroupPage(new AdminPage(selenium)));
testViewQuestionGroups();
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle1);
questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle2);
questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle3);
}
}
@Test(enabled = true)
public void checkQuestionGroupPermission() {
AdminPage adminPage = getAdminPage();
CreateQuestionGroupPage createQuestionGroupPage = getCreateQuestionGroupPage(adminPage);
CreateQuestionGroupParameters parameters = new CreateQuestionGroupParameters();
parameters.setTitle(qgTitle4);
parameters.setAppliesTo(APPLIES_TO_CREATE_CLIENT);
parameters.setAnswerEditable(true);
for (String question : asList(qTitle1, qTitle2)) {
parameters.addExistingQuestion(SECTION_DEFAULT, question);
}
for (String section : parameters.getExistingQuestions().keySet()) {
createQuestionGroupPage.addExistingQuestion(section, parameters.getExistingQuestions().get(section));
}
createQuestionGroupPage.submit(parameters);
ViewRolesPage rolesPage = adminPage.navigateToViewRolesPage();
ManageRolePage manageRolePage = rolesPage.navigateToManageRolePage(ADMIN_ROLE);
manageRolePage.verifyPermissionText(QUESTION_PERMISSION_ID, QUESTION_PERMISSION_HEADER + qgTitle4);
manageRolePage.disablePermission(QUESTION_PERMISSION_ID);
manageRolePage.submitAndGotoViewRolesPage();
adminPage = getAdminPage();
Assert.assertTrue(adminPage.navigateToViewAllQuestionGroups().navigateToQuestionGroupDetailPage(qgTitle4).isAccessDeniedDisplayed());
}
/**
* Verify that user is able to edit the defined Question Groups
* and create Office with edited Question Group
* http://mifosforge.jira.com/browse/MIFOSTEST-666
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void editQuestionGroupsForCreateOffice() throws Exception {
//When
ViewAllQuestionGroupsPage viewAllQuestionGroupsPage = questionGroupTestHelper.navigateToViewQuestionGroups(QUESTIONS_LIST);
String oldTitle = "CreateOffice";
EditQuestionGroupPage editQuestionGroupPage = viewAllQuestionGroupsPage.navigateToQuestionGroupDetailPage(oldTitle).navigateToEditPage();
editQuestionGroupPage.moveSectionUp("Misc");
editQuestionGroupPage.moveQuestionUp(9);
editQuestionGroupPage.moveQuestionDown(2);
String newTitle = "CreateOfficeQG";
QuestionGroupDetailPage questionGroupDetailPage = editQuestionGroupPage.editQuestionGroup(false, newTitle, "Create Office", Collections.<String>emptyList());
//Then
questionGroupDetailPage.verifyOrderQuestions(asList("MultiSelect", "Date", "FreeText"), 4);
questionGroupDetailPage.verifyOrderSections(asList("Misc", "Default"));
questionGroupDetailPage.verifyMandatoryQuestions(Arrays.asList("FreeText"), "Misc");
questionGroupDetailPage.verifyMandatoryQuestions(EMPTY_LIST, "Default");
questionGroupDetailPage.verifyTitle(newTitle);
questionGroupTestHelper.markQuestionGroupAsActive(newTitle);
createOfficeWithQuestionGroup();
questionGroupTestHelper.markQuestionGroupAsInactive(newTitle);
//When
viewAllQuestionGroupsPage = questionGroupDetailPage.navigateToViewQuestionGroupsPage();
//Then
viewAllQuestionGroupsPage.verifyInactiveQuestions(0, 0);
}
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private void createOfficeWithQuestionGroup() throws Exception {
//When
QuestionResponsePage questionResponsePage = officeHelper.navigateToQuestionResponsePage(getOfficeParameters("MyOfficeDHMFT", "DHM"));
QuestionResponseParameters initialResponse = getResponse("123");
QuestionResponseParameters updatedResponse = getResponse("1234");
CreateOfficePreviewDataPage createOfficePreviewDataPage = questionGroupTestHelper.createOfficeWithQuestionGroup(questionResponsePage, initialResponse, updatedResponse);
assertTextFoundOnPage("This office name already exist");
DefineNewOfficePage defineNewOfficePage = createOfficePreviewDataPage.editOfficeInformation();
defineNewOfficePage.setOfficeName("TestOffice");
defineNewOfficePage.setOfficeShortName("TO");
defineNewOfficePage.preview();
defineNewOfficePage.next();
OfficeViewDetailsPage officeViewDetailsPage = createOfficePreviewDataPage.submit().navigateToOfficeViewDetailsPage();
ViewQuestionResponseDetailPage viewQuestionResponseDetailPage = officeViewDetailsPage.navigateToViewAdditionalInformation();
viewQuestionResponseDetailPage.verifyQuestionPresent("FreeText", "1234");
officeViewDetailsPage = viewQuestionResponseDetailPage.navigateToDetailsPage();
String newQuestion = "Text";
addQuestion(newQuestion, "Default", CREATE_OFFICE_QUESTION_GROUP_ID);
String questionToDeactivate = "FreeText";
questionGroupTestHelper.markQuestionAsInactive(questionToDeactivate);
questionResponsePage = officeHelper.navigateToQuestionResponsePage(getOfficeParameters("TestOffice2", "TO2"));
//Then
questionResponsePage.verifyQuestionsDoesnotappear(new String[]{questionToDeactivate});
questionResponsePage.verifyQuestionsExists(new String[]{newQuestion});
officeHelper.verifyQuestionPresent("TestOffice", "Text", "");
}
/**
* Verifying that Change Log for Question Groups has an appropriate format
* http://mifosforge.jira.com/browse/MIFOSTEST-667
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void testChangeLog() throws Exception {
String questionGroup = "CreateClientQG-1";
try {
questionGroupTestHelper.markQuestionAsActive("FreeText");
questionGroupTestHelper.markQuestionGroupAsActive(questionGroup);
//Given
ClientViewDetailsPage clientViewDetailsPage = clientTestHelper.navigateToClientViewDetailsPage(CLIENT);
//When
clientViewDetailsPage = clientTestHelper.editQuestionGroupResponses(
clientViewDetailsPage, "0", "details[0].sectionDetails[0].questions[0].value", "qwert"
);
//Then
ClientViewChangeLogPage clientViewChangeLogPage = clientViewDetailsPage.navigateToClientViewChangeLog();
clientViewChangeLogPage.verifyChangeLog(asList("CreateClientQG-1/Misc/FreeText"),
asList("-"), asList("qwert"), asList("mifos"), 2);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(questionGroup);
}
}
private void addQuestion(String newQuestion, String section, int questionGroupId) {
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.addExistingQuestion(section, newQuestion);
questionGroupTestHelper.addQuestionsToQuestionGroup(questionGroupId, createQuestionGroupParameters.getExistingQuestions());
}
private OfficeParameters getOfficeParameters(String name, String shortName) {
OfficeParameters officeParameters = new OfficeParameters();
officeParameters.setOfficeName(name);
officeParameters.setOfficeType(OfficeParameters.REGIONAL_OFFICE);
officeParameters.setParentOffice("Head Office(Mifos HO )");
officeParameters.setShortName(shortName);
return officeParameters;
}
private QuestionResponseParameters getResponse(String answer) {
QuestionResponseParameters initialResponse = new QuestionResponseParameters();
initialResponse.addTextAnswer("questionGroups[0].sectionDetails[0].questions[2].value", answer);
return initialResponse;
}
/**
* Creating and editing Questions
* http://mifosforge.jira.com/browse/MIFOSTEST-700
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void createAndEditQuestionsTest() throws Exception {
//When
testValidationAddQuestion();
CreateQuestionPage createQuestionPage = questionGroupTestHelper.navigateToCreateQuestionPage();
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setText("TextQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_FREE_TEXT);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("DateQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_DATE);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("NumberQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_NUMBER);
createQuestionParameters.setNumericMin(1);
createQuestionParameters.setNumericMax(10);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("MultiSelectQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_MULTI_SELECT);
List<Choice> choices = new ArrayList<Choice>();
Choice c = new Choice("choice 1", EMPTY_LIST);
choices.add(c);
c = new Choice("choice 2", EMPTY_LIST);
choices.add(c);
c = new Choice("choice 3", EMPTY_LIST);
choices.add(c);
createQuestionParameters.setChoices(choices);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("SingleSelectQuestionTest");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_SINGLE_SELECT);
createQuestionParameters.setChoices(choices);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionParameters.setText("SmartSelectQuestionTest");
createQuestionParameters.setChoices(choices);
createQuestionParameters.setType(CreateQuestionParameters.TYPE_SMART_SELECT);
createQuestionPage.addQuestion(createQuestionParameters);
AdminPage adminPage = createQuestionPage.submitQuestions();
ViewAllQuestionsPage viewAllQuestionsPage = adminPage.navigateToViewAllQuestions();
//Then
viewAllQuestionsPage.verifyQuestions(QUESTIONS.keySet());
//When
c = new Choice("answerChoice1", EMPTY_LIST);
choices.add(c);
c = new Choice("answerChoice3", EMPTY_LIST);
choices.add(c);
for (String question : QUESTIONS.keySet()) {
QuestionDetailPage questionDetailPage = viewAllQuestionsPage.navigateToQuestionDetail(question);
EditQuestionPage editQuestionPage = questionDetailPage.navigateToEditQuestionPage();
createQuestionParameters.setText("");
editQuestionPage.tryUpdate(createQuestionParameters);
//Then
editQuestionPage.verifyTextPresent("Please specify the question", "No text <Please specify the question> present on the page");
questionDetailPage = editQuestionPage.cancelEdit();
//When
editQuestionPage = questionDetailPage.navigateToEditQuestionPage();
for (String characters : charactersList) {
editQuestionPage.setQuestionName(characters);
editQuestionPage.verifyQuestionName(characters);
}
if ("NumberQuestionTest".equals(question)) {
editQuestionPage.setNumberQuestion(noNumber, noNumber);
editQuestionPage.verifyNumberQuestion("", "");
editQuestionPage.setNumberQuestion("", "");
} else if ("MultiSelectQuestionTest".equals(question) || "SingleSelectQuestionTest".equals(question)) {
editQuestionPage.addAnswerChoices(asList("answerChoice1", "answerChoice2", "answerChoice3"));
editQuestionPage.removeAnswerChoice("4");
} else if ("SmartSelectQuestionTest".equals(question)) {
editQuestionPage.addSmartAnswerChoices(asList("answerChoice1", "answerChoice2", "answerChoice3"));
editQuestionPage.removeAnswerChoice("4");
}
editQuestionPage.setQuestionName(question + "Edit");
questionDetailPage = editQuestionPage.deactivate();
//Then
questionDetailPage.verifyQuestionTitle(question + "Edit");
if ("MultiSelectQuestionTest".equals(question) || "SingleSelectQuestionTest".equals(question) || "SmartSelectQuestionTest".equals(question)) {
questionDetailPage.assertForChoices(QUESTIONS.get(question), choices);
}
viewAllQuestionsPage = questionDetailPage.navigateToViewAllQuestionsPage();
}
}
/**
* Attaching a Question Group to Multiple flows
* http://mifosforge.jira.com/browse/MIFOSTEST-701
*
* @throws Exception
*/
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void attachingQuestionGroupToMultipleFlowsTest() throws Exception {
String newClient = "Joe701 Doe701";
questionGroupTestHelper.markQuestionGroupAsInactive("CreateOffice");
createClient("Joe701","Doe701");
//When
testValidationAddQuestionGroup();
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
questions.add("Date");
questions.add("Number");
questions.add("Text");
sectionQuestions.put("Sec Test", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setAnswerEditable(true);
String testQuestionGroup = "TestQuestionGroup";
createQuestionGroupParameters.setTitle(testQuestionGroup);
createQuestionGroupParameters.setAppliesTo("View Client");
createQuestionGroupParameters.setAppliesTo("Close Client");
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
try {
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
Map<String, String> answers = new HashMap<String, String>();
answers.put("Text", "Test - Text");
answers.put("Number", "2");
answers.put("Date", "11/11/2009");
ClientViewDetailsPage clientViewDetailsPage = questionGroupTestHelper.attachQuestionGroup(newClient, testQuestionGroup, asList("Sec Test"), answers);
CustomerChangeStatusPage customerChangeStatusPage = clientViewDetailsPage.navigateToCustomerChangeStatusPage();
EditCustomerStatusParameters customerStatusParameters = new EditCustomerStatusParameters();
customerStatusParameters.setNote("TEST");
customerStatusParameters.setClientStatus(ClientStatus.CLOSED);
customerStatusParameters.setClientCloseReason(ClientCloseReason.TRANSFERRED);
QuestionResponsePage questionResponsePage = customerChangeStatusPage.changeStatusAndNavigateToQuestionResponsePage(customerStatusParameters);
//Then
questionResponsePage.verifyQuestionsExists(questions.toArray(new String[questions.size()]));
//When
clientViewDetailsPage = questionResponsePage.cancel();
ViewQuestionResponseDetailPage viewQuestionResponseDetailPage = clientViewDetailsPage.navigateToViewAdditionalInformationPage();
//Then
viewQuestionResponseDetailPage.verifyQuestionsDoesnotappear(questions.toArray(new String[questions.size()]));
clientViewDetailsPage = viewQuestionResponseDetailPage.navigateToClientViewDetailsPage();
answers = new HashMap<String, String>();
answers.put("Text", "Test - Text - Edit");
answers.put("Number", "22");
questionGroupInstancesOfClient = clientViewDetailsPage.getQuestionGroupInstances();
questionGroupTestHelper.editResponses(clientViewDetailsPage, latestInstanceId(questionGroupInstancesOfClient), answers);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(testQuestionGroup);
questionGroupTestHelper.markQuestionGroupAsInactive("CreateOffice");
}
}
private void createClient(String firstName, String lastName) {
String groupName = "group1";
CreateClientEnterPersonalDataPage.SubmitFormParameters clientParams = new CreateClientEnterPersonalDataPage.SubmitFormParameters();
clientParams.setSalutation(CreateClientEnterPersonalDataPage.SubmitFormParameters.MRS);
clientParams.setFirstName(firstName);
clientParams.setLastName(lastName);
clientParams.setDateOfBirthDD("22");
clientParams.setDateOfBirthMM("06");
clientParams.setDateOfBirthYYYY("1987");
clientParams.setGender(CreateClientEnterPersonalDataPage.SubmitFormParameters.MALE);
clientParams.setPovertyStatus(CreateClientEnterPersonalDataPage.SubmitFormParameters.NOT_POOR);
clientParams.setSpouseNameType(CreateClientEnterPersonalDataPage.SubmitFormParameters.FATHER);
clientParams.setSpouseFirstName("fatherNameTest");
clientParams.setSpouseLastName("fatherLastNameTest");
clientTestHelper.createNewClient(groupName, clientParams);
clientTestHelper.activateClient(firstName + " " + lastName);
}
@Test(enabled=true)
//http://mifosforge.jira.com/browse/MIFOSTEST-660
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void verifyAttachingQuestionGroupToGroup() throws Exception {
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
String title = "TestQuestionGroup" + StringUtil.getRandomString(6);
questions.add("Date");
questions.add("question 3");
questions.add("question 4");
sectionQuestions.put("Sec 1", questions);
questions = new ArrayList<String>();
questions.add("DateQuestion");
questions.add("Number");
questions.add("question 1");
questions.add("Text");
sectionQuestions.put("Sec 2", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setAnswerEditable(true);
createQuestionGroupParameters.setAppliesTo("View Group");
createQuestionGroupParameters.setTitle(title);
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
AttachQuestionGroupParameters attachParams = new AttachQuestionGroupParameters();
attachParams.setTarget("Default Group");
attachParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachParams.addTextResponse("Date", "09/02/2011");
attachParams.addCheckResponse("question 4", "yes");
attachParams.addTextResponse("DateQuestion", "19/02/2011");
attachParams.addTextResponse("question 3", "25/02/2011");
attachParams.addTextResponse("Number", "60");
attachParams.addTextResponse("question 1", "tekst tekst");
attachParams.addTextResponse("Text", "ale alo olu");
AttachQuestionGroupParameters attachErrorParams = new AttachQuestionGroupParameters();
attachErrorParams.setTarget("Default Group");
attachErrorParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachErrorParams.addTextResponse("Number", "sdfsdf");
attachErrorParams.addTextResponse("question 3", "25/02/2011");
attachErrorParams.addCheckResponse("question 4", "yes");
attachErrorParams.addError("Please specify a number for Number.");
//When
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
questionGroupTestHelper.verifyErrorsWhileAttachingQuestionGroupToGroup(attachErrorParams);
questionGroupTestHelper.attachQuestionGroupToGroup(attachParams);
attachParams.addTextResponse("Number", "20");
attachParams.addTextResponse("question 3", "21/02/2011");
//Then
questionGroupTestHelper.editQuestionGroupResponsesInGroup(attachParams);
questionGroupTestHelper.markQuestionGroupAsInactive(title);
}
@Test(enabled=true)
//http://mifosforge.jira.com/browse/MIFOSTEST-662
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void verifyAttachingQuestionGroupToLoan() throws Exception {
String title = "TestQuestionGroup" + StringUtil.getRandomString(6);
try {
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
questions.add("question 4");
questions.add("question 3");
questions.add("Date");
sectionQuestions.put("Sec 1", questions);
questions = new ArrayList<String>();
questions.add("question 1");
questions.add("Number");
questions.add("DateQuestion");
questions.add("Text");
sectionQuestions.put("Sec 2", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setAppliesTo("View Loan");
createQuestionGroupParameters.setAnswerEditable(true);
createQuestionGroupParameters.setTitle(title);
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
AttachQuestionGroupParameters attachParams = new AttachQuestionGroupParameters();
attachParams.setTarget("000100000000012");
attachParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachParams.addCheckResponse("question 4", "yes");
attachParams.addTextResponse("Date", "09/02/2011");
attachParams.addTextResponse("DateQuestion", "19/02/2011");
attachParams.addTextResponse("question 3", "25/02/2011");
attachParams.addTextResponse("question 1", "tekst tekst");
attachParams.addTextResponse("Text", "ale alo olu");
attachParams.addTextResponse("Number", "60");
AttachQuestionGroupParameters attachErrorParams = new AttachQuestionGroupParameters();
attachErrorParams.setTarget("000100000000012");
attachErrorParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachErrorParams.addError("Please specify a number for Number.");
attachErrorParams.addTextResponse("Number", "sdfsdf");
attachErrorParams.addTextResponse("question 3", "25/02/2011");
attachErrorParams.addCheckResponse("question 4", "yes");
//When
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
questionGroupTestHelper.verifyErrorsWhileAttachingQuestionGroupToLoan(attachErrorParams);
questionGroupTestHelper.attachQuestionGroupToLoan(attachParams);
attachParams.addTextResponse("Number", "20");
attachParams.addTextResponse("question 3", "21/02/2011");
//Then
questionGroupTestHelper.editQuestionGroupResponsesInLoan(attachParams);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(title);
}
}
@Test(enabled=true)
//http://mifosforge.jira.com/browse/MIFOSTEST-680
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void verifyAttachingQuestionGroupToViewClient() throws Exception {
String title = "TestQuestionGroup" + StringUtil.getRandomString(6);
try {
Map<String, List<String>> sectionQuestions = new HashMap<String, List<String>>();
List<String> questions = new ArrayList<String>();
questions.add("Date");
questions.add("question 4");
questions.add("question 3");
sectionQuestions.put("Sec 1", questions);
questions = new ArrayList<String>();
questions.add("Number");
questions.add("DateQuestion");
questions.add("question 1");
questions.add("Text");
sectionQuestions.put("Sec 2", questions);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.setExistingQuestions(sectionQuestions);
createQuestionGroupParameters.setAnswerEditable(true);
createQuestionGroupParameters.setAppliesTo("View Client");
createQuestionGroupParameters.setTitle(title);
AttachQuestionGroupParameters attachParams = new AttachQuestionGroupParameters();
attachParams.setTarget("0002-000000003");
attachParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachParams.addTextResponse("Number", "60");
attachParams.addTextResponse("question 1", "tekst tekst");
attachParams.addCheckResponse("question 4", "yes");
attachParams.addTextResponse("question 3", "25/02/2011");
attachParams.addTextResponse("Date", "09/02/2011");
attachParams.addTextResponse("DateQuestion", "19/02/2011");
attachParams.addTextResponse("Text", "ale alo olu");
AttachQuestionGroupParameters attachErrorParams = new AttachQuestionGroupParameters();
attachErrorParams.setTarget("0002-000000003");
attachErrorParams.addError("Please specify a number for Number.");
attachErrorParams.setQuestionGroupName(createQuestionGroupParameters.getTitle());
attachErrorParams.addTextResponse("Number", "sdfsdf");
attachErrorParams.addCheckResponse("question 4", "yes");
attachErrorParams.addTextResponse("question 3", "25/02/2011");
//When
questionGroupTestHelper.createQuestionGroup(createQuestionGroupParameters);
questionGroupTestHelper.verifyErrorsWhileAttachingQuestionGroupToClient(attachErrorParams);
questionGroupTestHelper.attachQuestionGroupToClient(attachParams);
attachParams.addTextResponse("Number", "20");
attachParams.addTextResponse("question 3", "21/02/2011");
//Then
questionGroupTestHelper.editQuestionGroupResponsesInClient(attachParams);
} finally {
questionGroupTestHelper.markQuestionGroupAsInactive(title);
}
}
private void testValidationAddQuestionGroup() {
questionGroupTestHelper.validatePageBlankMandatoryField();
questionGroupTestHelper.validateQuestionGroupTitle(charactersList);
}
private void testValidationAddQuestion() {
CreateQuestionPage createQuestionPage = questionGroupTestHelper.navigateToCreateQuestionPage();
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setText("");
createQuestionParameters.setType(CreateQuestionParameters.TYPE_FREE_TEXT);
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionPage.verifyTextPresent("Please specify the question", "No text <Please specify the question> present on the page");
createQuestionPage.verifySubmitButtonStatus("true");
createQuestionPage.cancelQuestion();
createQuestionPage = questionGroupTestHelper.navigateToCreateQuestionPage();
createQuestionPage.setNumberQuestion("NumberQuestion", noNumber, noNumber);
createQuestionPage.verifyNumberQuestion("", "");
createQuestionPage.setNumberQuestion("NumberQuestion", "", "");
for (int i = 0; i < charactersList.size(); i++) {
createQuestionParameters.setText(charactersList.get(i));
createQuestionPage.addQuestion(createQuestionParameters);
createQuestionPage.verifyQuestionPresent(createQuestionParameters, i + 1);
}
}
private void testViewQuestionGroups() {
ViewAllQuestionGroupsPage viewQuestionGroupsPage = getViewQuestionGroupsPage(new AdminPage(selenium));
testViewQuestionGroups(viewQuestionGroupsPage);
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle1, SECTION_DEFAULT, asList(qTitle1, qTitle2), asList(qTitle1));
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle1, SECTION_MISC, asList(qTitle4), EMPTY_LIST);
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle2, SECTION_MISC, asList(qTitle1, qTitle3), asList(qTitle1));
testEditQuestionGroupDetail(viewQuestionGroupsPage.navigateToQuestionGroupDetailPage(qgTitle2));
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle3, SECTION_MISC, asList(qTitle1, qTitle3), asList(qTitle1));
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle3, "New Section", asList(qTitle4), EMPTY_LIST);
testQuestionGroupDetail(viewQuestionGroupsPage, qgTitle3, "Hello World", asList(qTitle5), EMPTY_LIST);
}
private void testEditQuestionGroupDetail(QuestionGroupDetailPage questionGroupDetailPage) {
EditQuestionGroupPage editQuestionGroupPage = questionGroupDetailPage.navigateToEditPage();
editQuestionGroupPage.setTitle(qgTitle3);
CreateQuestionGroupParameters createQuestionGroupParameters = new CreateQuestionGroupParameters();
createQuestionGroupParameters.addExistingQuestion("New Section", qTitle4);
for (String section : createQuestionGroupParameters.getExistingQuestions().keySet()) {
editQuestionGroupPage.addExistingQuestion(section, createQuestionGroupParameters.getExistingQuestions().get(section));
}
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setType("Free Text");
createQuestionParameters.setText(qTitle5);
editQuestionGroupPage.setSection("Hello World");
editQuestionGroupPage.addNewQuestion(createQuestionParameters);
editQuestionGroupPage.submit();
questionGroupDetailPage.verifyPage();
questionGroupDetailPage.navigateToViewQuestionGroupsPage();
}
private AdminPage createQuestions(String... qTitles) {
CreateQuestionPage createQuestionPage = getAdminPage().navigateToCreateQuestionPage();
CreateQuestionParameters parameters = new CreateQuestionParameters();
for (String qTitle : qTitles) {
parameters.setText(qTitle);
parameters.setType("Free Text");
createQuestionPage.addQuestion(parameters);
}
return createQuestionPage.submitQuestions().verifyPage();
}
private void testMissingMandatoryInputs(CreateQuestionGroupPage createQuestionGroupPage) {
CreateQuestionGroupParameters parameters = new CreateQuestionGroupParameters();
createQuestionGroupPage.submit(parameters);
assertTextFoundOnPage(TITLE_MISSING);
assertTextFoundOnPage(APPLIES_TO_MISSING);
assertTextFoundOnPage(SECTION_MISSING);
createQuestionGroupPage.addEmptySection("Empty Section");
for (String section : parameters.getExistingQuestions().keySet()) {
createQuestionGroupPage.addExistingQuestion(section, parameters.getExistingQuestions().get(section));
}
assertTextFoundOnPage(QUESTION_MISSING);
}
private void testCancelCreateQuestionGroup(CreateQuestionGroupPage createQuestionGroupPage) {
createQuestionGroupPage.cancel();
assertPage(AdminPage.PAGE_ID);
}
private void testQuestionGroupDetail(ViewAllQuestionGroupsPage viewAllQuestionGroupsPage, String title,
String sectionName, List<String> questions, List<String> mandatoryQuestions) {
QuestionGroupDetailPage questionGroupDetailPage = navigateToQuestionGroupDetailPage(viewAllQuestionGroupsPage, title);
testQuestionGroupDetail(questionGroupDetailPage, title, sectionName, questions, mandatoryQuestions);
questionGroupDetailPage.navigateToViewQuestionGroupsPage().verifyPage();
}
private QuestionGroupDetailPage navigateToQuestionGroupDetailPage(ViewAllQuestionGroupsPage viewAllQuestionGroupsPage, String title) {
QuestionGroupDetailPage questionGroupDetailPage = viewAllQuestionGroupsPage.navigateToQuestionGroupDetailPage(title);
questionGroupDetailPage.verifyPage();
return questionGroupDetailPage;
}
private void testQuestionGroupDetail(QuestionGroupDetailPage questionGroupDetailPage, String title, String sectionName,
List<String> questions, List<String> mandatoryQuestions) {
assertEquals(title, questionGroupDetailPage.getTitle());
assertEquals(APPLIES_TO_CREATE_CLIENT, questionGroupDetailPage.getAppliesTo());
assertTrue(questionGroupDetailPage.getSections().contains(sectionName));
assertEquals(questions, questionGroupDetailPage.getSectionsQuestions(sectionName));
assertEquals(mandatoryQuestions, questionGroupDetailPage.getMandatoryQuestions(sectionName));
}
private CreateQuestionGroupPage getCreateQuestionGroupPage(AdminPage adminPage) {
return adminPage.navigateToCreateQuestionGroupPage();
}
private void testViewQuestionGroups(ViewAllQuestionGroupsPage viewQuestionGroupsPage) {
String[] questionGroups = viewQuestionGroupsPage.getAllQuestionGroups();
Assert.assertTrue(contains(questionGroups, qgTitle1));
Assert.assertTrue(contains(questionGroups, qgTitle2));
Assert.assertTrue(indexOf(questionGroups, qgTitle2, indexOf(questionGroups, qgTitle1, 0)) > 0);
}
private ViewAllQuestionGroupsPage getViewQuestionGroupsPage(AdminPage adminPage) {
return adminPage.navigateToViewAllQuestionGroups().verifyPage();
}
private AdminPage getAdminPage() {
HomePage homePage = appLauncher.launchMifos().loginSuccessfullyUsingDefaultCredentials();
return homePage.navigateToAdminPage().verifyPage();
}
private void testShouldAllowDuplicateTitlesForQuestionGroup() {
testCreateQuestionGroup(getCreateQuestionGroupPage(new AdminPage(selenium)), qgTitle2, APPLIES_TO_CREATE_CLIENT, false, "", asList(qTitle1, qTitle3), asList(qTitle2), null);
testCreateQuestionGroup(getCreateQuestionGroupPage(new AdminPage(selenium)), qgTitle2, APPLIES_TO_CREATE_CLIENT, false, "Hello", asList(qTitle2), asList(qTitle1, qTitle3), null);
}
private void testCreateQuestionGroup(CreateQuestionGroupPage createQuestionGroupPage, String title, String appliesTo, boolean isAnswerEditable,
String sectionName, List<String> questionsToSelect, List<String> questionsNotToSelect, String questionToAdd) {
CreateQuestionGroupParameters parameters = new CreateQuestionGroupParameters();
parameters.setTitle(title);
parameters.setAppliesTo(appliesTo);
parameters.setAnswerEditable(isAnswerEditable);
for (String question : questionsToSelect) {
parameters.addExistingQuestion(sectionName, question);
}
for (String section : parameters.getExistingQuestions().keySet()) {
createQuestionGroupPage.addExistingQuestion(section, parameters.getExistingQuestions().get(section));
}
createQuestionGroupPage.markEveryOtherQuestionsMandatory(questionsToSelect);
assertTrue(createQuestionGroupPage.getAvailableQuestions().containsAll(questionsNotToSelect));
CreateQuestionParameters createQuestionParameters = new CreateQuestionParameters();
createQuestionParameters.setType("Free Text");
createQuestionParameters.setText(questionToAdd);
createQuestionGroupPage.setSection(SECTION_MISC);
if (questionToAdd != null) {
createQuestionGroupPage.addNewQuestion(createQuestionParameters);
}
createQuestionGroupPage.submit(parameters);
assertPage(AdminPage.PAGE_ID);
}
private Integer latestInstanceId(Map<Integer, QuestionGroup> questionGroups) {
Set<Integer> keys = questionGroups.keySet();
return Collections.max(keys);
}
private void editResponses(ClientViewDetailsPage clientViewDetailsPage, int id, Map<String,String> answers) {
QuestionGroupResponsePage questionGroupResponsePage = clientViewDetailsPage.navigateToQuestionGroupResponsePage(id);
QuestionnairePage questionnairePage = questionGroupResponsePage.navigateToEditResponses();
for(String question: answers.keySet()) {
questionnairePage.setResponse(question, answers.get(question));
}
ClientViewDetailsPage clientViewDetailsPage2 = (ClientViewDetailsPage)questionnairePage.submit();
Assert.assertEquals(clientViewDetailsPage2.getQuestionGroupInstances().get(id).getName(), "TestQuestionGroup");
}
}
| fixed acceptance tests
| acceptanceTests/src/test/java/org/mifos/test/acceptance/questionnaire/QuestionGroupTest.java | fixed acceptance tests | <ide><path>cceptanceTests/src/test/java/org/mifos/test/acceptance/questionnaire/QuestionGroupTest.java
<ide> manageRolePage.submitAndGotoViewRolesPage();
<ide> adminPage = getAdminPage();
<ide> Assert.assertTrue(adminPage.navigateToViewAllQuestionGroups().navigateToQuestionGroupDetailPage(qgTitle4).isAccessDeniedDisplayed());
<add> //set question group on inactive
<add> adminPage.navigateBack();
<add> adminPage.navigateToAdminPageUsingHeaderTab();
<add> manageRolePage = adminPage.navigateToViewRolesPage().navigateToManageRolePage(ADMIN_ROLE);
<add> manageRolePage.verifyPermissionText(QUESTION_PERMISSION_ID, QUESTION_PERMISSION_HEADER + qgTitle4);
<add> manageRolePage.enablePermission(QUESTION_PERMISSION_ID);
<add> manageRolePage.submitAndGotoViewRolesPage().navigateToAdminPage().navigateToViewAllQuestionGroups().navigateToQuestionGroupDetailPage(qgTitle4);
<add> questionGroupTestHelper.markQuestionGroupAsInactive(qgTitle4);
<add>
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 2802ca53d5e45f98870cff717e034fb21b49deba | 0 | gs1oliot/gs1source | package org.gs1.source.service.util;
public class CheckBit {
public boolean check(String gtin) {
int[] check = new int[13];
int sum = 0;
if(gtin.length() == 14) {
if(gtin.charAt(0) != '0') {
return false;
}
for(int i = 0; i < 13; i++) {
check[i] = Character.getNumericValue(gtin.charAt(i+1));
}
} else {
for(int i = 0; i < 13; i++) {
check[i] = Character.getNumericValue(gtin.charAt(i));
}
}
for(int i = 1; i < 12; i += 2) {
check[i] *= 3;
}
for(int i = 0; i < 12; i ++) {
sum += check[i];
}
int check_sum = 10 - (sum % 10);
if(check_sum == 10) {
check_sum = 0;
}
if(check[12] == check_sum) {
return true;
} else {
return false;
}
}
}
| DataAggregator/src/main/java/org/gs1/source/service/util/CheckBit.java | package org.gs1.source.service.util;
public class CheckBit {
public boolean check(String gtin) {
int[] check = new int[13];
int sum = 0;
if(gtin.length() == 14) {
if(gtin.charAt(0) != '0') {
return false;
}
for(int i = 0; i < 13; i++) {
check[i] = Character.getNumericValue(gtin.charAt(i+1));
}
} else {
for(int i = 0; i < 13; i++) {
check[i] = Character.getNumericValue(gtin.charAt(i));
}
}
for(int i = 1; i < 12; i += 2) {
check[i] *= 3;
}
for(int i = 0; i < 12; i ++) {
sum += check[i];
}
int check_sum = 10 - (sum % 10);
if(check[12] == check_sum) {
return true;
} else {
return false;
}
}
}
| modify CheckBit
| DataAggregator/src/main/java/org/gs1/source/service/util/CheckBit.java | modify CheckBit | <ide><path>ataAggregator/src/main/java/org/gs1/source/service/util/CheckBit.java
<ide>
<ide> int check_sum = 10 - (sum % 10);
<ide>
<add> if(check_sum == 10) {
<add> check_sum = 0;
<add> }
<add>
<ide> if(check[12] == check_sum) {
<ide> return true;
<ide> } else { |
|
Java | mit | 2d65a28979671d5f8f89fec918b689237117edc9 | 0 | PunchThrough/Bean-Android-SDK,PunchThrough/bean-sdk-android,PunchThrough/Bean-Android-SDK,PunchThrough/bean-sdk-android | package com.punchthrough.bean.sdk.internal.upload.firmware;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.util.Log;
import com.punchthrough.bean.sdk.BeanManager;
import com.punchthrough.bean.sdk.internal.ble.BaseProfile;
import com.punchthrough.bean.sdk.internal.ble.GattClient;
import com.punchthrough.bean.sdk.internal.device.DeviceProfile;
import com.punchthrough.bean.sdk.internal.utility.Constants;
import com.punchthrough.bean.sdk.internal.utility.Convert;
import com.punchthrough.bean.sdk.message.BeanError;
import com.punchthrough.bean.sdk.message.Callback;
import com.punchthrough.bean.sdk.message.UploadProgress;
import com.punchthrough.bean.sdk.upload.FirmwareBundle;
import com.punchthrough.bean.sdk.upload.FirmwareImage;
import java.util.Arrays;
import java.util.UUID;
public class OADProfile extends BaseProfile {
/**
* Custom OAD Profile for LightBlue Bean devices.
*
* This class encapsulates data and processes related to firmware updates to the CC2540.
*
*/
public static final String TAG = "OADProfile";
// OAD Characteristic handles
private BluetoothGattCharacteristic oadIdentify;
private BluetoothGattCharacteristic oadBlock;
// OAD Internal State
private FirmwareUploadState firmwareUploadState = FirmwareUploadState.INACTIVE;
private FirmwareImage currentImage;
private FirmwareBundle firmwareBundle;
private Runnable onComplete;
private Callback<BeanError> onError;
private Callback<UploadProgress> onProgress;
public OADProfile(GattClient client) {
super(client);
resetState();
}
private void setState(FirmwareUploadState state) {
Log.i(TAG, String.format("OAD State Change: %s -> %s", firmwareUploadState.name(), state.name()));
firmwareUploadState = state;
}
private void resetState() {
setState(FirmwareUploadState.INACTIVE);
onComplete = null;
onError = null;
currentImage = null;
}
private void offerNextImage() {
currentImage = firmwareBundle.getNextImage();
Log.i(TAG, "Offering image: " + currentImage.name());
writeToCharacteristic(oadIdentify, currentImage.metadata());
}
private void startOfferingImages() {
setState(FirmwareUploadState.OFFERING_IMAGES);
firmwareBundle.reset();
offerNextImage();
}
private void onNotificationIdentify(BluetoothGattCharacteristic characteristic) {
offerNextImage();
}
private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
int blk = Convert.twoBytesToInt(characteristic.getValue(), Constants.CC2540_BYTE_ORDER);
if (blk == 0) {
Log.i(TAG, "Image accepted: " + currentImage.name());
Log.i(TAG, String.format("Starting Block Transfer of %d blocks", currentImage.blockCount()));
setState(FirmwareUploadState.BLOCK_XFER);
}
if (blk % 100 == 0) {
Log.i(TAG, "Block request: " + blk);
}
writeToCharacteristic(oadBlock, currentImage.block(blk));
onProgress.onResult(UploadProgress.create(blk, currentImage.blockCount()));
if (blk == currentImage.blockCount() - 1) {
Log.i(TAG, "Last block sent!");
Log.i(TAG, "Waiting for device to reconnect...");
}
}
/**
* Stop the firmware upload and return an error to the user's {@link #onError} handler.
*
* @param error The error to be returned to the user
*/
private void throwBeanError(BeanError error) {
if (onError != null) {
onError.onResult(error);
}
resetState();
}
/**
* Setup BLOCK and IDENTIFY characteristics
*/
private void setupOAD() {
BluetoothGattService oadService = mGattClient.getService(Constants.UUID_OAD_SERVICE);
if (oadService == null) {
throwBeanError(BeanError.MISSING_OAD_SERVICE);
return;
}
oadIdentify = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_IDENTIFY);
if (oadIdentify == null) {
throwBeanError(BeanError.MISSING_OAD_IDENTIFY);
return;
}
oadBlock = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_BLOCK);
if (oadBlock == null) {
throwBeanError(BeanError.MISSING_OAD_BLOCK);
return;
}
}
/**
* Enables notifications for all OAD characteristics.
*/
private void setupNotifications() {
Log.d(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.d(TAG, "Enable notifications successful");
} else {
throwBeanError(BeanError.ENABLE_OAD_NOTIFY_FAILED);
}
}
/**
* Enable notifications for a given characteristic.
*
* See <a href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification">
* the Android docs
* </a>
* on this subject.
*
* @param characteristic The characteristic to enable notifications for
* @return true if notifications were enabled successfully
*/
private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) {
boolean result = mGattClient.setCharacteristicNotification(characteristic, true);
String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mGattClient.writeDescriptor(descriptor);
if (result) {
Log.d(TAG, "Enabled notify for characteristic: " + characteristic.getUuid());
} else {
Log.e(TAG, "Enable notify failed for characteristic: " + characteristic.getUuid());
}
return result;
}
/**
* @param charc The characteristic being inspected
* @return true if it's the OAD Block characteristic
*/
private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) {
charc.setValue(data);
boolean result = mGattClient.writeCharacteristic(charc);
if (result) {
Log.d(TAG, "Wrote to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
} else {
Log.e(TAG, "Write failed to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
}
return result;
}
private boolean needsUpdate(Long bundleVersion, String beanVersion) {
if (beanVersion.startsWith("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
}
return false;
}
private void checkFirmwareVersion() {
Log.i(TAG, "Checking Firmware version...");
setState(FirmwareUploadState.CHECKING_FW_VERSION);
mGattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.FirmwareVersionCallback() {
@Override
public void onComplete(String version) {
if (needsUpdate(firmwareBundle.version(), version)) {
startOfferingImages();
} else {
finishOAD();
}
}
});
}
private void finishOAD() {
Log.i(TAG, "OAD Finished");
setState(FirmwareUploadState.INACTIVE);
onComplete.run();
}
/****************************************************************************
PUBLIC METHODS
****************************************************************************/
public String getName() {
return "OAD Profile";
}
public boolean uploadInProgress() {
return firmwareUploadState != FirmwareUploadState.INACTIVE;
}
@Override
public void onProfileReady() {
setupOAD();
setupNotifications();
}
@Override
public void onBeanConnected() {
Log.i(TAG, "OAD Profile Detected Bean Connection!!!");
if (uploadInProgress()) {
checkFirmwareVersion();
BeanManager.getInstance().cancelDiscovery();
}
}
@Override
public void onBeanDisconnected() {
Log.i(TAG, "OAD Profile Detected Bean Disconnection!!!");
}
@Override
public void onBeanConnectionFailed() {
Log.i(TAG, "OAD Profile Detected Bean Connection FAILURE!!!");
if(uploadInProgress()) {
BeanManager.getInstance().startDiscovery();
}
}
@Override
public void onCharacteristicChanged(GattClient client, BluetoothGattCharacteristic characteristic) {
if (uploadInProgress()) {
if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_IDENTIFY)) {
onNotificationIdentify(characteristic);
} else if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_BLOCK)) {
onNotificationBlock(characteristic);
}
}
}
/**
* Program the Bean's CC2540 with new firmware.
*
* @param bundle The {@link com.punchthrough.bean.sdk.upload.FirmwareBundle} to be sent
* @param onProgress Called when progress is made during the upload
* @param onComplete Called when the upload is complete
* @param onError Called if an error occurs during the upload
*/
public void programWithFirmware(final FirmwareBundle bundle, final Callback<UploadProgress> onProgress,
final Runnable onComplete, Callback<BeanError> onError) {
if (!mGattClient.isConnected()) {
onError.onResult(BeanError.NOT_CONNECTED);
}
Log.i(TAG, "Starting firmware update procedure!");
// Save state for this firmware procedure
this.onComplete = onComplete;
this.onError = onError;
this.onProgress = onProgress;
this.firmwareBundle = bundle;
checkFirmwareVersion();
}
}
| sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | package com.punchthrough.bean.sdk.internal.upload.firmware;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.util.Log;
import com.punchthrough.bean.sdk.BeanManager;
import com.punchthrough.bean.sdk.internal.ble.BaseProfile;
import com.punchthrough.bean.sdk.internal.ble.GattClient;
import com.punchthrough.bean.sdk.internal.device.DeviceProfile;
import com.punchthrough.bean.sdk.internal.utility.Constants;
import com.punchthrough.bean.sdk.internal.utility.Convert;
import com.punchthrough.bean.sdk.message.BeanError;
import com.punchthrough.bean.sdk.message.Callback;
import com.punchthrough.bean.sdk.message.UploadProgress;
import com.punchthrough.bean.sdk.upload.FirmwareBundle;
import com.punchthrough.bean.sdk.upload.FirmwareImage;
import java.util.Arrays;
import java.util.UUID;
public class OADProfile extends BaseProfile {
/**
* Custom OAD Profile for LightBlue Bean devices.
*
* This class encapsulates data and processes related to firmware updates to the CC2540.
*
*/
public static final String TAG = "OADProfile";
// OAD Characteristic handles
private BluetoothGattCharacteristic oadIdentify;
private BluetoothGattCharacteristic oadBlock;
// OAD Internal State
private FirmwareUploadState firmwareUploadState = FirmwareUploadState.INACTIVE;
private FirmwareImage currentImage;
private FirmwareBundle firmwareBundle;
private Runnable onComplete;
private Callback<BeanError> onError;
private Callback<UploadProgress> onProgress;
public OADProfile(GattClient client) {
super(client);
resetState();
}
private void setState(FirmwareUploadState state) {
Log.i(TAG, String.format("OAD State Change: %s -> %s", firmwareUploadState.name(), state.name()));
firmwareUploadState = state;
}
private void resetState() {
setState(FirmwareUploadState.INACTIVE);
onComplete = null;
onError = null;
currentImage = null;
}
private void onNotificationIdentify(BluetoothGattCharacteristic characteristic) {
currentImage = firmwareBundle.getNextImage();
Log.i(TAG, "Offering image: " + currentImage.name());
writeToCharacteristic(oadIdentify, currentImage.metadata());
}
private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
int blk = Convert.twoBytesToInt(characteristic.getValue(), Constants.CC2540_BYTE_ORDER);
if (blk == 0) {
Log.i(TAG, "Image accepted: " + currentImage.name());
Log.i(TAG, String.format("Starting Block Transfer of %d blocks", currentImage.blockCount()));
setState(FirmwareUploadState.BLOCK_XFER);
}
if (blk % 100 == 0) {
Log.i(TAG, "Block request: " + blk);
}
writeToCharacteristic(oadBlock, currentImage.block(blk));
onProgress.onResult(UploadProgress.create(blk, currentImage.blockCount()));
if (blk == currentImage.blockCount() - 1) {
Log.i(TAG, "Last block sent!");
Log.i(TAG, "Waiting for device to reconnect...");
}
}
/**
* Stop the firmware upload and return an error to the user's {@link #onError} handler.
*
* @param error The error to be returned to the user
*/
private void throwBeanError(BeanError error) {
if (onError != null) {
onError.onResult(error);
}
resetState();
}
/**
* Setup BLOCK and IDENTIFY characteristics
*/
private void setupOAD() {
BluetoothGattService oadService = mGattClient.getService(Constants.UUID_OAD_SERVICE);
if (oadService == null) {
throwBeanError(BeanError.MISSING_OAD_SERVICE);
return;
}
oadIdentify = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_IDENTIFY);
if (oadIdentify == null) {
throwBeanError(BeanError.MISSING_OAD_IDENTIFY);
return;
}
oadBlock = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_BLOCK);
if (oadBlock == null) {
throwBeanError(BeanError.MISSING_OAD_BLOCK);
return;
}
}
/**
* Enables notifications for all OAD characteristics.
*/
private void setupNotifications() {
Log.d(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.d(TAG, "Enable notifications successful");
} else {
throwBeanError(BeanError.ENABLE_OAD_NOTIFY_FAILED);
}
}
/**
* Enable notifications for a given characteristic.
*
* See <a href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification">
* the Android docs
* </a>
* on this subject.
*
* @param characteristic The characteristic to enable notifications for
* @return true if notifications were enabled successfully
*/
private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) {
boolean result = mGattClient.setCharacteristicNotification(characteristic, true);
String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mGattClient.writeDescriptor(descriptor);
if (result) {
Log.d(TAG, "Enabled notify for characteristic: " + characteristic.getUuid());
} else {
Log.e(TAG, "Enable notify failed for characteristic: " + characteristic.getUuid());
}
return result;
}
/**
* Request the Bean's current OAD firmware header.
*/
private void triggerCurrentHeader() {
Log.d(TAG, "Requesting current header");
setState(FirmwareUploadState.OFFERING_IMAGES);
// To request the current header, write [0x00] to OAD Identify
firmwareBundle.reset();
writeToCharacteristic(oadIdentify, new byte[]{0x00});
}
/**
* @param charc The characteristic being inspected
* @return true if it's the OAD Block characteristic
*/
private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) {
charc.setValue(data);
boolean result = mGattClient.writeCharacteristic(charc);
if (result) {
Log.d(TAG, "Wrote to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
} else {
Log.e(TAG, "Write failed to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
}
return result;
}
private boolean needsUpdate(Long bundleVersion, String beanVersion) {
if (beanVersion.startsWith("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
}
return false;
}
private void checkFirmwareVersion() {
Log.i(TAG, "Checking Firmware version...");
setState(FirmwareUploadState.CHECKING_FW_VERSION);
mGattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.FirmwareVersionCallback() {
@Override
public void onComplete(String version) {
if (needsUpdate(firmwareBundle.version(), version)) {
triggerCurrentHeader();
} else {
finishOAD();
}
}
});
}
private void finishOAD() {
Log.i(TAG, "OAD Finished");
setState(FirmwareUploadState.INACTIVE);
onComplete.run();
}
/****************************************************************************
PUBLIC METHODS
****************************************************************************/
public String getName() {
return "OAD Profile";
}
public boolean uploadInProgress() {
return firmwareUploadState != FirmwareUploadState.INACTIVE;
}
@Override
public void onProfileReady() {
setupOAD();
setupNotifications();
}
@Override
public void onBeanConnected() {
Log.i(TAG, "OAD Profile Detected Bean Connection!!!");
if (uploadInProgress()) {
checkFirmwareVersion();
BeanManager.getInstance().cancelDiscovery();
}
}
@Override
public void onBeanDisconnected() {
Log.i(TAG, "OAD Profile Detected Bean Disconnection!!!");
}
@Override
public void onBeanConnectionFailed() {
Log.i(TAG, "OAD Profile Detected Bean Connection FAILURE!!!");
if(uploadInProgress()) {
BeanManager.getInstance().startDiscovery();
}
}
@Override
public void onCharacteristicChanged(GattClient client, BluetoothGattCharacteristic characteristic) {
if (uploadInProgress()) {
if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_IDENTIFY)) {
onNotificationIdentify(characteristic);
} else if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_BLOCK)) {
onNotificationBlock(characteristic);
}
}
}
/**
* Program the Bean's CC2540 with new firmware.
*
* @param bundle The {@link com.punchthrough.bean.sdk.upload.FirmwareBundle} to be sent
* @param onProgress Called when progress is made during the upload
* @param onComplete Called when the upload is complete
* @param onError Called if an error occurs during the upload
*/
public void programWithFirmware(final FirmwareBundle bundle, final Callback<UploadProgress> onProgress,
final Runnable onComplete, Callback<BeanError> onError) {
if (!mGattClient.isConnected()) {
onError.onResult(BeanError.NOT_CONNECTED);
}
Log.i(TAG, "Starting firmware update procedure!");
// Save state for this firmware procedure
this.onComplete = onComplete;
this.onError = onError;
this.onProgress = onProgress;
this.firmwareBundle = bundle;
checkFirmwareVersion();
}
}
| oad: start offering images immediately without writing 0x00 to identify
| sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | oad: start offering images immediately without writing 0x00 to identify | <ide><path>dk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java
<ide> currentImage = null;
<ide> }
<ide>
<del> private void onNotificationIdentify(BluetoothGattCharacteristic characteristic) {
<add> private void offerNextImage() {
<ide> currentImage = firmwareBundle.getNextImage();
<ide> Log.i(TAG, "Offering image: " + currentImage.name());
<ide> writeToCharacteristic(oadIdentify, currentImage.metadata());
<add> }
<add>
<add> private void startOfferingImages() {
<add> setState(FirmwareUploadState.OFFERING_IMAGES);
<add> firmwareBundle.reset();
<add> offerNextImage();
<add> }
<add>
<add> private void onNotificationIdentify(BluetoothGattCharacteristic characteristic) {
<add> offerNextImage();
<ide> }
<ide>
<ide> private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
<ide> Log.e(TAG, "Enable notify failed for characteristic: " + characteristic.getUuid());
<ide> }
<ide> return result;
<del> }
<del>
<del> /**
<del> * Request the Bean's current OAD firmware header.
<del> */
<del> private void triggerCurrentHeader() {
<del>
<del> Log.d(TAG, "Requesting current header");
<del> setState(FirmwareUploadState.OFFERING_IMAGES);
<del>
<del> // To request the current header, write [0x00] to OAD Identify
<del> firmwareBundle.reset();
<del> writeToCharacteristic(oadIdentify, new byte[]{0x00});
<ide> }
<ide>
<ide> /**
<ide> @Override
<ide> public void onComplete(String version) {
<ide> if (needsUpdate(firmwareBundle.version(), version)) {
<del> triggerCurrentHeader();
<add> startOfferingImages();
<ide> } else {
<ide> finishOAD();
<ide> } |
|
Java | apache-2.0 | 129e90b66e1d1addfd3efc9c32ec9dbc4e5ba98f | 0 | DwayneJengSage/BridgePF,alxdarksage/BridgePF,alxdarksage/BridgePF,alxdarksage/BridgePF,Sage-Bionetworks/BridgePF,DwayneJengSage/BridgePF,Sage-Bionetworks/BridgePF,DwayneJengSage/BridgePF,Sage-Bionetworks/BridgePF | package org.sagebionetworks.bridge.services;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.RequestContext;
import org.sagebionetworks.bridge.Roles;
import org.sagebionetworks.bridge.TestConstants;
import org.sagebionetworks.bridge.TestUtils;
import org.sagebionetworks.bridge.cache.CacheProvider;
import org.sagebionetworks.bridge.dao.AccountDao;
import org.sagebionetworks.bridge.dao.AccountSecretDao;
import org.sagebionetworks.bridge.exceptions.InvalidEntityException;
import org.sagebionetworks.bridge.models.CriteriaContext;
import org.sagebionetworks.bridge.models.accounts.Account;
import org.sagebionetworks.bridge.models.accounts.AccountId;
import org.sagebionetworks.bridge.models.accounts.AccountSecretType;
import org.sagebionetworks.bridge.models.accounts.ConsentStatus;
import org.sagebionetworks.bridge.models.accounts.IdentifierHolder;
import org.sagebionetworks.bridge.models.accounts.SharingScope;
import org.sagebionetworks.bridge.models.accounts.SignIn;
import org.sagebionetworks.bridge.models.accounts.StudyParticipant;
import org.sagebionetworks.bridge.models.accounts.UserSession;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid;
import org.sagebionetworks.bridge.models.substudies.AccountSubstudy;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
@RunWith(MockitoJUnitRunner.class)
public class UserAdminServiceMockTest {
@Mock
private AuthenticationService authenticationService;
@Mock
private NotificationsService notificationsService;
@Mock
private ParticipantService participantService;
@Mock
private ConsentService consentService;
@Mock
private AccountDao accountDao;
@Mock
private Account account;
@Mock
private UploadService uploadService;
@Mock
private HealthDataService healthDataService;
@Mock
private CacheProvider cacheProvider;
@Mock
private ScheduledActivityService scheduledActivityService;
@Mock
private ActivityEventService activityEventService;
@Mock
private ExternalIdService externalIdService;
@Mock
private AccountSecretDao accountSecretDao;
@Captor
private ArgumentCaptor<CriteriaContext> contextCaptor;
@Captor
private ArgumentCaptor<SignIn> signInCaptor;
@Captor
private ArgumentCaptor<Account> accountCaptor;
private UserAdminService service;
private Map<SubpopulationGuid,ConsentStatus> statuses;
@Before
public void before() {
service = new UserAdminService();
service.setAuthenticationService(authenticationService);
service.setConsentService(consentService);
service.setNotificationsService(notificationsService);
service.setParticipantService(participantService);
service.setUploadService(uploadService);
service.setAccountDao(accountDao);
service.setCacheProvider(cacheProvider);
service.setHealthDataService(healthDataService);
service.setScheduledActivityService(scheduledActivityService);
service.setActivityEventService(activityEventService);
service.setExternalIdService(externalIdService);
service.setAccountSecretDao(accountSecretDao);
// Make a user with multiple consent statuses, and just verify that we call the
// consent service that many times.
statuses = Maps.newHashMap();
addConsentStatus(statuses, "subpop1");
addConsentStatus(statuses, "subpop2");
addConsentStatus(statuses, "subpop3");
UserSession session = new UserSession();
session.setConsentStatuses(statuses);
when(authenticationService.signIn(any(), any(), any())).thenReturn(session);
doReturn(new IdentifierHolder("ABC")).when(participantService).createParticipant(any(), any(),
anyBoolean());
doReturn(new StudyParticipant.Builder().withId("ABC").build()).when(participantService).getParticipant(any(),
anyString(), anyBoolean());
}
@After
public void after() {
BridgeUtils.setRequestContext(RequestContext.NULL_INSTANCE);
}
private void addConsentStatus(Map<SubpopulationGuid,ConsentStatus> statuses, String guid) {
SubpopulationGuid subpopGuid = SubpopulationGuid.create(guid);
ConsentStatus status = new ConsentStatus.Builder().withConsented(false).withGuid(subpopGuid).withName(guid)
.withRequired(true).build();
statuses.put(subpopGuid, status);
}
@Test
public void creatingUserConsentsToAllRequiredConsents() {
BridgeUtils.setRequestContext(new RequestContext.Builder().withCallerRoles(
ImmutableSet.of(Roles.ADMIN)).build());
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withEmail("[email protected]").withPassword("password").build();
Map<SubpopulationGuid,ConsentStatus> statuses = Maps.newHashMap();
statuses.put(SubpopulationGuid.create("foo1"), TestConstants.REQUIRED_SIGNED_CURRENT);
statuses.put(SubpopulationGuid.create("foo2"), TestConstants.REQUIRED_SIGNED_OBSOLETE);
when(consentService.getConsentStatuses(any())).thenReturn(statuses);
service.createUser(study, participant, null, true, true);
verify(participantService).createParticipant(study, participant, false);
verify(authenticationService).signIn(eq(study), contextCaptor.capture(), signInCaptor.capture());
CriteriaContext context = contextCaptor.getValue();
assertEquals(study.getStudyIdentifier(), context.getStudyIdentifier());
verify(consentService).consentToResearch(eq(study), eq(SubpopulationGuid.create("foo1")), any(StudyParticipant.class), any(),
eq(SharingScope.NO_SHARING), eq(false));
verify(consentService).consentToResearch(eq(study), eq(SubpopulationGuid.create("foo2")), any(StudyParticipant.class), any(),
eq(SharingScope.NO_SHARING), eq(false));
SignIn signIn = signInCaptor.getValue();
assertEquals(participant.getEmail(), signIn.getEmail());
assertEquals(participant.getPassword(), signIn.getPassword());
verify(consentService).getConsentStatuses(context);
}
@Test
public void creatingUserWithPhone() {
BridgeUtils.setRequestContext(new RequestContext.Builder().withCallerRoles(
ImmutableSet.of(Roles.ADMIN)).build());
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withPhone(TestConstants.PHONE)
.withPassword("password").build();
service.createUser(study, participant, null, true, true);
verify(participantService).createParticipant(study, participant, false);
verify(authenticationService).signIn(eq(study), contextCaptor.capture(), signInCaptor.capture());
CriteriaContext context = contextCaptor.getValue();
assertEquals(study.getStudyIdentifier(), context.getStudyIdentifier());
SignIn signIn = signInCaptor.getValue();
assertEquals(participant.getPhone(), signIn.getPhone());
assertEquals(participant.getPassword(), signIn.getPassword());
verify(consentService).getConsentStatuses(context);
}
@Test(expected = InvalidEntityException.class)
public void creatingUserWithoutEmailOrPhoneProhibited() {
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withPassword("password").build();
service.createUser(study, participant, null, true, true);
}
@Test
public void creatingUserWithSubpopulationOnlyConsentsToThatSubpopulation() {
BridgeUtils.setRequestContext(new RequestContext.Builder().withCallerRoles(
ImmutableSet.of(Roles.ADMIN)).build());
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withEmail("[email protected]").withPassword("password").build();
SubpopulationGuid consentedGuid = statuses.keySet().iterator().next();
UserSession session = service.createUser(study, participant, consentedGuid, true, true);
verify(participantService).createParticipant(study, participant, false);
// consented to the indicated subpopulation
verify(consentService).consentToResearch(eq(study), eq(consentedGuid), any(StudyParticipant.class), any(), eq(SharingScope.NO_SHARING), eq(false));
// but not to the other two
for (SubpopulationGuid guid : session.getConsentStatuses().keySet()) {
if (guid != consentedGuid) {
verify(consentService, never()).consentToResearch(eq(study), eq(guid), eq(participant), any(), eq(SharingScope.NO_SHARING), eq(false));
}
}
}
@Test
public void deleteUser() {
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
AccountId accountId = AccountId.forId(study.getIdentifier(), "userId");
AccountSubstudy as1 = AccountSubstudy.create(TestConstants.TEST_STUDY_IDENTIFIER, "substudyA", "userId");
as1.setExternalId("subAextId");
AccountSubstudy as2 = AccountSubstudy.create(TestConstants.TEST_STUDY_IDENTIFIER, "substudyB", "userId");
as2.setExternalId("subBextId");
Set<AccountSubstudy> substudies = ImmutableSet.of(as1, as2);
doReturn("userId").when(account).getId();
doReturn("healthCode").when(account).getHealthCode();
doReturn("externalId").when(account).getExternalId();
doReturn(substudies).when(account).getAccountSubstudies();
doReturn(account).when(accountDao).getAccount(accountId);
service.deleteUser(study, "userId");
// Verify a lot of stuff is deleted or removed
verify(cacheProvider).removeSessionByUserId("userId");
verify(cacheProvider).removeRequestInfo("userId");
verify(healthDataService).deleteRecordsForHealthCode("healthCode");
verify(notificationsService).deleteAllRegistrations(study.getStudyIdentifier(), "healthCode");
verify(uploadService).deleteUploadsForHealthCode("healthCode");
verify(scheduledActivityService).deleteActivitiesForUser("healthCode");
verify(activityEventService).deleteActivityEvents("healthCode");
verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("externalId"));
verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("subAextId"));
verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("subBextId"));
verify(accountDao).deleteAccount(accountId);
assertEquals("healthCode", accountCaptor.getValue().getHealthCode());
}
}
| test/org/sagebionetworks/bridge/services/UserAdminServiceMockTest.java | package org.sagebionetworks.bridge.services;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.RequestContext;
import org.sagebionetworks.bridge.Roles;
import org.sagebionetworks.bridge.TestConstants;
import org.sagebionetworks.bridge.TestUtils;
import org.sagebionetworks.bridge.cache.CacheProvider;
import org.sagebionetworks.bridge.dao.AccountDao;
import org.sagebionetworks.bridge.dao.AccountSecretDao;
import org.sagebionetworks.bridge.exceptions.InvalidEntityException;
import org.sagebionetworks.bridge.models.CriteriaContext;
import org.sagebionetworks.bridge.models.accounts.Account;
import org.sagebionetworks.bridge.models.accounts.AccountId;
import org.sagebionetworks.bridge.models.accounts.AccountSecretType;
import org.sagebionetworks.bridge.models.accounts.ConsentStatus;
import org.sagebionetworks.bridge.models.accounts.IdentifierHolder;
import org.sagebionetworks.bridge.models.accounts.SharingScope;
import org.sagebionetworks.bridge.models.accounts.SignIn;
import org.sagebionetworks.bridge.models.accounts.StudyParticipant;
import org.sagebionetworks.bridge.models.accounts.UserSession;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid;
import org.sagebionetworks.bridge.models.substudies.AccountSubstudy;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
@RunWith(MockitoJUnitRunner.class)
public class UserAdminServiceMockTest {
@Mock
private AuthenticationService authenticationService;
@Mock
private NotificationsService notificationsService;
@Mock
private ParticipantService participantService;
@Mock
private ConsentService consentService;
@Mock
private AccountDao accountDao;
@Mock
private Account account;
@Mock
private UploadService uploadService;
@Mock
private HealthDataService healthDataService;
@Mock
private CacheProvider cacheProvider;
@Mock
private ScheduledActivityService scheduledActivityService;
@Mock
private ActivityEventService activityEventService;
@Mock
private ExternalIdService externalIdService;
@Mock
private AccountSecretDao accountSecretDao;
@Captor
private ArgumentCaptor<CriteriaContext> contextCaptor;
@Captor
private ArgumentCaptor<SignIn> signInCaptor;
@Captor
private ArgumentCaptor<Account> accountCaptor;
private UserAdminService service;
private Map<SubpopulationGuid,ConsentStatus> statuses;
@Before
public void before() {
service = new UserAdminService();
service.setAuthenticationService(authenticationService);
service.setConsentService(consentService);
service.setNotificationsService(notificationsService);
service.setParticipantService(participantService);
service.setUploadService(uploadService);
service.setAccountDao(accountDao);
service.setCacheProvider(cacheProvider);
service.setHealthDataService(healthDataService);
service.setScheduledActivityService(scheduledActivityService);
service.setActivityEventService(activityEventService);
service.setExternalIdService(externalIdService);
service.setAccountSecretDao(accountSecretDao);
// Make a user with multiple consent statuses, and just verify that we call the
// consent service that many times.
statuses = Maps.newHashMap();
addConsentStatus(statuses, "subpop1");
addConsentStatus(statuses, "subpop2");
addConsentStatus(statuses, "subpop3");
UserSession session = new UserSession();
session.setConsentStatuses(statuses);
when(authenticationService.signIn(any(), any(), any())).thenReturn(session);
doReturn(new IdentifierHolder("ABC")).when(participantService).createParticipant(any(), any(),
anyBoolean());
doReturn(new StudyParticipant.Builder().withId("ABC").build()).when(participantService).getParticipant(any(),
anyString(), anyBoolean());
}
@After
public void after() {
BridgeUtils.setRequestContext(RequestContext.NULL_INSTANCE);
}
private void addConsentStatus(Map<SubpopulationGuid,ConsentStatus> statuses, String guid) {
SubpopulationGuid subpopGuid = SubpopulationGuid.create(guid);
ConsentStatus status = new ConsentStatus.Builder().withConsented(false).withGuid(subpopGuid).withName(guid)
.withRequired(true).build();
statuses.put(subpopGuid, status);
}
@Test
public void creatingUserConsentsToAllRequiredConsents() {
BridgeUtils.setRequestContext(new RequestContext.Builder().withCallerRoles(
ImmutableSet.of(Roles.ADMIN)).build());
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withEmail("[email protected]").withPassword("password").build();
Map<SubpopulationGuid,ConsentStatus> statuses = Maps.newHashMap();
statuses.put(SubpopulationGuid.create("foo1"), TestConstants.REQUIRED_SIGNED_CURRENT);
statuses.put(SubpopulationGuid.create("foo2"), TestConstants.REQUIRED_SIGNED_OBSOLETE);
when(consentService.getConsentStatuses(any())).thenReturn(statuses);
service.createUser(study, participant, null, true, true);
verify(participantService).createParticipant(study, participant, false);
verify(authenticationService).signIn(eq(study), contextCaptor.capture(), signInCaptor.capture());
CriteriaContext context = contextCaptor.getValue();
assertEquals(study.getStudyIdentifier(), context.getStudyIdentifier());
verify(consentService).consentToResearch(eq(study), eq(SubpopulationGuid.create("foo1")), any(StudyParticipant.class), any(),
eq(SharingScope.NO_SHARING), eq(false));
verify(consentService).consentToResearch(eq(study), eq(SubpopulationGuid.create("foo2")), any(StudyParticipant.class), any(),
eq(SharingScope.NO_SHARING), eq(false));
SignIn signIn = signInCaptor.getValue();
assertEquals(participant.getEmail(), signIn.getEmail());
assertEquals(participant.getPassword(), signIn.getPassword());
verify(consentService).getConsentStatuses(context);
}
@Test
public void creatingUserWithPhone() {
BridgeUtils.setRequestContext(new RequestContext.Builder().withCallerRoles(
ImmutableSet.of(Roles.ADMIN)).build());
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withPhone(TestConstants.PHONE)
.withPassword("password").build();
service.createUser(study, participant, null, true, true);
verify(participantService).createParticipant(study, participant, false);
verify(authenticationService).signIn(eq(study), contextCaptor.capture(), signInCaptor.capture());
CriteriaContext context = contextCaptor.getValue();
assertEquals(study.getStudyIdentifier(), context.getStudyIdentifier());
SignIn signIn = signInCaptor.getValue();
assertEquals(participant.getPhone(), signIn.getPhone());
assertEquals(participant.getPassword(), signIn.getPassword());
verify(consentService).getConsentStatuses(context);
}
@Test(expected = InvalidEntityException.class)
public void creatingUserWithoutEmailOrPhoneProhibited() {
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withPassword("password").build();
service.createUser(study, participant, null, true, true);
}
@Test
public void creatingUserWithSubpopulationOnlyConsentsToThatSubpopulation() {
BridgeUtils.setRequestContext(new RequestContext.Builder().withCallerRoles(
ImmutableSet.of(Roles.ADMIN)).build());
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
StudyParticipant participant = new StudyParticipant.Builder().withEmail("[email protected]").withPassword("password").build();
SubpopulationGuid consentedGuid = statuses.keySet().iterator().next();
UserSession session = service.createUser(study, participant, consentedGuid, true, true);
verify(participantService).createParticipant(study, participant, false);
// consented to the indicated subpopulation
verify(consentService).consentToResearch(eq(study), eq(consentedGuid), any(StudyParticipant.class), any(), eq(SharingScope.NO_SHARING), eq(false));
// but not to the other two
for (SubpopulationGuid guid : session.getConsentStatuses().keySet()) {
if (guid != consentedGuid) {
verify(consentService, never()).consentToResearch(eq(study), eq(guid), eq(participant), any(), eq(SharingScope.NO_SHARING), eq(false));
}
}
}
@Test
public void deleteUser() {
Study study = TestUtils.getValidStudy(UserAdminServiceMockTest.class);
AccountId accountId = AccountId.forId(study.getIdentifier(), "userId");
AccountSubstudy as1 = AccountSubstudy.create(TestConstants.TEST_STUDY_IDENTIFIER, "substudyA", "userId");
as1.setExternalId("subAextId");
AccountSubstudy as2 = AccountSubstudy.create(TestConstants.TEST_STUDY_IDENTIFIER, "substudyB", "userId");
as2.setExternalId("subBextId");
Set<AccountSubstudy> substudies = ImmutableSet.of(as1, as2);
doReturn("userId").when(account).getId();
doReturn("healthCode").when(account).getHealthCode();
doReturn("externalId").when(account).getExternalId();
doReturn(substudies).when(account).getAccountSubstudies();
doReturn(account).when(accountDao).getAccount(accountId);
service.deleteUser(study, "userId");
// Verify a lot of stuff is deleted or removed
verify(cacheProvider).removeSessionByUserId("userId");
verify(cacheProvider).removeRequestInfo("userId");
verify(healthDataService).deleteRecordsForHealthCode("healthCode");
verify(notificationsService).deleteAllRegistrations(study.getStudyIdentifier(), "healthCode");
verify(uploadService).deleteUploadsForHealthCode("healthCode");
verify(scheduledActivityService).deleteActivitiesForUser("healthCode");
verify(activityEventService).deleteActivityEvents("healthCode");
verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("externalId"));
verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("subAextId"));
verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("subBextId"));
verify(accountSecretDao).removeSecrets(AccountSecretType.REAUTH, "userId");
verify(accountDao).deleteAccount(accountId);
assertEquals("healthCode", accountCaptor.getValue().getHealthCode());
}
}
| Remove this verification
| test/org/sagebionetworks/bridge/services/UserAdminServiceMockTest.java | Remove this verification | <ide><path>est/org/sagebionetworks/bridge/services/UserAdminServiceMockTest.java
<ide> verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("externalId"));
<ide> verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("subAextId"));
<ide> verify(externalIdService).unassignExternalId(accountCaptor.capture(), eq("subBextId"));
<del> verify(accountSecretDao).removeSecrets(AccountSecretType.REAUTH, "userId");
<ide> verify(accountDao).deleteAccount(accountId);
<ide>
<ide> assertEquals("healthCode", accountCaptor.getValue().getHealthCode()); |
|
Java | apache-2.0 | 5e66c581b5432dd84c87df6d3f438308ddd461e0 | 0 | jiangzhonghui/mp4parser-1,rasheedamir/mp4parser,murat8505/mp4parser,agenliuhuan/mp4parser,shijian95/mp4parser,olegloa/mp4parser,shs1989/mp4parser-1,sannies/mp4parser,LoveOpenSource/mp4parser,michalliu/mp4parser,hatiboy/mp4parser-1,godghdai/mp4parser-1,frostwire/mp4parser | package com.googlecode.mp4parser.authoring.builder;
import com.coremedia.iso.BoxParser;
import com.coremedia.iso.Hex;
import com.coremedia.iso.IsoFile;
import com.coremedia.iso.IsoTypeWriter;
import com.coremedia.iso.boxes.Box;
import com.coremedia.iso.boxes.CompositionTimeToSample;
import com.coremedia.iso.boxes.ContainerBox;
import com.coremedia.iso.boxes.DataEntryUrlBox;
import com.coremedia.iso.boxes.DataInformationBox;
import com.coremedia.iso.boxes.DataReferenceBox;
import com.coremedia.iso.boxes.FileTypeBox;
import com.coremedia.iso.boxes.HandlerBox;
import com.coremedia.iso.boxes.MediaBox;
import com.coremedia.iso.boxes.MediaHeaderBox;
import com.coremedia.iso.boxes.MediaInformationBox;
import com.coremedia.iso.boxes.MovieBox;
import com.coremedia.iso.boxes.MovieHeaderBox;
import com.coremedia.iso.boxes.SampleDependencyTypeBox;
import com.coremedia.iso.boxes.SampleTableBox;
import com.coremedia.iso.boxes.StaticChunkOffsetBox;
import com.coremedia.iso.boxes.TimeToSampleBox;
import com.coremedia.iso.boxes.TrackBox;
import com.coremedia.iso.boxes.TrackHeaderBox;
import com.coremedia.iso.boxes.fragment.MovieExtendsBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentHeaderBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentRandomAccessBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentRandomAccessOffsetBox;
import com.coremedia.iso.boxes.fragment.SampleFlags;
import com.coremedia.iso.boxes.fragment.TrackExtendsBox;
import com.coremedia.iso.boxes.fragment.TrackFragmentBox;
import com.coremedia.iso.boxes.fragment.TrackFragmentHeaderBox;
import com.coremedia.iso.boxes.fragment.TrackFragmentRandomAccessBox;
import com.coremedia.iso.boxes.fragment.TrackRunBox;
import com.googlecode.mp4parser.authoring.DateHelper;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Logger;
import static com.coremedia.iso.boxes.CastUtils.l2i;
/**
* Creates a fragmented MP4 file.
*/
public class FragmentedMp4Builder implements Mp4Builder {
FragmentIntersectionFinder intersectionFinder = new SyncSampleIntersectFinderImpl();
private static final Logger LOG = Logger.getLogger(FragmentedMp4Builder.class.getName());
public List<String> getAllowedHandlers() {
return Arrays.asList("soun", "vide");
}
public Box createFtyp(Movie movie) {
List<String> minorBrands = new LinkedList<String>();
minorBrands.add("isom");
minorBrands.add("iso2");
minorBrands.add("avc1");
return new FileTypeBox("isom", 0, minorBrands);
}
protected List<Box> createMoofMdat(final Movie movie) {
List<Box> boxes = new LinkedList<Box>();
int maxNumberOfFragments = 0;
for (Track track : movie.getTracks()) {
int currentLength = intersectionFinder.sampleNumbers(track, movie).length;
maxNumberOfFragments = currentLength > maxNumberOfFragments ? currentLength : maxNumberOfFragments;
}
int sequence = 1;
for (int i = 0; i < maxNumberOfFragments; i++) {
final List<Track> sizeSortedTracks = new LinkedList<Track>(movie.getTracks());
final int j = i;
Collections.sort(sizeSortedTracks, new Comparator<Track>() {
public int compare(Track o1, Track o2) {
int[] startSamples1 = intersectionFinder.sampleNumbers(o1, movie);
int startSample1 = startSamples1[j];
int endSample1 = j + 1 < startSamples1.length ? startSamples1[j + 1] : o1.getSamples().size();
int[] startSamples2 = intersectionFinder.sampleNumbers(o2, movie);
int startSample2 = startSamples2[j];
int endSample2 = j + 1 < startSamples2.length ? startSamples2[j + 1] : o2.getSamples().size();
List<ByteBuffer> samples1 = o1.getSamples().subList(startSample1, endSample1);
List<ByteBuffer> samples2 = o2.getSamples().subList(startSample2, endSample2);
int size1 = 0;
for (ByteBuffer byteBuffer : samples1) {
size1 += byteBuffer.limit();
}
int size2 = 0;
for (ByteBuffer byteBuffer : samples2) {
size2 += byteBuffer.limit();
}
return size1 - size2;
}
});
for (Track track : sizeSortedTracks) {
if (getAllowedHandlers().isEmpty() || getAllowedHandlers().contains(track.getHandler())) {
int[] startSamples = intersectionFinder.sampleNumbers(track, movie);
if (i < startSamples.length) {
int startSample = startSamples[i];
int endSample = i + 1 < startSamples.length ? startSamples[i + 1] : track.getSamples().size();
if (startSample == endSample) {
// empty fragment
// just don't add any boxes.
} else {
boxes.add(createMoof(startSample, endSample, track, sequence));
boxes.add(createMdat(startSample, endSample, track, sequence++));
}
} else {
//obvious this track has not that many fragments
}
}
}
}
return boxes;
}
public IsoFile build(Movie movie) throws IOException {
LOG.info("Creating movie " + movie);
IsoFile isoFile = new IsoFile();
isoFile.addBox(createFtyp(movie));
isoFile.addBox(createMoov(movie));
for (Box box : createMoofMdat(movie)) {
isoFile.addBox(box);
}
isoFile.addBox(createMfra(movie, isoFile));
return isoFile;
}
protected Box createMdat(int startSample, int endSample, Track track, int i) {
final List<ByteBuffer> samples = ByteBufferHelper.mergeAdjacentBuffers(getSamples(startSample, endSample, track, i));
return new Box() {
ContainerBox parent;
public ContainerBox getParent() {
return parent;
}
public void setParent(ContainerBox parent) {
this.parent = parent;
}
public long getSize() {
long size = 8; // I don't expect 2gig fragments
for (ByteBuffer sample : samples) {
size += sample.limit();
}
return size;
}
public String getType() {
return "mdat";
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
ByteBuffer header = ByteBuffer.allocate(8);
IsoTypeWriter.writeUInt32(header, l2i(getSize()));
header.put(IsoFile.fourCCtoBytes(getType()));
header.rewind();
writableByteChannel.write(header);
if (writableByteChannel instanceof GatheringByteChannel) {
int STEPSIZE = 1024;
for (int i = 0; i < Math.ceil((double) samples.size() / STEPSIZE); i++) {
List<ByteBuffer> sublist = samples.subList(
i * STEPSIZE, // start
(i + 1) * STEPSIZE < samples.size() ? (i + 1) * STEPSIZE : samples.size()); // end
ByteBuffer sampleArray[] = sublist.toArray(new ByteBuffer[sublist.size()]);
do {
((GatheringByteChannel) writableByteChannel).write(sampleArray);
} while (sampleArray[sampleArray.length - 1].remaining() > 0);
}
//System.err.println(bytesWritten);
} else {
for (ByteBuffer sample : samples) {
sample.rewind();
writableByteChannel.write(sample);
}
}
}
public void parse(ReadableByteChannel inFC, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
}
};
}
public static void dumpHex(ByteBuffer bb) {
byte[] b = new byte[bb.limit()];
bb.get(b);
System.err.println(Hex.encodeHex(b));
bb.rewind();
}
protected Box createTfhd(int startSample, int endSample, Track track, int sequenceNumber) {
TrackFragmentHeaderBox tfhd = new TrackFragmentHeaderBox();
SampleFlags sf = new SampleFlags();
tfhd.setDefaultSampleFlags(sf);
tfhd.setBaseDataOffset(-1);
tfhd.setTrackId(track.getTrackMetaData().getTrackId());
return tfhd;
}
protected Box createMfhd(int startSample, int endSample, Track track, int sequenceNumber) {
MovieFragmentHeaderBox mfhd = new MovieFragmentHeaderBox();
mfhd.setSequenceNumber(sequenceNumber);
return mfhd;
}
protected Box createTraf(int startSample, int endSample, Track track, int sequenceNumber) {
TrackFragmentBox traf = new TrackFragmentBox();
traf.addBox(createTfhd(startSample, endSample, track, sequenceNumber));
for (Box trun : createTruns(startSample, endSample, track, sequenceNumber)) {
traf.addBox(trun);
}
return traf;
}
protected List<ByteBuffer> getSamples(int startSample, int endSample, Track track, int sequenceNumber) {
return track.getSamples().subList(startSample, endSample);
}
protected List<? extends Box> createTruns(int startSample, int endSample, Track track, int sequenceNumber) {
List<ByteBuffer> samples = getSamples(startSample, endSample, track, sequenceNumber);
long[] sampleSizes = new long[samples.size()];
for (int i = 0; i < sampleSizes.length; i++) {
sampleSizes[i] = samples.get(i).limit();
}
TrackRunBox trun = new TrackRunBox();
trun.setSampleDurationPresent(true);
trun.setSampleSizePresent(true);
List<TrackRunBox.Entry> entries = new ArrayList<TrackRunBox.Entry>(endSample - startSample);
Queue<TimeToSampleBox.Entry> timeQueue = new LinkedList<TimeToSampleBox.Entry>(track.getDecodingTimeEntries());
long durationEntriesLeft = timeQueue.peek().getCount();
Queue<CompositionTimeToSample.Entry> compositionTimeQueue =
track.getCompositionTimeEntries() != null && track.getCompositionTimeEntries().size() > 0 ?
new LinkedList<CompositionTimeToSample.Entry>(track.getCompositionTimeEntries()) : null;
long compositionTimeEntriesLeft = compositionTimeQueue != null ? compositionTimeQueue.peek().getCount() : -1;
trun.setSampleCompositionTimeOffsetPresent(compositionTimeEntriesLeft > 0);
boolean sampleFlagsRequired = (track.getSampleDependencies() != null && !track.getSampleDependencies().isEmpty() ||
track.getSyncSamples() != null && track.getSyncSamples().length != 0);
trun.setSampleFlagsPresent(sampleFlagsRequired);
for (int i = 0; i < sampleSizes.length; i++) {
TrackRunBox.Entry entry = new TrackRunBox.Entry();
entry.setSampleSize(sampleSizes[i]);
if (sampleFlagsRequired) {
//if (false) {
SampleFlags sflags = new SampleFlags();
if (track.getSampleDependencies() != null && !track.getSampleDependencies().isEmpty()) {
SampleDependencyTypeBox.Entry e = track.getSampleDependencies().get(i);
sflags.setSampleDependsOn(e.getSampleDependsOn());
sflags.setSampleIsDependedOn(e.getSampleIsDependentOn());
sflags.setSampleHasRedundancy(e.getSampleHasRedundancy());
}
if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) {
// we have to mark non-sync samples!
if (Arrays.binarySearch(track.getSyncSamples(), startSample + i + 1) >= 0) {
sflags.setSampleIsDifferenceSample(false);
sflags.setSampleDependsOn(2);
} else {
sflags.setSampleIsDifferenceSample(true);
sflags.setSampleDependsOn(1);
}
}
// i don't have sample degradation
entry.setSampleFlags(sflags);
}
entry.setSampleDuration(timeQueue.peek().getDelta());
if (--durationEntriesLeft == 0 && timeQueue.size() > 1) {
timeQueue.remove();
durationEntriesLeft = timeQueue.peek().getCount();
}
if (compositionTimeQueue != null) {
trun.setSampleCompositionTimeOffsetPresent(true);
entry.setSampleCompositionTimeOffset(compositionTimeQueue.peek().getOffset());
if (--compositionTimeEntriesLeft == 0 && compositionTimeQueue.size() > 1) {
compositionTimeQueue.remove();
compositionTimeEntriesLeft = compositionTimeQueue.element().getCount();
}
}
entries.add(entry);
}
trun.setEntries(entries);
return Collections.singletonList(trun);
}
protected Box createMoof(int startSample, int endSample, Track track, int sequenceNumber) {
MovieFragmentBox moof = new MovieFragmentBox();
moof.addBox(createMfhd(startSample, endSample, track, sequenceNumber));
moof.addBox(createTraf(startSample, endSample, track, sequenceNumber));
TrackRunBox firstTrun = moof.getTrackRunBoxes().get(0);
firstTrun.setDataOffset(1); // dummy to make size correct
firstTrun.setDataOffset((int) (8 + moof.getSize())); // mdat header + moof size
return moof;
}
protected Box createMvhd(Movie movie) {
MovieHeaderBox mvhd = new MovieHeaderBox();
mvhd.setCreationTime(DateHelper.convert(new Date()));
mvhd.setModificationTime(DateHelper.convert(new Date()));
long movieTimeScale = movie.getTimescale();
long duration = 0;
for (Track track : movie.getTracks()) {
long tracksDuration = getDuration(track) * movieTimeScale / track.getTrackMetaData().getTimescale();
if (tracksDuration > duration) {
duration = tracksDuration;
}
}
mvhd.setDuration(duration);
mvhd.setTimescale(movieTimeScale);
// find the next available trackId
long nextTrackId = 0;
for (Track track : movie.getTracks()) {
nextTrackId = nextTrackId < track.getTrackMetaData().getTrackId() ? track.getTrackMetaData().getTrackId() : nextTrackId;
}
mvhd.setNextTrackId(++nextTrackId);
return mvhd;
}
protected Box createMoov(Movie movie) {
MovieBox movieBox = new MovieBox();
movieBox.addBox(createMvhd(movie));
movieBox.addBox(createMvex(movie));
for (Track track : movie.getTracks()) {
movieBox.addBox(createTrak(track, movie));
}
// metadata here
return movieBox;
}
protected Box createTfra(Track track, IsoFile isoFile) {
TrackFragmentRandomAccessBox tfra = new TrackFragmentRandomAccessBox();
tfra.setVersion(1); // use long offsets and times
List<TrackFragmentRandomAccessBox.Entry> offset2timeEntries = new LinkedList<TrackFragmentRandomAccessBox.Entry>();
List<Box> boxes = isoFile.getBoxes();
long offset = 0;
long duration = 0;
for (Box box : boxes) {
if (box instanceof MovieFragmentBox) {
List<TrackFragmentBox> trafs = ((MovieFragmentBox) box).getBoxes(TrackFragmentBox.class);
for (int i = 0; i < trafs.size(); i++) {
TrackFragmentBox traf = trafs.get(i);
if (traf.getTrackFragmentHeaderBox().getTrackId() == track.getTrackMetaData().getTrackId()) {
// here we are at the offset required for the current entry.
List<TrackRunBox> truns = traf.getBoxes(TrackRunBox.class);
for (int j = 0; j < truns.size(); j++) {
List<TrackFragmentRandomAccessBox.Entry> offset2timeEntriesThisTrun = new LinkedList<TrackFragmentRandomAccessBox.Entry>();
TrackRunBox trun = truns.get(j);
for (int k = 0; k < trun.getEntries().size(); k++) {
TrackRunBox.Entry trunEntry = trun.getEntries().get(k);
SampleFlags sf = null;
if (k == 0 && trun.isFirstSampleFlagsPresent()) {
sf = trun.getFirstSampleFlags();
} else if (trun.isSampleFlagsPresent()) {
sf = trunEntry.getSampleFlags();
} else {
List<MovieExtendsBox> mvexs = isoFile.getMovieBox().getBoxes(MovieExtendsBox.class);
for (MovieExtendsBox mvex : mvexs) {
List<TrackExtendsBox> trexs = mvex.getBoxes(TrackExtendsBox.class);
for (TrackExtendsBox trex : trexs) {
if (trex.getTrackId() == track.getTrackMetaData().getTrackId()) {
sf = trex.getDefaultSampleFlags();
}
}
}
}
if (sf == null) {
throw new RuntimeException("Could not find any SampleFlags to indicate random access or not");
}
if (sf.getSampleDependsOn() == 2) {
offset2timeEntriesThisTrun.add(new TrackFragmentRandomAccessBox.Entry(
duration,
offset,
i + 1, j + 1, k + 1));
duration += trunEntry.getSampleDuration();
}
}
if (offset2timeEntriesThisTrun.size() == trun.getEntries().size() && trun.getEntries().size() > 0) {
// Oooops every sample seems to be random access sample
// is this an audio track? I don't care.
// I just use the first for trun sample for tfra random access
offset2timeEntries.add(offset2timeEntriesThisTrun.get(0));
} else {
offset2timeEntries.addAll(offset2timeEntriesThisTrun);
}
}
}
}
}
offset += box.getSize();
}
tfra.setEntries(offset2timeEntries);
tfra.setTrackId(track.getTrackMetaData().getTrackId());
return tfra;
}
protected Box createMfra(Movie movie, IsoFile isoFile) {
MovieFragmentRandomAccessBox mfra = new MovieFragmentRandomAccessBox();
for (Track track : movie.getTracks()) {
mfra.addBox(createTfra(track, isoFile));
}
MovieFragmentRandomAccessOffsetBox mfro = new MovieFragmentRandomAccessOffsetBox();
mfra.addBox(mfro);
mfro.setMfraSize(mfra.getSize());
return mfra;
}
protected Box createTrex(Movie movie, Track track) {
TrackExtendsBox trex = new TrackExtendsBox();
trex.setTrackId(track.getTrackMetaData().getTrackId());
trex.setDefaultSampleDescriptionIndex(1);
trex.setDefaultSampleDuration(0);
trex.setDefaultSampleSize(0);
SampleFlags sf = new SampleFlags();
if ("soun".equals(track.getHandler())) {
// as far as I know there is no audio encoding
// where the sample are not self contained.
sf.setSampleDependsOn(2);
sf.setSampleIsDependedOn(2);
}
trex.setDefaultSampleFlags(sf);
return trex;
}
protected Box createMvex(Movie movie) {
MovieExtendsBox mvex = new MovieExtendsBox();
for (Track track : movie.getTracks()) {
mvex.addBox(createTrex(movie, track));
}
return mvex;
}
protected Box createTkhd(Movie movie, Track track) {
TrackHeaderBox tkhd = new TrackHeaderBox();
int flags = 0;
if (track.isEnabled()) {
flags += 1;
}
if (track.isInMovie()) {
flags += 2;
}
if (track.isInPreview()) {
flags += 4;
}
if (track.isInPoster()) {
flags += 8;
}
tkhd.setFlags(flags);
tkhd.setAlternateGroup(track.getTrackMetaData().getGroup());
tkhd.setCreationTime(DateHelper.convert(track.getTrackMetaData().getCreationTime()));
// We need to take edit list box into account in trackheader duration
// but as long as I don't support edit list boxes it is sufficient to
// just translate media duration to movie timescale
tkhd.setDuration(getDuration(track) * movie.getTimescale() / track.getTrackMetaData().getTimescale());
tkhd.setHeight(track.getTrackMetaData().getHeight());
tkhd.setWidth(track.getTrackMetaData().getWidth());
tkhd.setLayer(track.getTrackMetaData().getLayer());
tkhd.setModificationTime(DateHelper.convert(new Date()));
tkhd.setTrackId(track.getTrackMetaData().getTrackId());
tkhd.setVolume(track.getTrackMetaData().getVolume());
return tkhd;
}
protected Box createMdhd(Movie movie, Track track) {
MediaHeaderBox mdhd = new MediaHeaderBox();
mdhd.setCreationTime(DateHelper.convert(track.getTrackMetaData().getCreationTime()));
mdhd.setDuration(getDuration(track));
mdhd.setTimescale(track.getTrackMetaData().getTimescale());
mdhd.setLanguage(track.getTrackMetaData().getLanguage());
return mdhd;
}
protected Box createStbl(Movie movie, Track track) {
SampleTableBox stbl = new SampleTableBox();
stbl.addBox(track.getSampleDescriptionBox());
stbl.addBox(new TimeToSampleBox());
//stbl.addBox(new SampleToChunkBox());
stbl.addBox(new StaticChunkOffsetBox());
return stbl;
}
protected Box createMinf(Track track, Movie movie) {
MediaInformationBox minf = new MediaInformationBox();
minf.addBox(track.getMediaHeaderBox());
minf.addBox(createDinf(movie, track));
minf.addBox(createStbl(movie, track));
return minf;
}
protected Box createMdiaHdlr(Track track, Movie movie) {
HandlerBox hdlr = new HandlerBox();
hdlr.setHandlerType(track.getHandler());
return hdlr;
}
protected Box createMdia(Track track, Movie movie) {
MediaBox mdia = new MediaBox();
mdia.addBox(createMdhd(movie, track));
mdia.addBox(createMdiaHdlr(track, movie));
mdia.addBox(createMinf(track, movie));
return mdia;
}
protected Box createTrak(Track track, Movie movie) {
LOG.info("Creating Track " + track);
TrackBox trackBox = new TrackBox();
trackBox.addBox(createTkhd(movie, track));
trackBox.addBox(createMdia(track, movie));
return trackBox;
}
protected DataInformationBox createDinf(Movie movie, Track track) {
DataInformationBox dinf = new DataInformationBox();
DataReferenceBox dref = new DataReferenceBox();
dinf.addBox(dref);
DataEntryUrlBox url = new DataEntryUrlBox();
url.setFlags(1);
dref.addBox(url);
return dinf;
}
public void setIntersectionFinder(FragmentIntersectionFinder intersectionFinder) {
this.intersectionFinder = intersectionFinder;
}
protected long getDuration(Track track) {
long duration = 0;
for (TimeToSampleBox.Entry entry : track.getDecodingTimeEntries()) {
duration += entry.getCount() * entry.getDelta();
}
return duration;
}
}
| src/main/java/com/googlecode/mp4parser/authoring/builder/FragmentedMp4Builder.java | package com.googlecode.mp4parser.authoring.builder;
import com.coremedia.iso.BoxParser;
import com.coremedia.iso.Hex;
import com.coremedia.iso.IsoFile;
import com.coremedia.iso.IsoTypeWriter;
import com.coremedia.iso.boxes.Box;
import com.coremedia.iso.boxes.CompositionTimeToSample;
import com.coremedia.iso.boxes.ContainerBox;
import com.coremedia.iso.boxes.DataEntryUrlBox;
import com.coremedia.iso.boxes.DataInformationBox;
import com.coremedia.iso.boxes.DataReferenceBox;
import com.coremedia.iso.boxes.FileTypeBox;
import com.coremedia.iso.boxes.HandlerBox;
import com.coremedia.iso.boxes.MediaBox;
import com.coremedia.iso.boxes.MediaHeaderBox;
import com.coremedia.iso.boxes.MediaInformationBox;
import com.coremedia.iso.boxes.MovieBox;
import com.coremedia.iso.boxes.MovieHeaderBox;
import com.coremedia.iso.boxes.SampleDependencyTypeBox;
import com.coremedia.iso.boxes.SampleTableBox;
import com.coremedia.iso.boxes.StaticChunkOffsetBox;
import com.coremedia.iso.boxes.TimeToSampleBox;
import com.coremedia.iso.boxes.TrackBox;
import com.coremedia.iso.boxes.TrackHeaderBox;
import com.coremedia.iso.boxes.fragment.MovieExtendsBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentHeaderBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentRandomAccessBox;
import com.coremedia.iso.boxes.fragment.MovieFragmentRandomAccessOffsetBox;
import com.coremedia.iso.boxes.fragment.SampleFlags;
import com.coremedia.iso.boxes.fragment.TrackExtendsBox;
import com.coremedia.iso.boxes.fragment.TrackFragmentBox;
import com.coremedia.iso.boxes.fragment.TrackFragmentHeaderBox;
import com.coremedia.iso.boxes.fragment.TrackFragmentRandomAccessBox;
import com.coremedia.iso.boxes.fragment.TrackRunBox;
import com.googlecode.mp4parser.authoring.DateHelper;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.logging.Logger;
import static com.coremedia.iso.boxes.CastUtils.l2i;
/**
* Creates a fragmented MP4 file.
*/
public class FragmentedMp4Builder implements Mp4Builder {
FragmentIntersectionFinder intersectionFinder = new SyncSampleIntersectFinderImpl();
private static final Logger LOG = Logger.getLogger(FragmentedMp4Builder.class.getName());
public List<String> getAllowedHandlers() {
return Arrays.asList("soun", "vide");
}
public Box createFtyp(Movie movie) {
List<String> minorBrands = new LinkedList<String>();
minorBrands.add("isom");
minorBrands.add("iso2");
minorBrands.add("avc1");
return new FileTypeBox("isom", 0, minorBrands);
}
protected List<Box> createMoofMdat(Movie movie) {
List<Box> boxes = new LinkedList<Box>();
int maxNumberOfFragments = 0;
for (Track track : movie.getTracks()) {
int currentLength = intersectionFinder.sampleNumbers(track, movie).length;
maxNumberOfFragments = currentLength > maxNumberOfFragments ? currentLength : maxNumberOfFragments;
}
int sequence = 1;
for (int i = 0; i < maxNumberOfFragments; i++) {
for (Track track : movie.getTracks()) {
if (getAllowedHandlers().isEmpty() || getAllowedHandlers().contains(track.getHandler())) {
int[] startSamples = intersectionFinder.sampleNumbers(track, movie);
if (i < startSamples.length) {
int startSample = startSamples[i];
int endSample = i + 1 < startSamples.length ? startSamples[i + 1] : track.getSamples().size();
if (startSample == endSample) {
// empty fragment
// just don't add any boxes.
} else {
boxes.add(createMoof(startSample, endSample, track, sequence));
boxes.add(createMdat(startSample, endSample, track, sequence++));
}
} else {
//obvious this track has not that many fragments
}
}
}
}
return boxes;
}
public IsoFile build(Movie movie) throws IOException {
LOG.info("Creating movie " + movie);
IsoFile isoFile = new IsoFile();
isoFile.addBox(createFtyp(movie));
isoFile.addBox(createMoov(movie));
for (Box box : createMoofMdat(movie)) {
isoFile.addBox(box);
}
isoFile.addBox(createMfra(movie, isoFile));
return isoFile;
}
protected Box createMdat(int startSample, int endSample, Track track, int i) {
final List<ByteBuffer> samples = ByteBufferHelper.mergeAdjacentBuffers(getSamples(startSample, endSample, track, i));
return new Box() {
ContainerBox parent;
public ContainerBox getParent() {
return parent;
}
public void setParent(ContainerBox parent) {
this.parent = parent;
}
public long getSize() {
long size = 8; // I don't expect 2gig fragments
for (ByteBuffer sample : samples) {
size += sample.limit();
}
return size;
}
public String getType() {
return "mdat";
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
ByteBuffer header = ByteBuffer.allocate(8);
IsoTypeWriter.writeUInt32(header, l2i(getSize()));
header.put(IsoFile.fourCCtoBytes(getType()));
header.rewind();
writableByteChannel.write(header);
if (writableByteChannel instanceof GatheringByteChannel) {
int STEPSIZE = 1024;
for (int i = 0; i < Math.ceil((double) samples.size() / STEPSIZE); i++) {
List<ByteBuffer> sublist = samples.subList(
i * STEPSIZE, // start
(i + 1) * STEPSIZE < samples.size() ? (i + 1) * STEPSIZE : samples.size()); // end
ByteBuffer sampleArray[] = sublist.toArray(new ByteBuffer[sublist.size()]);
do {
((GatheringByteChannel) writableByteChannel).write(sampleArray);
} while (sampleArray[sampleArray.length - 1].remaining() > 0);
}
//System.err.println(bytesWritten);
} else {
for (ByteBuffer sample : samples) {
sample.rewind();
writableByteChannel.write(sample);
}
}
}
public void parse(ReadableByteChannel inFC, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
}
};
}
public static void dumpHex(ByteBuffer bb) {
byte[] b = new byte[bb.limit()];
bb.get(b);
System.err.println(Hex.encodeHex(b));
bb.rewind();
}
protected Box createTfhd(int startSample, int endSample, Track track, int sequenceNumber) {
TrackFragmentHeaderBox tfhd = new TrackFragmentHeaderBox();
SampleFlags sf = new SampleFlags();
tfhd.setDefaultSampleFlags(sf);
tfhd.setBaseDataOffset(-1);
tfhd.setTrackId(track.getTrackMetaData().getTrackId());
return tfhd;
}
protected Box createMfhd(int startSample, int endSample, Track track, int sequenceNumber) {
MovieFragmentHeaderBox mfhd = new MovieFragmentHeaderBox();
mfhd.setSequenceNumber(sequenceNumber);
return mfhd;
}
protected Box createTraf(int startSample, int endSample, Track track, int sequenceNumber) {
TrackFragmentBox traf = new TrackFragmentBox();
traf.addBox(createTfhd(startSample, endSample, track, sequenceNumber));
for (Box trun : createTruns(startSample, endSample, track, sequenceNumber)) {
traf.addBox(trun);
}
return traf;
}
protected List<ByteBuffer> getSamples(int startSample, int endSample, Track track, int sequenceNumber) {
return track.getSamples().subList(startSample, endSample);
}
protected List<? extends Box> createTruns(int startSample, int endSample, Track track, int sequenceNumber) {
List<ByteBuffer> samples = getSamples(startSample, endSample, track, sequenceNumber);
long[] sampleSizes = new long[samples.size()];
for (int i = 0; i < sampleSizes.length; i++) {
sampleSizes[i] = samples.get(i).limit();
}
TrackRunBox trun = new TrackRunBox();
trun.setSampleDurationPresent(true);
trun.setSampleSizePresent(true);
List<TrackRunBox.Entry> entries = new ArrayList<TrackRunBox.Entry>(endSample - startSample);
Queue<TimeToSampleBox.Entry> timeQueue = new LinkedList<TimeToSampleBox.Entry>(track.getDecodingTimeEntries());
long durationEntriesLeft = timeQueue.peek().getCount();
Queue<CompositionTimeToSample.Entry> compositionTimeQueue =
track.getCompositionTimeEntries() != null && track.getCompositionTimeEntries().size() > 0 ?
new LinkedList<CompositionTimeToSample.Entry>(track.getCompositionTimeEntries()) : null;
long compositionTimeEntriesLeft = compositionTimeQueue != null ? compositionTimeQueue.peek().getCount() : -1;
trun.setSampleCompositionTimeOffsetPresent(compositionTimeEntriesLeft > 0);
boolean sampleFlagsRequired = (track.getSampleDependencies() != null && !track.getSampleDependencies().isEmpty() ||
track.getSyncSamples() != null && track.getSyncSamples().length != 0);
trun.setSampleFlagsPresent(sampleFlagsRequired);
for (int i = 0; i < sampleSizes.length; i++) {
TrackRunBox.Entry entry = new TrackRunBox.Entry();
entry.setSampleSize(sampleSizes[i]);
if (sampleFlagsRequired) {
//if (false) {
SampleFlags sflags = new SampleFlags();
if (track.getSampleDependencies() != null && !track.getSampleDependencies().isEmpty()) {
SampleDependencyTypeBox.Entry e = track.getSampleDependencies().get(i);
sflags.setSampleDependsOn(e.getSampleDependsOn());
sflags.setSampleIsDependedOn(e.getSampleIsDependentOn());
sflags.setSampleHasRedundancy(e.getSampleHasRedundancy());
}
if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) {
// we have to mark non-sync samples!
if (Arrays.binarySearch(track.getSyncSamples(), startSample + i + 1) >= 0) {
sflags.setSampleIsDifferenceSample(false);
sflags.setSampleDependsOn(2);
} else {
sflags.setSampleIsDifferenceSample(true);
sflags.setSampleDependsOn(1);
}
}
// i don't have sample degradation
entry.setSampleFlags(sflags);
}
entry.setSampleDuration(timeQueue.peek().getDelta());
if (--durationEntriesLeft == 0 && timeQueue.size() > 1) {
timeQueue.remove();
durationEntriesLeft = timeQueue.peek().getCount();
}
if (compositionTimeQueue != null) {
trun.setSampleCompositionTimeOffsetPresent(true);
entry.setSampleCompositionTimeOffset(compositionTimeQueue.peek().getOffset());
if (--compositionTimeEntriesLeft == 0 && compositionTimeQueue.size() > 1) {
compositionTimeQueue.remove();
compositionTimeEntriesLeft = compositionTimeQueue.element().getCount();
}
}
entries.add(entry);
}
trun.setEntries(entries);
return Collections.singletonList(trun);
}
protected Box createMoof(int startSample, int endSample, Track track, int sequenceNumber) {
MovieFragmentBox moof = new MovieFragmentBox();
moof.addBox(createMfhd(startSample, endSample, track, sequenceNumber));
moof.addBox(createTraf(startSample, endSample, track, sequenceNumber));
TrackRunBox firstTrun = moof.getTrackRunBoxes().get(0);
firstTrun.setDataOffset(1); // dummy to make size correct
firstTrun.setDataOffset((int) (8 + moof.getSize())); // mdat header + moof size
return moof;
}
protected Box createMvhd(Movie movie) {
MovieHeaderBox mvhd = new MovieHeaderBox();
mvhd.setCreationTime(DateHelper.convert(new Date()));
mvhd.setModificationTime(DateHelper.convert(new Date()));
long movieTimeScale = movie.getTimescale();
long duration = 0;
for (Track track : movie.getTracks()) {
long tracksDuration = getDuration(track) * movieTimeScale / track.getTrackMetaData().getTimescale();
if (tracksDuration > duration) {
duration = tracksDuration;
}
}
mvhd.setDuration(duration);
mvhd.setTimescale(movieTimeScale);
// find the next available trackId
long nextTrackId = 0;
for (Track track : movie.getTracks()) {
nextTrackId = nextTrackId < track.getTrackMetaData().getTrackId() ? track.getTrackMetaData().getTrackId() : nextTrackId;
}
mvhd.setNextTrackId(++nextTrackId);
return mvhd;
}
protected Box createMoov(Movie movie) {
MovieBox movieBox = new MovieBox();
movieBox.addBox(createMvhd(movie));
movieBox.addBox(createMvex(movie));
for (Track track : movie.getTracks()) {
movieBox.addBox(createTrak(track, movie));
}
// metadata here
return movieBox;
}
protected Box createTfra(Track track, IsoFile isoFile) {
TrackFragmentRandomAccessBox tfra = new TrackFragmentRandomAccessBox();
tfra.setVersion(1); // use long offsets and times
List<TrackFragmentRandomAccessBox.Entry> offset2timeEntries = new LinkedList<TrackFragmentRandomAccessBox.Entry>();
List<Box> boxes = isoFile.getBoxes();
long offset = 0;
long duration = 0;
for (Box box : boxes) {
if (box instanceof MovieFragmentBox) {
List<TrackFragmentBox> trafs = ((MovieFragmentBox) box).getBoxes(TrackFragmentBox.class);
for (int i = 0; i < trafs.size(); i++) {
TrackFragmentBox traf = trafs.get(i);
if (traf.getTrackFragmentHeaderBox().getTrackId() == track.getTrackMetaData().getTrackId()) {
// here we are at the offset required for the current entry.
List<TrackRunBox> truns = traf.getBoxes(TrackRunBox.class);
for (int j = 0; j < truns.size(); j++) {
List<TrackFragmentRandomAccessBox.Entry> offset2timeEntriesThisTrun = new LinkedList<TrackFragmentRandomAccessBox.Entry>();
TrackRunBox trun = truns.get(j);
for (int k = 0; k < trun.getEntries().size(); k++) {
TrackRunBox.Entry trunEntry = trun.getEntries().get(k);
SampleFlags sf = null;
if (k == 0 && trun.isFirstSampleFlagsPresent()) {
sf = trun.getFirstSampleFlags();
} else if (trun.isSampleFlagsPresent()) {
sf = trunEntry.getSampleFlags();
} else {
List<MovieExtendsBox> mvexs = isoFile.getMovieBox().getBoxes(MovieExtendsBox.class);
for (MovieExtendsBox mvex : mvexs) {
List<TrackExtendsBox> trexs = mvex.getBoxes(TrackExtendsBox.class);
for (TrackExtendsBox trex : trexs) {
if (trex.getTrackId() == track.getTrackMetaData().getTrackId()) {
sf = trex.getDefaultSampleFlags();
}
}
}
}
if (sf == null) {
throw new RuntimeException("Could not find any SampleFlags to indicate random access or not");
}
if (sf.getSampleDependsOn() == 2) {
offset2timeEntriesThisTrun.add(new TrackFragmentRandomAccessBox.Entry(
duration,
offset,
i + 1, j + 1, k + 1));
duration += trunEntry.getSampleDuration();
}
}
if (offset2timeEntriesThisTrun.size() == trun.getEntries().size() && trun.getEntries().size() > 0) {
// Oooops every sample seems to be random access sample
// is this an audio track? I don't care.
// I just use the first for trun sample for tfra random access
offset2timeEntries.add(offset2timeEntriesThisTrun.get(0));
} else {
offset2timeEntries.addAll(offset2timeEntriesThisTrun);
}
}
}
}
}
offset += box.getSize();
}
tfra.setEntries(offset2timeEntries);
tfra.setTrackId(track.getTrackMetaData().getTrackId());
return tfra;
}
protected Box createMfra(Movie movie, IsoFile isoFile) {
MovieFragmentRandomAccessBox mfra = new MovieFragmentRandomAccessBox();
for (Track track : movie.getTracks()) {
mfra.addBox(createTfra(track, isoFile));
}
MovieFragmentRandomAccessOffsetBox mfro = new MovieFragmentRandomAccessOffsetBox();
mfra.addBox(mfro);
mfro.setMfraSize(mfra.getSize());
return mfra;
}
protected Box createTrex(Movie movie, Track track) {
TrackExtendsBox trex = new TrackExtendsBox();
trex.setTrackId(track.getTrackMetaData().getTrackId());
trex.setDefaultSampleDescriptionIndex(1);
trex.setDefaultSampleDuration(0);
trex.setDefaultSampleSize(0);
SampleFlags sf = new SampleFlags();
if ("soun".equals(track.getHandler())) {
// as far as I know there is no audio encoding
// where the sample are not self contained.
sf.setSampleDependsOn(2);
sf.setSampleIsDependedOn(2);
}
trex.setDefaultSampleFlags(sf);
return trex;
}
protected Box createMvex(Movie movie) {
MovieExtendsBox mvex = new MovieExtendsBox();
for (Track track : movie.getTracks()) {
mvex.addBox(createTrex(movie, track));
}
return mvex;
}
protected Box createTkhd(Movie movie, Track track) {
TrackHeaderBox tkhd = new TrackHeaderBox();
int flags = 0;
if (track.isEnabled()) {
flags += 1;
}
if (track.isInMovie()) {
flags += 2;
}
if (track.isInPreview()) {
flags += 4;
}
if (track.isInPoster()) {
flags += 8;
}
tkhd.setFlags(flags);
tkhd.setAlternateGroup(track.getTrackMetaData().getGroup());
tkhd.setCreationTime(DateHelper.convert(track.getTrackMetaData().getCreationTime()));
// We need to take edit list box into account in trackheader duration
// but as long as I don't support edit list boxes it is sufficient to
// just translate media duration to movie timescale
tkhd.setDuration(getDuration(track) * movie.getTimescale() / track.getTrackMetaData().getTimescale());
tkhd.setHeight(track.getTrackMetaData().getHeight());
tkhd.setWidth(track.getTrackMetaData().getWidth());
tkhd.setLayer(track.getTrackMetaData().getLayer());
tkhd.setModificationTime(DateHelper.convert(new Date()));
tkhd.setTrackId(track.getTrackMetaData().getTrackId());
tkhd.setVolume(track.getTrackMetaData().getVolume());
return tkhd;
}
protected Box createMdhd(Movie movie, Track track) {
MediaHeaderBox mdhd = new MediaHeaderBox();
mdhd.setCreationTime(DateHelper.convert(track.getTrackMetaData().getCreationTime()));
mdhd.setDuration(getDuration(track));
mdhd.setTimescale(track.getTrackMetaData().getTimescale());
mdhd.setLanguage(track.getTrackMetaData().getLanguage());
return mdhd;
}
protected Box createStbl(Movie movie, Track track) {
SampleTableBox stbl = new SampleTableBox();
stbl.addBox(track.getSampleDescriptionBox());
stbl.addBox(new TimeToSampleBox());
//stbl.addBox(new SampleToChunkBox());
stbl.addBox(new StaticChunkOffsetBox());
return stbl;
}
protected Box createMinf(Track track, Movie movie) {
MediaInformationBox minf = new MediaInformationBox();
minf.addBox(track.getMediaHeaderBox());
minf.addBox(createDinf(movie, track));
minf.addBox(createStbl(movie, track));
return minf;
}
protected Box createMdiaHdlr(Track track, Movie movie) {
HandlerBox hdlr = new HandlerBox();
hdlr.setHandlerType(track.getHandler());
return hdlr;
}
protected Box createMdia(Track track, Movie movie) {
MediaBox mdia = new MediaBox();
mdia.addBox(createMdhd(movie, track));
mdia.addBox(createMdiaHdlr(track, movie));
mdia.addBox(createMinf(track, movie));
return mdia;
}
protected Box createTrak(Track track, Movie movie) {
LOG.info("Creating Track " + track);
TrackBox trackBox = new TrackBox();
trackBox.addBox(createTkhd(movie, track));
trackBox.addBox(createMdia(track, movie));
return trackBox;
}
protected DataInformationBox createDinf(Movie movie, Track track) {
DataInformationBox dinf = new DataInformationBox();
DataReferenceBox dref = new DataReferenceBox();
dinf.addBox(dref);
DataEntryUrlBox url = new DataEntryUrlBox();
url.setFlags(1);
dref.addBox(url);
return dinf;
}
public void setIntersectionFinder(FragmentIntersectionFinder intersectionFinder) {
this.intersectionFinder = intersectionFinder;
}
protected long getDuration(Track track) {
long duration = 0;
for (TimeToSampleBox.Entry entry : track.getDecodingTimeEntries()) {
duration += entry.getCount() * entry.getDelta();
}
return duration;
}
}
| sort fragments according to their sizes
git-svn-id: c4d2d6f4036cbf3d898a71de5246e4e6216e7677@412 7decde4b-c250-0410-a0da-51896bc88be6
| src/main/java/com/googlecode/mp4parser/authoring/builder/FragmentedMp4Builder.java | sort fragments according to their sizes | <ide><path>rc/main/java/com/googlecode/mp4parser/authoring/builder/FragmentedMp4Builder.java
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<add>import java.util.Comparator;
<ide> import java.util.Date;
<add>import java.util.HashMap;
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<add>import java.util.Map;
<ide> import java.util.Queue;
<ide> import java.util.logging.Logger;
<ide>
<ide> return new FileTypeBox("isom", 0, minorBrands);
<ide> }
<ide>
<del> protected List<Box> createMoofMdat(Movie movie) {
<add> protected List<Box> createMoofMdat(final Movie movie) {
<ide> List<Box> boxes = new LinkedList<Box>();
<ide> int maxNumberOfFragments = 0;
<ide> for (Track track : movie.getTracks()) {
<ide> }
<ide> int sequence = 1;
<ide> for (int i = 0; i < maxNumberOfFragments; i++) {
<del> for (Track track : movie.getTracks()) {
<add>
<add> final List<Track> sizeSortedTracks = new LinkedList<Track>(movie.getTracks());
<add> final int j = i;
<add> Collections.sort(sizeSortedTracks, new Comparator<Track>() {
<add> public int compare(Track o1, Track o2) {
<add> int[] startSamples1 = intersectionFinder.sampleNumbers(o1, movie);
<add> int startSample1 = startSamples1[j];
<add> int endSample1 = j + 1 < startSamples1.length ? startSamples1[j + 1] : o1.getSamples().size();
<add> int[] startSamples2 = intersectionFinder.sampleNumbers(o2, movie);
<add> int startSample2 = startSamples2[j];
<add> int endSample2 = j + 1 < startSamples2.length ? startSamples2[j + 1] : o2.getSamples().size();
<add> List<ByteBuffer> samples1 = o1.getSamples().subList(startSample1, endSample1);
<add> List<ByteBuffer> samples2 = o2.getSamples().subList(startSample2, endSample2);
<add> int size1 = 0;
<add> for (ByteBuffer byteBuffer : samples1) {
<add> size1 += byteBuffer.limit();
<add> }
<add> int size2 = 0;
<add> for (ByteBuffer byteBuffer : samples2) {
<add> size2 += byteBuffer.limit();
<add> }
<add> return size1 - size2;
<add> }
<add> });
<add>
<add> for (Track track : sizeSortedTracks) {
<ide> if (getAllowedHandlers().isEmpty() || getAllowedHandlers().contains(track.getHandler())) {
<ide> int[] startSamples = intersectionFinder.sampleNumbers(track, movie);
<ide>
<ide> }
<ide> }
<ide> }
<add>
<add>
<add>
<ide> }
<ide> return boxes;
<ide> } |
|
JavaScript | mit | 2a7169df7ccea1d4571f7c91e1b4e590b6f03ee4 | 0 | Jam3/generator-jam3,Jam3/generator-jam3,Jam3/generator-jam3 | 'use strict';
var fs = require('graceful-fs');
var path = require('path');
var config = require('./config');
var mkdirp = require('mkdirp');
var browserify = require('browserify');
var uglify = require('uglify-js');
var concat = require('concat-stream');
var pkg = require('../package.json');
var deps = Object.keys(pkg.dependencies);
process.env.NODE_ENV = config.NODE_ENV;
process.env.ASSET_PATH = config.ASSET_PATH;
var post = function(file,src) {
mkdirp(config.output,function(err) {
if (!err) {
try {
var min = uglify.minify(src.toString(),{fromString: true});
} catch(err) {
fs.writeFile(path.join(config.output,file),src.toString(),function(e) {
console.log('\x1b[31m Error at line',err.line+':',err.message+'\x1b[0m');
});
}
if (min) {
fs.writeFile(path.join(config.output,file),min.code,function(err) {
console.log((err) ? '\x1b[31m Failed to output '+file+'\x1b[0m' : '\x1b[32m '+file+' created successfully.\x1b[0m');
});
}
} else {
console.log('\x1b[31m Cannot create ouput folder\x1b[0m');
}
});
};
if (config.vendor && typeof config.vendor === 'string') {
browserify(config.entry).external(deps).bundle().pipe(concat(post.bind(undefined,config.bundle)));
browserify().require(deps).bundle().pipe(concat(post.bind(undefined,config.vendor)));
} else {
browserify(config.entry).bundle().pipe(concat(post.bind(undefined,config.bundle)));
}
| templates/scripts/release.js | 'use strict';
var fs = require('graceful-fs');
var config = require('./config');
var mkdirp = require('mkdirp');
var browserify = require('browserify');
var uglify = require('uglify-js');
var concat = require('concat-stream');
var pkg = require('../package.json');
var deps = Object.keys(pkg.dependencies);
process.env.NODE_ENV = config.NODE_ENV;
process.env.ASSET_PATH = config.ASSET_PATH;
var post = function(file,src) {
mkdirp(config.output,function(err) {
if (!err) {
try {
var min = uglify.minify(src.toString(),{fromString: true});
} catch(err) {
fs.writeFile(path.join(config.output,file),src.toString(),function(e) {
console.log('\x1b[31m Error at line',err.line+':',err.message+'\x1b[0m');
});
}
if (min) {
fs.writeFile(path.join(config.output,file),min.code,function(err) {
console.log((err) ? '\x1b[31m Failed to output '+file+'\x1b[0m' : '\x1b[32m '+file+' created successfully.\x1b[0m');
});
}
} else {
console.log('\x1b[31m Cannot create ouput folder\x1b[0m');
}
});
};
if (config.vendor && typeof config.vendor === 'string') {
browserify(config.entry).external(deps).bundle().pipe(concat(post.bind(undefined,config.bundle)));
browserify().require(deps).bundle().pipe(concat(post.bind(undefined,config.vendor)));
} else {
browserify(config.entry).bundle().pipe(concat(post.bind(undefined,config.bundle)));
}
| Fixed release path include
| templates/scripts/release.js | Fixed release path include | <ide><path>emplates/scripts/release.js
<ide> 'use strict';
<ide> var fs = require('graceful-fs');
<add>var path = require('path');
<ide> var config = require('./config');
<ide> var mkdirp = require('mkdirp');
<ide> var browserify = require('browserify'); |
|
Java | apache-2.0 | 15301f922a382b98431731e3079638117d6d8cf5 | 0 | jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate | /*
* InputSplit class for Syndicate
*/
package SyndicateHadoop.input;
import JSyndicateFS.FileSystem;
import JSyndicateFS.Path;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputSplit;
/**
*
* @author iychoi
*/
public class SyndicateInputSplit extends InputSplit implements Writable {
private FileSystem filesystem;
private Path path;
private long start;
private long length;
/*
* Constructs a split
*/
public SyndicateInputSplit(FileSystem fs, Path path, long start, long length) {
if(fs == null)
throw new IllegalArgumentException("Can not create Input Split from null file system");
if(path == null)
throw new IllegalArgumentException("Can not create Input Split from null path");
this.filesystem = fs;
this.path = path;
this.start = start;
this.length = length;
}
public FileSystem getFileSystem() {
return this.filesystem;
}
/*
* The file containing this split's data
*/
public Path getPath() {
return this.path;
}
/*
* The position of split start
*/
public long getStart() {
return this.start;
}
/*
* The number of bytes in the file to process
*/
@Override
public long getLength() {
return this.length;
}
@Override
public String toString() {
return this.path.getPath() + ":" + start + "+" + length;
}
@Override
public String[] getLocations() throws IOException, InterruptedException {
String volume = this.filesystem.getConfiguration().getVolumeName();
return new String[] {volume};
}
@Override
public void write(DataOutput out) throws IOException {
Text.writeString(out, this.path.getPath());
out.writeLong(this.start);
out.writeLong(this.length);
}
@Override
public void readFields(DataInput in) throws IOException {
this.path = new Path(Text.readString(in));
this.start = in.readLong();
this.length = in.readLong();
}
}
| UG-shared/SyndicateHadoop/src/SyndicateHadoop/input/SyndicateInputSplit.java | /*
* InputSplit class for Syndicate
*/
package SyndicateHadoop.input;
import JSyndicateFS.FileSystem;
import JSyndicateFS.Path;
import java.io.IOException;
import org.apache.hadoop.mapreduce.InputSplit;
/**
*
* @author iychoi
*/
public class SyndicateInputSplit extends InputSplit {
private FileSystem filesystem;
private Path path;
private long start;
private long length;
/*
* Constructs a split
*/
public SyndicateInputSplit(FileSystem fs, Path path, long start, long length) {
if(fs == null)
throw new IllegalArgumentException("Can not create Input Split from null file system");
if(path == null)
throw new IllegalArgumentException("Can not create Input Split from null path");
this.filesystem = fs;
this.path = path;
this.start = start;
this.length = length;
}
public FileSystem getFileSystem() {
return this.filesystem;
}
/*
* The file containing this split's data
*/
public Path getPath() {
return this.path;
}
/*
* The position of split start
*/
public long getStart() {
return this.start;
}
/*
* The number of bytes in the file to process
*/
@Override
public long getLength() {
return this.length;
}
@Override
public String toString() {
return this.path.getPath() + ":" + start + "+" + length;
}
@Override
public String[] getLocations() throws IOException, InterruptedException {
return null;
}
}
| Add writable interface to InputSplit | UG-shared/SyndicateHadoop/src/SyndicateHadoop/input/SyndicateInputSplit.java | Add writable interface to InputSplit | <ide><path>G-shared/SyndicateHadoop/src/SyndicateHadoop/input/SyndicateInputSplit.java
<ide>
<ide> import JSyndicateFS.FileSystem;
<ide> import JSyndicateFS.Path;
<add>import java.io.DataInput;
<add>import java.io.DataOutput;
<ide> import java.io.IOException;
<add>import org.apache.hadoop.io.Text;
<add>import org.apache.hadoop.io.Writable;
<ide> import org.apache.hadoop.mapreduce.InputSplit;
<ide>
<ide> /**
<ide> *
<ide> * @author iychoi
<ide> */
<del>public class SyndicateInputSplit extends InputSplit {
<add>public class SyndicateInputSplit extends InputSplit implements Writable {
<ide>
<ide> private FileSystem filesystem;
<ide> private Path path;
<ide>
<ide> @Override
<ide> public String[] getLocations() throws IOException, InterruptedException {
<del> return null;
<add> String volume = this.filesystem.getConfiguration().getVolumeName();
<add> return new String[] {volume};
<add> }
<add>
<add> @Override
<add> public void write(DataOutput out) throws IOException {
<add> Text.writeString(out, this.path.getPath());
<add> out.writeLong(this.start);
<add> out.writeLong(this.length);
<add> }
<add>
<add> @Override
<add> public void readFields(DataInput in) throws IOException {
<add> this.path = new Path(Text.readString(in));
<add> this.start = in.readLong();
<add> this.length = in.readLong();
<ide> }
<ide> } |
|
Java | apache-2.0 | 51b39564171e34aa31aa982b13ab7bb490f761d5 | 0 | nikeshmhr/unitime,sktoo/timetabling-system-,nikeshmhr/unitime,zuzanamullerova/unitime,zuzanamullerova/unitime,nikeshmhr/unitime,zuzanamullerova/unitime,rafati/unitime,UniTime/unitime,UniTime/unitime,maciej-zygmunt/unitime,UniTime/unitime,sktoo/timetabling-system-,rafati/unitime,rafati/unitime,maciej-zygmunt/unitime,sktoo/timetabling-system-,maciej-zygmunt/unitime | /*
* UniTime 3.2 (University Timetabling Application)
* Copyright (C) 2008 - 2010, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.action;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.unitime.commons.MultiComparable;
import org.unitime.commons.web.WebTable;
import org.unitime.timetable.defaults.SessionAttribute;
import org.unitime.timetable.form.RoleListForm;
import org.unitime.timetable.model.Roles;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.dao.SessionDAO;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.UserAuthority;
import org.unitime.timetable.security.UserContext;
/**
* MyEclipse Struts
* Creation date: 03-17-2005
*
* XDoclet definition:
* @struts:action path="/selectPrimaryRole" name="roleListForm" input="/selectPrimaryRole.jsp" scope="request" validate="true"
* @struts:action-forward name="success" path="/main.jsp" contextRelative="true"
* @struts:action-forward name="fail" path="/selectPrimaryRole.jsp" contextRelative="true"
*/
@Service("/selectPrimaryRole")
public class RoleListAction extends Action {
@Autowired SessionContext sessionContext;
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
RoleListForm roleListForm = (RoleListForm) form;
UserContext user = null;
try {
user = (UserContext)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} catch (Exception e) {}
if (user == null) return mapping.findForward("loginRequired");
if (user.getAuthorities().isEmpty()) return mapping.findForward("norole");
// Form submitted
if (roleListForm.getAuthority() != null) {
UserAuthority authority = user.getAuthority(roleListForm.getAuthority());
if (authority != null) {
user.setCurrentAuthority(authority);
for (SessionAttribute s: SessionAttribute.values())
sessionContext.removeAttribute(s);
}
return mapping.findForward("success");
}
UserAuthority authority = setupAuthorities(request, user);
// Role/session list not requested -- try assign default role/session first
if (!"Y".equals(request.getParameter("list")) && authority != null) {
user.setCurrentAuthority(authority);
return mapping.findForward("success");
}
Set<String> roles = new HashSet<String>();
for (UserAuthority a: user.getAuthorities())
roles.add(a.getRole());
switch (roles.size()) {
case 0:
return mapping.findForward("norole");
case 1:
return mapping.findForward("getDefaultAcadSession");
default:
return mapping.findForward("getUserSelectedRole");
}
}
private UserAuthority setupAuthorities(HttpServletRequest request, UserContext user) {
WebTable.setOrder(sessionContext,"roleLists.ord",request.getParameter("ord"), -2);
Set<String> roles = new HashSet<String>();
for (UserAuthority authority: user.getAuthorities())
roles.add(authority.getRole());
WebTable table = new WebTable(4,"Select " + (roles.size() > 1 ? "User Role & " : "") + "Academic Session",
"selectPrimaryRole.do?list=Y&ord=%%",
new String[] { "User Role", "Academic Session", "Academic Initiative", "Academic Session Status" },
new String[] { "left", "left", "left", "left"},
new boolean[] { true, true, true, true});
int nrLines = 0;
UserAuthority firstAuthority = null;
for (UserAuthority authority: user.getAuthorities()) {
Session session = (authority.getAcademicSession() == null ? null : SessionDAO.getInstance().get((Long)authority.getAcademicSession().getQualifierId()));
if (session == null) continue;
String onClick =
"onClick=\"roleListForm.authority.value='" + authority.getAuthority() + "';roleListForm.submit();\"";
String bgColor = (authority.equals(user.getCurrentAuthority()) ? "rgb(168,187,225)" : null);
table.addLine(
onClick,
new String[] {
authority.getLabel(),
session.getAcademicYear()+" "+session.getAcademicTerm(),
session.getAcademicInitiative(),
(session.getStatusType()==null?"":session.getStatusType().getLabel())},
new Comparable[] {
new MultiComparable(authority.toString(), session.getSessionBeginDateTime(), session.getAcademicInitiative()),
new MultiComparable(session.getSessionBeginDateTime(), session.getAcademicInitiative(), authority.toString()),
new MultiComparable(session.getAcademicInitiative(), session.getSessionBeginDateTime(), authority.toString()),
new MultiComparable(session.getStatusType()==null ? -1 : session.getStatusType().getOrd(), session.getAcademicInitiative(), session.getSessionBeginDateTime(), authority.toString())
}
).setBgColor(bgColor);
if (firstAuthority == null) firstAuthority = authority;
nrLines++;
}
if (user.getCurrentAuthority() == null && nrLines == 0)
table.addLine(new String[] {"<i><font color='red'>No user role and/or academic session associated with the user " + (user.getName() == null ? user.getUsername() : user.getName()) + ".</font></i>",null,null,null}, null);
if (nrLines == 1 && firstAuthority != null)
user.setCurrentAuthority(firstAuthority);
request.setAttribute(Roles.USER_ROLES_ATTR_NAME, table.printTable(WebTable.getOrder(sessionContext,"roleLists.ord")));
return user.getCurrentAuthority();
}
}
| JavaSource/org/unitime/timetable/action/RoleListAction.java | /*
* UniTime 3.2 (University Timetabling Application)
* Copyright (C) 2008 - 2010, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.action;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.unitime.commons.MultiComparable;
import org.unitime.commons.web.WebTable;
import org.unitime.timetable.form.RoleListForm;
import org.unitime.timetable.model.Roles;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.dao.SessionDAO;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.UserAuthority;
import org.unitime.timetable.security.UserContext;
/**
* MyEclipse Struts
* Creation date: 03-17-2005
*
* XDoclet definition:
* @struts:action path="/selectPrimaryRole" name="roleListForm" input="/selectPrimaryRole.jsp" scope="request" validate="true"
* @struts:action-forward name="success" path="/main.jsp" contextRelative="true"
* @struts:action-forward name="fail" path="/selectPrimaryRole.jsp" contextRelative="true"
*/
@Service("/selectPrimaryRole")
public class RoleListAction extends Action {
@Autowired SessionContext sessionContext;
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
RoleListForm roleListForm = (RoleListForm) form;
UserContext user = null;
try {
user = (UserContext)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} catch (Exception e) {}
if (user == null) return mapping.findForward("loginRequired");
if (user.getAuthorities().isEmpty()) return mapping.findForward("norole");
// Form submitted
if (roleListForm.getAuthority() != null) {
UserAuthority authority = user.getAuthority(roleListForm.getAuthority());
if (authority != null)
user.setCurrentAuthority(authority);
return mapping.findForward("success");
}
UserAuthority authority = setupAuthorities(request, user);
// Role/session list not requested -- try assign default role/session first
if (!"Y".equals(request.getParameter("list")) && authority != null) {
user.setCurrentAuthority(authority);
return mapping.findForward("success");
}
Set<String> roles = new HashSet<String>();
for (UserAuthority a: user.getAuthorities())
roles.add(a.getRole());
switch (roles.size()) {
case 0:
return mapping.findForward("norole");
case 1:
return mapping.findForward("getDefaultAcadSession");
default:
return mapping.findForward("getUserSelectedRole");
}
}
private UserAuthority setupAuthorities(HttpServletRequest request, UserContext user) {
WebTable.setOrder(sessionContext,"roleLists.ord",request.getParameter("ord"), -2);
Set<String> roles = new HashSet<String>();
for (UserAuthority authority: user.getAuthorities())
roles.add(authority.getRole());
WebTable table = new WebTable(4,"Select " + (roles.size() > 1 ? "User Role & " : "") + "Academic Session",
"selectPrimaryRole.do?list=Y&ord=%%",
new String[] { "User Role", "Academic Session", "Academic Initiative", "Academic Session Status" },
new String[] { "left", "left", "left", "left"},
new boolean[] { true, true, true, true});
int nrLines = 0;
UserAuthority firstAuthority = null;
for (UserAuthority authority: user.getAuthorities()) {
Session session = (authority.getAcademicSession() == null ? null : SessionDAO.getInstance().get((Long)authority.getAcademicSession().getQualifierId()));
if (session == null) continue;
String onClick =
"onClick=\"roleListForm.authority.value='" + authority.getAuthority() + "';roleListForm.submit();\"";
String bgColor = (authority.equals(user.getCurrentAuthority()) ? "rgb(168,187,225)" : null);
table.addLine(
onClick,
new String[] {
authority.getLabel(),
session.getAcademicYear()+" "+session.getAcademicTerm(),
session.getAcademicInitiative(),
(session.getStatusType()==null?"":session.getStatusType().getLabel())},
new Comparable[] {
new MultiComparable(authority.toString(), session.getSessionBeginDateTime(), session.getAcademicInitiative()),
new MultiComparable(session.getSessionBeginDateTime(), session.getAcademicInitiative(), authority.toString()),
new MultiComparable(session.getAcademicInitiative(), session.getSessionBeginDateTime(), authority.toString()),
new MultiComparable(session.getStatusType()==null ? -1 : session.getStatusType().getOrd(), session.getAcademicInitiative(), session.getSessionBeginDateTime(), authority.toString())
}
).setBgColor(bgColor);
if (firstAuthority == null) firstAuthority = authority;
nrLines++;
}
if (user.getCurrentAuthority() == null && nrLines == 0)
table.addLine(new String[] {"<i><font color='red'>No user role and/or academic session associated with the user " + (user.getName() == null ? user.getUsername() : user.getName()) + ".</font></i>",null,null,null}, null);
if (nrLines == 1 && firstAuthority != null)
user.setCurrentAuthority(firstAuthority);
request.setAttribute(Roles.USER_ROLES_ATTR_NAME, table.printTable(WebTable.getOrder(sessionContext,"roleLists.ord")));
return user.getCurrentAuthority();
}
}
| Select Academic Session / Select User Role
- remove academic session specific (http session) attributes when a user role / academic session is changed
| JavaSource/org/unitime/timetable/action/RoleListAction.java | Select Academic Session / Select User Role - remove academic session specific (http session) attributes when a user role / academic session is changed | <ide><path>avaSource/org/unitime/timetable/action/RoleListAction.java
<ide> import org.springframework.stereotype.Service;
<ide> import org.unitime.commons.MultiComparable;
<ide> import org.unitime.commons.web.WebTable;
<add>import org.unitime.timetable.defaults.SessionAttribute;
<ide> import org.unitime.timetable.form.RoleListForm;
<ide> import org.unitime.timetable.model.Roles;
<ide> import org.unitime.timetable.model.Session;
<ide> // Form submitted
<ide> if (roleListForm.getAuthority() != null) {
<ide> UserAuthority authority = user.getAuthority(roleListForm.getAuthority());
<del> if (authority != null)
<add> if (authority != null) {
<ide> user.setCurrentAuthority(authority);
<add> for (SessionAttribute s: SessionAttribute.values())
<add> sessionContext.removeAttribute(s);
<add> }
<ide> return mapping.findForward("success");
<ide> }
<ide> |
|
Java | apache-2.0 | e365b607a46bf6e0381661d0370cf0e94f84957c | 0 | davidsoergel/phyloutils | package edu.berkeley.compbio.phyloutils;
import com.davidsoergel.dsutils.file.IntArrayReader;
import com.davidsoergel.trees.NoSuchNodeException;
import java.io.IOException;
/**
* Load a list of "known" nodes, eg the isolates. Then for each query sequence (eg from an environment), find the
* closest known node, and print the distance (along with whatever other stats are desired, e.g. subtree span).
*
* @author <a href="mailto:[email protected]">David Soergel</a>
* @version $Id$
*/
public class NearestNodeFinder
{
static HugenholtzTaxonomyService service = new HugenholtzTaxonomyService();
public static void main(String[] argv) throws IOException, NoSuchNodeException
{
//service.setGreengenesRawFilename(argv[0]);
service.setHugenholtzFilename(argv[0]);
//service.setSynonymService(NcbiTaxonomyClient.getInstance());
service.init();
int[] targetIds = IntArrayReader.read(argv[1]);
int[] queryIds = IntArrayReader.read(argv[2]);
for (int queryId : queryIds)
{
double best = Double.MAX_VALUE;
for (int targetId : targetIds)
{
double d = service.minDistanceBetween(queryId, targetId);
best = Math.min(best, d);
}
System.out.println(queryId + "\t" + best);
}
}
}
| src/main/java/edu/berkeley/compbio/phyloutils/NearestNodeFinder.java | package edu.berkeley.compbio.phyloutils;
import com.davidsoergel.dsutils.file.IntArrayReader;
import com.davidsoergel.trees.NoSuchNodeException;
import java.io.IOException;
/**
* Load a list of "known" nodes, eg the isolates. Then for each query sequence (eg from an environment), find the
* closest known node, and print the distance (along with whatever other stats are desired, e.g. subtree span).
*
* @author <a href="mailto:[email protected]">David Soergel</a>
* @version $Id$
*/
public class NearestNodeFinder
{
static HugenholtzTaxonomyService service = new HugenholtzTaxonomyService();
public static void main(String[] argv) throws IOException, NoSuchNodeException
{
//service.setGreengenesRawFilename(argv[0]);
service.setHugenholtzFilename(argv[0]);
//service.setSynonymService(NcbiTaxonomyClient.getInstance());
service.init();
int[] targetIds = IntArrayReader.read(argv[1]);
int[] queryIds = IntArrayReader.read(argv[2]);
for (int queryId : queryIds)
{
double best = Double.MAX_VALUE;
for (int targetId : targetIds)
{
double d = service.minDistanceBetween(queryId, targetId);
best = Math.min(best, d);
}
System.err.println(queryId + "\t" + best);
}
}
}
| aeouoeu
| src/main/java/edu/berkeley/compbio/phyloutils/NearestNodeFinder.java | aeouoeu | <ide><path>rc/main/java/edu/berkeley/compbio/phyloutils/NearestNodeFinder.java
<ide> double d = service.minDistanceBetween(queryId, targetId);
<ide> best = Math.min(best, d);
<ide> }
<del> System.err.println(queryId + "\t" + best);
<add> System.out.println(queryId + "\t" + best);
<ide> }
<ide> }
<ide> } |
|
Java | bsd-3-clause | 5b2db1781ec36b5004c30b75ae3deabd042283ca | 0 | exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent | // Copyright 2015-present 650 Industries. All rights reserved.
package versioned.host.exp.exponent.modules.api.av;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.net.Uri;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.SystemClock;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.NativeViewHierarchyManager;
import com.facebook.react.uimanager.UIBlock;
import com.facebook.react.uimanager.UIManagerModule;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import host.exp.exponent.utils.ExpFileUtils;
import host.exp.exponent.utils.ScopedContext;
import versioned.host.exp.exponent.modules.api.av.player.PlayerData;
import versioned.host.exp.exponent.modules.api.av.video.VideoTextureView;
import versioned.host.exp.exponent.modules.api.av.video.VideoView;
import versioned.host.exp.exponent.modules.api.av.video.VideoViewWrapper;
import static android.media.MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED;
public class AVModule extends ReactContextBaseJavaModule
implements LifecycleEventListener, AudioManager.OnAudioFocusChangeListener, MediaRecorder.OnInfoListener {
private static final String AUDIO_MODE_SHOULD_DUCK_KEY = "shouldDuckAndroid";
private static final String AUDIO_MODE_INTERRUPTION_MODE_KEY = "interruptionModeAndroid";
private static final String RECORDING_OPTIONS_KEY = "android";
private static final String RECORDING_OPTION_EXTENSION_KEY = "extension";
private static final String RECORDING_OPTION_OUTPUT_FORMAT_KEY = "outputFormat";
private static final String RECORDING_OPTION_AUDIO_ENCODER_KEY = "audioEncoder";
private static final String RECORDING_OPTION_SAMPLE_RATE_KEY = "sampleRate";
private static final String RECORDING_OPTION_NUMBER_OF_CHANNELS_KEY = "numberOfChannels";
private static final String RECORDING_OPTION_BIT_RATE_KEY = "bitRate";
private static final String RECORDING_OPTION_MAX_FILE_SIZE_KEY = "maxFileSize";
private enum AudioInterruptionMode {
DO_NOT_MIX,
DUCK_OTHERS,
}
public class AudioFocusNotAcquiredException extends Exception {
AudioFocusNotAcquiredException(final String message) {
super(message);
}
}
public final ScopedContext mScopedContext; // used by PlayerData
private final ReactApplicationContext mReactApplicationContext;
private boolean mEnabled = true;
private final AudioManager mAudioManager;
private final BroadcastReceiver mNoisyAudioStreamReceiver;
private boolean mAcquiredAudioFocus = false;
private boolean mAppIsPaused = false;
private AudioInterruptionMode mAudioInterruptionMode = AudioInterruptionMode.DUCK_OTHERS;
private boolean mShouldDuckAudio = true;
private boolean mIsDuckingAudio = false;
private int mSoundMapKeyCount = 0;
// There will never be many PlayerData objects in the map, so HashMap is most efficient.
private final Map<Integer, PlayerData> mSoundMap = new HashMap<>();
private final Set<AudioEventHandler> mVideoViewSet = new HashSet<>();
private MediaRecorder mAudioRecorder = null;
private String mAudioRecordingFilePath = null;
private long mAudioRecorderUptimeOfLastStartResume = 0L;
private long mAudioRecorderDurationAlreadyRecorded = 0L;
private boolean mAudioRecorderIsRecording = false;
private boolean mAudioRecorderIsPaused = false;
private Callback mAudioRecorderUnloadedCallback = null;
@Override
public String getName() {
return "ExponentAV";
}
public AVModule(final ReactApplicationContext reactContext, final ScopedContext scopedContext) {
super(reactContext);
mScopedContext = scopedContext;
mReactApplicationContext = reactContext;
mAudioManager = (AudioManager) mScopedContext.getSystemService(Context.AUDIO_SERVICE);
// Implemented because of the suggestion here:
// https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html
mNoisyAudioStreamReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
abandonAudioFocus();
}
}
};
mReactApplicationContext.registerReceiver(mNoisyAudioStreamReceiver,
new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
mReactApplicationContext.addLifecycleEventListener(this);
}
private void sendEvent(String eventName, WritableMap params) {
mReactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
// LifecycleEventListener
@Override
public void onHostResume() {
if (mAppIsPaused) {
mAppIsPaused = false;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.onResume();
}
}
}
@Override
public void onHostPause() {
if (!mAppIsPaused) {
mAppIsPaused = true;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.onPause();
}
abandonAudioFocus();
}
}
@Override
public void onHostDestroy() {
mReactApplicationContext.unregisterReceiver(mNoisyAudioStreamReceiver);
for (final Integer key : mSoundMap.keySet()) {
removeSoundForKey(key);
}
removeAudioRecorder();
abandonAudioFocus();
}
// Global audio state control API
public void registerVideoViewForAudioLifecycle(final AudioEventHandler videoView) {
mVideoViewSet.add(videoView);
}
public void unregisterVideoViewForAudioLifecycle(final AudioEventHandler videoView) {
mVideoViewSet.remove(videoView);
}
private Set<AudioEventHandler> getAllRegisteredAudioEventHandlers() {
final Set<AudioEventHandler> set = new HashSet<>();
set.addAll(mVideoViewSet);
set.addAll(mSoundMap.values());
return set;
}
@Override // AudioManager.OnAudioFocusChangeListener
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
if (mShouldDuckAudio) {
mIsDuckingAudio = true;
mAcquiredAudioFocus = true;
updateDuckStatusForAllPlayersPlaying();
break;
} // Otherwise, it is treated as AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS:
mIsDuckingAudio = false;
mAcquiredAudioFocus = false;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.handleAudioFocusInterruptionBegan();
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
mIsDuckingAudio = false;
mAcquiredAudioFocus = true;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.handleAudioFocusGained();
}
break;
}
}
public void acquireAudioFocus() throws AudioFocusNotAcquiredException {
if (!mEnabled) {
throw new AudioFocusNotAcquiredException("Expo Audio is disabled, so audio focus could not be acquired.");
}
if (mAppIsPaused) {
throw new AudioFocusNotAcquiredException("This experience is currently in the background, so audio focus could not be acquired.");
}
if (mAcquiredAudioFocus) {
return;
}
final int audioFocusRequest = mAudioInterruptionMode == AudioInterruptionMode.DO_NOT_MIX
? AudioManager.AUDIOFOCUS_GAIN : AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, audioFocusRequest);
mAcquiredAudioFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
if (!mAcquiredAudioFocus) {
throw new AudioFocusNotAcquiredException("Audio focus could not be acquired from the OS at this time.");
}
}
private void abandonAudioFocus() {
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
if (handler.requiresAudioFocus()) {
handler.pauseImmediately();
}
}
mAcquiredAudioFocus = false;
mAudioManager.abandonAudioFocus(this);
}
public void abandonAudioFocusIfUnused() { // used by PlayerData
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
if (handler.requiresAudioFocus()) {
return;
}
}
abandonAudioFocus();
}
public float getVolumeForDuckAndFocus(final boolean isMuted, final float volume) {
return (!mAcquiredAudioFocus || isMuted) ? 0f : mIsDuckingAudio ? volume / 2f : volume;
}
private void updateDuckStatusForAllPlayersPlaying() {
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.updateVolumeMuteAndDuck();
}
}
@ReactMethod
public void setAudioIsEnabled(final Boolean value, final Promise promise) {
mEnabled = value;
if (!value) {
abandonAudioFocus();
}
promise.resolve(null);
}
@ReactMethod
public void setAudioMode(final ReadableMap map, final Promise promise) {
mShouldDuckAudio = map.getBoolean(AUDIO_MODE_SHOULD_DUCK_KEY);
if (!mShouldDuckAudio) {
mIsDuckingAudio = false;
updateDuckStatusForAllPlayersPlaying();
}
final int interruptionModeInt = map.getInt(AUDIO_MODE_INTERRUPTION_MODE_KEY);
switch (interruptionModeInt) {
case 1:
mAudioInterruptionMode = AudioInterruptionMode.DO_NOT_MIX;
case 2:
default:
mAudioInterruptionMode = AudioInterruptionMode.DUCK_OTHERS;
}
promise.resolve(null);
}
// Unified playback API - Audio
// Rejects the promise and returns null if the PlayerData is not found.
private PlayerData tryGetSoundForKey(final Integer key, final Promise promise) {
final PlayerData data = this.mSoundMap.get(key);
if (data == null && promise != null) {
promise.reject("E_AUDIO_NOPLAYER", "Player does not exist.");
}
return data;
}
private void removeSoundForKey(final Integer key) {
final PlayerData data = mSoundMap.remove(key);
if (data != null) {
data.release();
abandonAudioFocusIfUnused();
}
}
@ReactMethod
public void loadForSound(final ReadableMap source, final ReadableMap status, final Callback loadSuccess, final Callback loadError) {
final int key = mSoundMapKeyCount++;
final PlayerData data = PlayerData.createUnloadedPlayerData(this, source, status);
data.setErrorListener(new PlayerData.ErrorListener() {
@Override
public void onError(final String error) {
removeSoundForKey(key);
}
});
mSoundMap.put(key, data);
data.load(status, new PlayerData.LoadCompletionListener() {
@Override
public void onLoadSuccess(final WritableMap status) {
loadSuccess.invoke(key, status);
}
@Override
public void onLoadError(final String error) {
mSoundMap.remove(key);
loadError.invoke(error);
}
});
data.setStatusUpdateListener(new PlayerData.StatusUpdateListener() {
@Override
public void onStatusUpdate(final WritableMap status) {
WritableMap payload = Arguments.createMap();
payload.putInt("key", key);
payload.putMap("status", status);
sendEvent("didUpdatePlaybackStatus", payload);
}
});
}
@ReactMethod
public void unloadForSound(final Integer key, final Promise promise) {
if (tryGetSoundForKey(key, promise) != null) {
removeSoundForKey(key);
promise.resolve(PlayerData.getUnloadedStatus());
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void setStatusForSound(final Integer key, final ReadableMap status, final Promise promise) {
final PlayerData data = tryGetSoundForKey(key, promise);
if (data != null) {
data.setStatus(status, promise);
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void replaySound(final Integer key, final ReadableMap status, final Promise promise) {
final PlayerData data = tryGetSoundForKey(key, promise);
if (data != null) {
data.setStatus(status, promise);
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void getStatusForSound(final Integer key, final Promise promise) {
final PlayerData data = tryGetSoundForKey(key, promise);
if (data != null) {
promise.resolve(data.getStatus());
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void setErrorCallbackForSound(final Integer key, final Callback callback) {
final PlayerData data = tryGetSoundForKey(key, null);
if (data != null) {
data.setErrorListener(new PlayerData.ErrorListener() {
@Override
public void onError(final String error) {
data.setErrorListener(null); // Can only use callback once.
removeSoundForKey(key);
callback.invoke(error);
}
});
}
}
// Unified playback API - Video
private interface VideoViewCallback {
void runWithVideoView(final VideoView videoView);
}
// Rejects the promise if the VideoView is not found, otherwise executes the callback.
private void tryRunWithVideoView(final Integer tag, final VideoViewCallback callback, final Promise promise) {
mReactApplicationContext.getNativeModule(UIManagerModule.class).addUIBlock(new UIBlock() {
@Override
public void execute(final NativeViewHierarchyManager nativeViewHierarchyManager) {
final VideoViewWrapper videoViewWrapper;
try {
final View view = nativeViewHierarchyManager.resolveView(tag);
if (!(view instanceof VideoViewWrapper)) {
throw new Exception();
}
videoViewWrapper = (VideoViewWrapper) view;
} catch (final Throwable e) {
promise.reject("E_VIDEO_TAGINCORRECT", "Invalid view returned from registry.");
return;
}
callback.runWithVideoView(videoViewWrapper.getVideoViewInstance());
}
});
}
@ReactMethod
public void loadForVideo(final Integer tag, final ReadableMap source, final ReadableMap status, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setSource(source, status, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void unloadForVideo(final Integer tag, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setSource(null, null, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void setStatusForVideo(final Integer tag, final ReadableMap status, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setStatus(status, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void replayVideo(final Integer tag, final ReadableMap status, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setStatus(status, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void getStatusForVideo(final Integer tag, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
promise.resolve(videoView.getStatus());
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
// Note that setStatusUpdateCallback happens in the JS for video via onStatusUpdate
// Recording API
private boolean isMissingAudioRecordingPermissions() {
return Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED;
}
// Rejects the promise and returns false if the MediaRecorder is not found.
private boolean checkAudioRecorderExistsOrReject(final Promise promise) {
if (mAudioRecorder == null && promise != null) {
promise.reject("E_AUDIO_NORECORDER", "Recorder does not exist.");
}
return mAudioRecorder != null;
}
private long getAudioRecorderDurationMillis() {
if (mAudioRecorder == null) {
return 0L;
}
long duration = mAudioRecorderDurationAlreadyRecorded;
if (mAudioRecorderIsRecording && mAudioRecorderUptimeOfLastStartResume > 0) {
duration += SystemClock.uptimeMillis() - mAudioRecorderUptimeOfLastStartResume;
}
return duration;
}
private WritableMap getAudioRecorderStatus() {
final WritableMap map = Arguments.createMap();
if (mAudioRecorder != null) {
map.putBoolean("canRecord", true);
map.putBoolean("isRecording", mAudioRecorderIsRecording);
map.putInt("durationMillis", (int) getAudioRecorderDurationMillis());
}
return map;
}
private void removeAudioRecorder() {
if (mAudioRecorder != null) {
try {
mAudioRecorder.stop();
} catch (final RuntimeException e) {
// Do nothing-- this just means that the recorder is already stopped,
// or was stopped immediately after starting.
}
mAudioRecorder.release();
mAudioRecorder = null;
}
mAudioRecordingFilePath = null;
mAudioRecorderIsRecording = false;
mAudioRecorderIsPaused = false;
mAudioRecorderDurationAlreadyRecorded = 0L;
mAudioRecorderUptimeOfLastStartResume = 0L;
}
@Override
public void onInfo(final MediaRecorder mr, final int what, final int extra) {
switch (what) {
case MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED:
final WritableMap finalStatus = getAudioRecorderStatus();
removeAudioRecorder();
if (mAudioRecorderUnloadedCallback != null) {
final Callback callback = mAudioRecorderUnloadedCallback;
mAudioRecorderUnloadedCallback = null;
callback.invoke(finalStatus);
}
default:
// Do nothing
}
}
@ReactMethod
public void setUnloadedCallbackForAndroidRecording(final Callback callback) {
// In JS, this is called before prepareAudioRecorder to make sure it is
// available immediately upon recording. So, we don't check mAudioRecorder != null.
mAudioRecorderUnloadedCallback = callback;
}
@ReactMethod
public void prepareAudioRecorder(final ReadableMap options, final Promise promise) {
if (isMissingAudioRecordingPermissions()) {
promise.reject("E_MISSING_PERMISSION", "Missing audio recording permissions.");
return;
}
removeAudioRecorder();
final ReadableMap androidOptions = options.getMap(RECORDING_OPTIONS_KEY);
final String filename = "recording-" + UUID.randomUUID().toString()
+ androidOptions.getString(RECORDING_OPTION_EXTENSION_KEY);
try {
final File directory = new File(mScopedContext.getCacheDir() + File.separator + "Audio");
ExpFileUtils.ensureDirExists(directory);
mAudioRecordingFilePath = directory + File.separator + filename;
} catch (final IOException e) {
// This only occurs in the case that the scoped path is not in this experience's scope,
// which is never true.
}
mAudioRecorder = new MediaRecorder();
mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mAudioRecorder.setOutputFormat(androidOptions.getInt(RECORDING_OPTION_OUTPUT_FORMAT_KEY));
mAudioRecorder.setAudioEncoder(androidOptions.getInt(RECORDING_OPTION_AUDIO_ENCODER_KEY));
if (androidOptions.hasKey(RECORDING_OPTION_SAMPLE_RATE_KEY)) {
mAudioRecorder.setAudioSamplingRate(androidOptions.getInt(RECORDING_OPTION_SAMPLE_RATE_KEY));
}
if (androidOptions.hasKey(RECORDING_OPTION_NUMBER_OF_CHANNELS_KEY)) {
mAudioRecorder.setAudioChannels(androidOptions.getInt(RECORDING_OPTION_NUMBER_OF_CHANNELS_KEY));
}
if (androidOptions.hasKey(RECORDING_OPTION_BIT_RATE_KEY)) {
mAudioRecorder.setAudioEncodingBitRate(androidOptions.getInt(RECORDING_OPTION_BIT_RATE_KEY));
}
mAudioRecorder.setOutputFile(mAudioRecordingFilePath);
if (androidOptions.hasKey(RECORDING_OPTION_MAX_FILE_SIZE_KEY)) {
mAudioRecorder.setMaxFileSize(androidOptions.getInt(RECORDING_OPTION_MAX_FILE_SIZE_KEY));
mAudioRecorder.setOnInfoListener(this);
}
try {
mAudioRecorder.prepare();
} catch (final Exception e) {
promise.reject("E_AUDIO_RECORDERNOTCREATED", "Prepare encountered an error: recorder not prepared", e);
removeAudioRecorder();
return;
}
final WritableMap map = Arguments.createMap();
map.putString("uri", Uri.fromFile(new File(mAudioRecordingFilePath)).toString());
map.putMap("status", getAudioRecorderStatus());
promise.resolve(map);
}
@ReactMethod
public void startAudioRecording(final Promise promise) {
if (isMissingAudioRecordingPermissions()) {
promise.reject("E_MISSING_PERMISSION", "Missing audio recording permissions.");
return;
}
if (checkAudioRecorderExistsOrReject(promise)) {
try {
if (mAudioRecorderIsPaused && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mAudioRecorder.resume();
} else {
mAudioRecorder.start();
}
} catch (final IllegalStateException e) {
promise.reject("E_AUDIO_RECORDING", "Start encountered an error: recording not started", e);
return;
}
mAudioRecorderUptimeOfLastStartResume = SystemClock.uptimeMillis();
mAudioRecorderIsRecording = true;
mAudioRecorderIsPaused = false;
promise.resolve(getAudioRecorderStatus());
}
}
@ReactMethod
public void pauseAudioRecording(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
promise.reject("E_AUDIO_VERSIONINCOMPATIBLE", "Pausing an audio recording is unsupported on" +
" Android devices running SDK < 24.");
} else {
try {
mAudioRecorder.pause();
} catch (final IllegalStateException e) {
promise.reject("E_AUDIO_RECORDINGPAUSE", "Pause encountered an error: recording not paused", e);
return;
}
mAudioRecorderDurationAlreadyRecorded = getAudioRecorderDurationMillis();
mAudioRecorderIsRecording = false;
mAudioRecorderIsPaused = true;
promise.resolve(getAudioRecorderStatus());
}
}
}
@ReactMethod
public void stopAudioRecording(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
try {
mAudioRecorder.stop();
} catch (final RuntimeException e) {
promise.reject("E_AUDIO_RECORDINGSTOP", "Stop encountered an error: recording not stopped", e);
return;
}
mAudioRecorderDurationAlreadyRecorded = getAudioRecorderDurationMillis();
mAudioRecorderIsRecording = false;
mAudioRecorderIsPaused = false;
promise.resolve(getAudioRecorderStatus());
}
}
@ReactMethod
public void getAudioRecordingStatus(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
promise.resolve(getAudioRecorderStatus());
}
}
@ReactMethod
public void unloadAudioRecorder(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
removeAudioRecorder();
promise.resolve(null);
}
}
}
| android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/av/AVModule.java | // Copyright 2015-present 650 Industries. All rights reserved.
package versioned.host.exp.exponent.modules.api.av;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.view.View;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.SystemClock;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.NativeViewHierarchyManager;
import com.facebook.react.uimanager.UIBlock;
import com.facebook.react.uimanager.UIManagerModule;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import host.exp.exponent.utils.ExpFileUtils;
import host.exp.exponent.utils.ScopedContext;
import versioned.host.exp.exponent.modules.api.av.player.PlayerData;
import versioned.host.exp.exponent.modules.api.av.video.VideoTextureView;
import versioned.host.exp.exponent.modules.api.av.video.VideoView;
import versioned.host.exp.exponent.modules.api.av.video.VideoViewWrapper;
import static android.media.MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED;
public class AVModule extends ReactContextBaseJavaModule
implements LifecycleEventListener, AudioManager.OnAudioFocusChangeListener, MediaRecorder.OnInfoListener {
private static final String AUDIO_MODE_SHOULD_DUCK_KEY = "shouldDuckAndroid";
private static final String AUDIO_MODE_INTERRUPTION_MODE_KEY = "interruptionModeAndroid";
private static final String RECORDING_OPTIONS_KEY = "android";
private static final String RECORDING_OPTION_EXTENSION_KEY = "extension";
private static final String RECORDING_OPTION_OUTPUT_FORMAT_KEY = "outputFormat";
private static final String RECORDING_OPTION_AUDIO_ENCODER_KEY = "audioEncoder";
private static final String RECORDING_OPTION_SAMPLE_RATE_KEY = "sampleRate";
private static final String RECORDING_OPTION_NUMBER_OF_CHANNELS_KEY = "numberOfChannels";
private static final String RECORDING_OPTION_BIT_RATE_KEY = "bitRate";
private static final String RECORDING_OPTION_MAX_FILE_SIZE_KEY = "maxFileSize";
private enum AudioInterruptionMode {
DO_NOT_MIX,
DUCK_OTHERS,
}
public class AudioFocusNotAcquiredException extends Exception {
AudioFocusNotAcquiredException(final String message) {
super(message);
}
}
public final ScopedContext mScopedContext; // used by PlayerData
private final ReactApplicationContext mReactApplicationContext;
private boolean mEnabled = true;
private final AudioManager mAudioManager;
private final BroadcastReceiver mNoisyAudioStreamReceiver;
private boolean mAcquiredAudioFocus = false;
private boolean mAppIsPaused = false;
private AudioInterruptionMode mAudioInterruptionMode = AudioInterruptionMode.DUCK_OTHERS;
private boolean mShouldDuckAudio = true;
private boolean mIsDuckingAudio = false;
private int mSoundMapKeyCount = 0;
// There will never be many PlayerData objects in the map, so HashMap is most efficient.
private final Map<Integer, PlayerData> mSoundMap = new HashMap<>();
private final Set<AudioEventHandler> mVideoViewSet = new HashSet<>();
private MediaRecorder mAudioRecorder = null;
private String mAudioRecordingFilePath = null;
private long mAudioRecorderUptimeOfLastStartResume = 0L;
private long mAudioRecorderDurationAlreadyRecorded = 0L;
private boolean mAudioRecorderIsRecording = false;
private boolean mAudioRecorderIsPaused = false;
private Callback mAudioRecorderUnloadedCallback = null;
@Override
public String getName() {
return "ExponentAV";
}
public AVModule(final ReactApplicationContext reactContext, final ScopedContext scopedContext) {
super(reactContext);
mScopedContext = scopedContext;
mReactApplicationContext = reactContext;
mAudioManager = (AudioManager) mScopedContext.getSystemService(Context.AUDIO_SERVICE);
// Implemented because of the suggestion here:
// https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html
mNoisyAudioStreamReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
abandonAudioFocus();
}
}
};
mReactApplicationContext.registerReceiver(mNoisyAudioStreamReceiver,
new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
mReactApplicationContext.addLifecycleEventListener(this);
}
private void sendEvent(String eventName, WritableMap params) {
mReactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
// LifecycleEventListener
@Override
public void onHostResume() {
if (mAppIsPaused) {
mAppIsPaused = false;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.onResume();
}
}
}
@Override
public void onHostPause() {
if (!mAppIsPaused) {
mAppIsPaused = true;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.onPause();
}
abandonAudioFocus();
}
}
@Override
public void onHostDestroy() {
mReactApplicationContext.unregisterReceiver(mNoisyAudioStreamReceiver);
for (final Integer key : mSoundMap.keySet()) {
removeSoundForKey(key);
}
removeAudioRecorder();
abandonAudioFocus();
}
// Global audio state control API
public void registerVideoViewForAudioLifecycle(final AudioEventHandler videoView) {
mVideoViewSet.add(videoView);
}
public void unregisterVideoViewForAudioLifecycle(final AudioEventHandler videoView) {
mVideoViewSet.remove(videoView);
}
private Set<AudioEventHandler> getAllRegisteredAudioEventHandlers() {
final Set<AudioEventHandler> set = new HashSet<>();
set.addAll(mVideoViewSet);
set.addAll(mSoundMap.values());
return set;
}
@Override // AudioManager.OnAudioFocusChangeListener
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
if (mShouldDuckAudio) {
mIsDuckingAudio = true;
mAcquiredAudioFocus = true;
updateDuckStatusForAllPlayersPlaying();
break;
} // Otherwise, it is treated as AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS:
mIsDuckingAudio = false;
mAcquiredAudioFocus = false;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.handleAudioFocusInterruptionBegan();
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
mIsDuckingAudio = false;
mAcquiredAudioFocus = true;
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.handleAudioFocusGained();
}
break;
}
}
public void acquireAudioFocus() throws AudioFocusNotAcquiredException {
if (!mEnabled) {
throw new AudioFocusNotAcquiredException("Expo Audio is disabled, so audio focus could not be acquired.");
}
if (mAppIsPaused) {
throw new AudioFocusNotAcquiredException("This experience is currently in the background, so audio focus could not be acquired.");
}
if (mAcquiredAudioFocus) {
return;
}
final int audioFocusRequest = mAudioInterruptionMode == AudioInterruptionMode.DO_NOT_MIX
? AudioManager.AUDIOFOCUS_GAIN : AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, audioFocusRequest);
mAcquiredAudioFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
if (!mAcquiredAudioFocus) {
throw new AudioFocusNotAcquiredException("Audio focus could not be acquired from the OS at this time.");
}
}
private void abandonAudioFocus() {
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
if (handler.requiresAudioFocus()) {
handler.pauseImmediately();
}
}
mAcquiredAudioFocus = false;
mAudioManager.abandonAudioFocus(this);
}
public void abandonAudioFocusIfUnused() { // used by PlayerData
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
if (handler.requiresAudioFocus()) {
return;
}
}
abandonAudioFocus();
}
public float getVolumeForDuckAndFocus(final boolean isMuted, final float volume) {
return (!mAcquiredAudioFocus || isMuted) ? 0f : mIsDuckingAudio ? volume / 2f : volume;
}
private void updateDuckStatusForAllPlayersPlaying() {
for (final AudioEventHandler handler : getAllRegisteredAudioEventHandlers()) {
handler.updateVolumeMuteAndDuck();
}
}
@ReactMethod
public void setAudioIsEnabled(final Boolean value, final Promise promise) {
mEnabled = value;
if (!value) {
abandonAudioFocus();
}
promise.resolve(null);
}
@ReactMethod
public void setAudioMode(final ReadableMap map, final Promise promise) {
mShouldDuckAudio = map.getBoolean(AUDIO_MODE_SHOULD_DUCK_KEY);
if (!mShouldDuckAudio) {
mIsDuckingAudio = false;
updateDuckStatusForAllPlayersPlaying();
}
final int interruptionModeInt = map.getInt(AUDIO_MODE_INTERRUPTION_MODE_KEY);
switch (interruptionModeInt) {
case 1:
mAudioInterruptionMode = AudioInterruptionMode.DO_NOT_MIX;
case 2:
default:
mAudioInterruptionMode = AudioInterruptionMode.DUCK_OTHERS;
}
promise.resolve(null);
}
// Unified playback API - Audio
// Rejects the promise and returns null if the PlayerData is not found.
private PlayerData tryGetSoundForKey(final Integer key, final Promise promise) {
final PlayerData data = this.mSoundMap.get(key);
if (data == null && promise != null) {
promise.reject("E_AUDIO_NOPLAYER", "Player does not exist.");
}
return data;
}
private void removeSoundForKey(final Integer key) {
final PlayerData data = mSoundMap.remove(key);
if (data != null) {
data.release();
abandonAudioFocusIfUnused();
}
}
@ReactMethod
public void loadForSound(final ReadableMap source, final ReadableMap status, final Callback loadSuccess, final Callback loadError) {
final int key = mSoundMapKeyCount++;
final PlayerData data = PlayerData.createUnloadedPlayerData(this, source, status);
data.setErrorListener(new PlayerData.ErrorListener() {
@Override
public void onError(final String error) {
removeSoundForKey(key);
}
});
mSoundMap.put(key, data);
data.load(status, new PlayerData.LoadCompletionListener() {
@Override
public void onLoadSuccess(final WritableMap status) {
loadSuccess.invoke(key, status);
}
@Override
public void onLoadError(final String error) {
mSoundMap.remove(key);
loadError.invoke(error);
}
});
data.setStatusUpdateListener(new PlayerData.StatusUpdateListener() {
@Override
public void onStatusUpdate(final WritableMap status) {
WritableMap payload = Arguments.createMap();
payload.putInt("key", key);
payload.putMap("status", status);
sendEvent("didUpdatePlaybackStatus", payload);
}
});
}
@ReactMethod
public void unloadForSound(final Integer key, final Promise promise) {
if (tryGetSoundForKey(key, promise) != null) {
removeSoundForKey(key);
promise.resolve(PlayerData.getUnloadedStatus());
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void setStatusForSound(final Integer key, final ReadableMap status, final Promise promise) {
final PlayerData data = tryGetSoundForKey(key, promise);
if (data != null) {
data.setStatus(status, promise);
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void replaySound(final Integer key, final ReadableMap status, final Promise promise) {
final PlayerData data = tryGetSoundForKey(key, promise);
if (data != null) {
data.setStatus(status, promise);
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void getStatusForSound(final Integer key, final Promise promise) {
final PlayerData data = tryGetSoundForKey(key, promise);
if (data != null) {
promise.resolve(data.getStatus());
} // Otherwise, tryGetSoundForKey has already rejected the promise.
}
@ReactMethod
public void setErrorCallbackForSound(final Integer key, final Callback callback) {
final PlayerData data = tryGetSoundForKey(key, null);
if (data != null) {
data.setErrorListener(new PlayerData.ErrorListener() {
@Override
public void onError(final String error) {
data.setErrorListener(null); // Can only use callback once.
removeSoundForKey(key);
callback.invoke(error);
}
});
}
}
// Unified playback API - Video
private interface VideoViewCallback {
void runWithVideoView(final VideoView videoView);
}
// Rejects the promise if the VideoView is not found, otherwise executes the callback.
private void tryRunWithVideoView(final Integer tag, final VideoViewCallback callback, final Promise promise) {
mReactApplicationContext.getNativeModule(UIManagerModule.class).addUIBlock(new UIBlock() {
@Override
public void execute(final NativeViewHierarchyManager nativeViewHierarchyManager) {
final VideoViewWrapper videoViewWrapper;
try {
final View view = nativeViewHierarchyManager.resolveView(tag);
if (!(view instanceof VideoViewWrapper)) {
throw new Exception();
}
videoViewWrapper = (VideoViewWrapper) view;
} catch (final Throwable e) {
promise.reject("E_VIDEO_TAGINCORRECT", "Invalid view returned from registry.");
return;
}
callback.runWithVideoView(videoViewWrapper.getVideoViewInstance());
}
});
}
@ReactMethod
public void loadForVideo(final Integer tag, final ReadableMap source, final ReadableMap status, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setSource(source, status, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void unloadForVideo(final Integer tag, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setSource(null, null, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void setStatusForVideo(final Integer tag, final ReadableMap status, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setStatus(status, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void replayVideo(final Integer tag, final ReadableMap status, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
videoView.setStatus(status, promise);
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
@ReactMethod
public void getStatusForVideo(final Integer tag, final Promise promise) {
tryRunWithVideoView(tag, new VideoViewCallback() {
@Override
public void runWithVideoView(final VideoView videoView) {
promise.resolve(videoView.getStatus());
}
}, promise); // Otherwise, tryRunWithVideoView has already rejected the promise.
}
// Note that setStatusUpdateCallback happens in the JS for video via onStatusUpdate
// Recording API
private boolean isMissingAudioRecordingPermissions() {
return Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED;
}
// Rejects the promise and returns false if the MediaRecorder is not found.
private boolean checkAudioRecorderExistsOrReject(final Promise promise) {
if (mAudioRecorder == null && promise != null) {
promise.reject("E_AUDIO_NORECORDER", "Recorder does not exist.");
}
return mAudioRecorder != null;
}
private long getAudioRecorderDurationMillis() {
if (mAudioRecorder == null) {
return 0L;
}
long duration = mAudioRecorderDurationAlreadyRecorded;
if (mAudioRecorderIsRecording && mAudioRecorderUptimeOfLastStartResume > 0) {
duration += SystemClock.uptimeMillis() - mAudioRecorderUptimeOfLastStartResume;
}
return duration;
}
private WritableMap getAudioRecorderStatus() {
final WritableMap map = Arguments.createMap();
if (mAudioRecorder != null) {
map.putBoolean("canRecord", true);
map.putBoolean("isRecording", mAudioRecorderIsRecording);
map.putInt("durationMillis", (int) getAudioRecorderDurationMillis());
}
return map;
}
private void removeAudioRecorder() {
if (mAudioRecorder != null) {
try {
mAudioRecorder.stop();
} catch (final RuntimeException e) {
// Do nothing-- this just means that the recorder is already stopped,
// or was stopped immediately after starting.
}
mAudioRecorder.release();
mAudioRecorder = null;
}
mAudioRecordingFilePath = null;
mAudioRecorderIsRecording = false;
mAudioRecorderIsPaused = false;
mAudioRecorderDurationAlreadyRecorded = 0L;
mAudioRecorderUptimeOfLastStartResume = 0L;
}
@Override
public void onInfo(final MediaRecorder mr, final int what, final int extra) {
switch (what) {
case MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED:
final WritableMap finalStatus = getAudioRecorderStatus();
removeAudioRecorder();
if (mAudioRecorderUnloadedCallback != null) {
final Callback callback = mAudioRecorderUnloadedCallback;
mAudioRecorderUnloadedCallback = null;
callback.invoke(finalStatus);
}
default:
// Do nothing
}
}
@ReactMethod
public void setUnloadedCallbackForAndroidRecording(final Callback callback) {
// In JS, this is called before prepareAudioRecorder to make sure it is
// available immediately upon recording. So, we don't check mAudioRecorder != null.
mAudioRecorderUnloadedCallback = callback;
}
@ReactMethod
public void prepareAudioRecorder(final ReadableMap options, final Promise promise) {
if (isMissingAudioRecordingPermissions()) {
promise.reject("E_MISSING_PERMISSION", "Missing audio recording permissions.");
return;
}
removeAudioRecorder();
final ReadableMap androidOptions = options.getMap(RECORDING_OPTIONS_KEY);
final String filename = "recording-" + UUID.randomUUID().toString()
+ androidOptions.getString(RECORDING_OPTION_EXTENSION_KEY);
try {
final File directory = new File(mScopedContext.getCacheDir() + File.separator + "Audio");
ExpFileUtils.ensureDirExists(directory);
mAudioRecordingFilePath = directory + File.separator + filename;
} catch (final IOException e) {
// This only occurs in the case that the scoped path is not in this experience's scope,
// which is never true.
}
mAudioRecorder = new MediaRecorder();
mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mAudioRecorder.setOutputFormat(androidOptions.getInt(RECORDING_OPTION_OUTPUT_FORMAT_KEY));
mAudioRecorder.setAudioEncoder(androidOptions.getInt(RECORDING_OPTION_AUDIO_ENCODER_KEY));
if (androidOptions.hasKey(RECORDING_OPTION_SAMPLE_RATE_KEY)) {
mAudioRecorder.setAudioSamplingRate(androidOptions.getInt(RECORDING_OPTION_SAMPLE_RATE_KEY));
}
if (androidOptions.hasKey(RECORDING_OPTION_NUMBER_OF_CHANNELS_KEY)) {
mAudioRecorder.setAudioChannels(androidOptions.getInt(RECORDING_OPTION_NUMBER_OF_CHANNELS_KEY));
}
if (androidOptions.hasKey(RECORDING_OPTION_BIT_RATE_KEY)) {
mAudioRecorder.setAudioEncodingBitRate(androidOptions.getInt(RECORDING_OPTION_BIT_RATE_KEY));
}
mAudioRecorder.setOutputFile(mAudioRecordingFilePath);
if (androidOptions.hasKey(RECORDING_OPTION_MAX_FILE_SIZE_KEY)) {
mAudioRecorder.setMaxFileSize(androidOptions.getInt(RECORDING_OPTION_MAX_FILE_SIZE_KEY));
mAudioRecorder.setOnInfoListener(this);
}
try {
mAudioRecorder.prepare();
} catch (final Exception e) {
promise.reject("E_AUDIO_RECORDERNOTCREATED", "Prepare encountered an error: recorder not prepared", e);
removeAudioRecorder();
return;
}
final WritableMap map = Arguments.createMap();
map.putString("uri", Uri.fromFile(new File(mAudioRecordingFilePath)).toString());
map.putMap("status", getAudioRecorderStatus());
promise.resolve(map);
}
@ReactMethod
public void startAudioRecording(final Promise promise) {
if (isMissingAudioRecordingPermissions()) {
promise.reject("E_MISSING_PERMISSION", "Missing audio recording permissions.");
return;
}
if (checkAudioRecorderExistsOrReject(promise)) {
try {
if (mAudioRecorderIsPaused && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mAudioRecorder.resume();
} else {
mAudioRecorder.start();
}
} catch (final IllegalStateException e) {
promise.reject("E_AUDIO_RECORDING", "Start encountered an error: recording not started", e);
return;
}
mAudioRecorderUptimeOfLastStartResume = SystemClock.uptimeMillis();
mAudioRecorderIsRecording = true;
mAudioRecorderIsPaused = false;
promise.resolve(getAudioRecorderStatus());
}
}
@ReactMethod
public void pauseAudioRecording(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
promise.reject("E_AUDIO_VERSIONINCOMPATIBLE", "Pausing an audio recording is unsupported on" +
" Android devices running SDK < 24.");
} else {
try {
mAudioRecorder.pause();
} catch (final IllegalStateException e) {
promise.reject("E_AUDIO_RECORDINGPAUSE", "Pause encountered an error: recording not paused", e);
return;
}
mAudioRecorderDurationAlreadyRecorded = getAudioRecorderDurationMillis();
mAudioRecorderIsRecording = false;
mAudioRecorderIsPaused = true;
promise.resolve(getAudioRecorderStatus());
}
}
}
@ReactMethod
public void stopAudioRecording(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
try {
mAudioRecorder.stop();
} catch (final RuntimeException e) {
promise.reject("E_AUDIO_RECORDINGSTOP", "Stop encountered an error: recording not stopped", e);
return;
}
mAudioRecorderDurationAlreadyRecorded = getAudioRecorderDurationMillis();
mAudioRecorderIsRecording = false;
mAudioRecorderIsPaused = false;
promise.resolve(getAudioRecorderStatus());
}
}
@ReactMethod
public void getAudioRecordingStatus(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
promise.resolve(getAudioRecorderStatus());
}
}
@ReactMethod
public void unloadAudioRecorder(final Promise promise) {
if (checkAudioRecorderExistsOrReject(promise)) {
removeAudioRecorder();
promise.resolve(null);
}
}
}
| Missing URI import
fbshipit-source-id: 2953de7
| android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/av/AVModule.java | Missing URI import | <ide><path>ndroid/expoview/src/main/java/versioned/host/exp/exponent/modules/api/av/AVModule.java
<ide> import android.os.Build;
<ide> import android.support.v4.content.ContextCompat;
<ide> import android.view.View;
<add>import android.net.Uri;
<ide>
<ide> import com.facebook.react.bridge.Arguments;
<ide> import com.facebook.react.bridge.Callback; |
|
JavaScript | mit | 18a596e63888456c0bd777a77240091ff66603c9 | 0 | pueue/range-shuffle | import Big from 'big-integer';
export class Shuffler {
constructor({ a, c, m }) {
[this.A, this.C, this.M] = [a, c, m];
}
lcg(before) {
const after = this.A.times(before).add(this.C).mod(this.M);
return after;
}
r_lcg(after) {
const inverse = this._extendedEuclidX(this.A, this.M);
let before = after.minus(this.C).times(inverse).mod(this.M);
if (before.compare(0) === -1)
before = before.add(this.M);
return before;
}
_makeDivisible(a, b) {
return a.divide(b).times(b);
}
_extendedEuclidX(a, b) {
if (b.compare(0) === 0)
return Big(1);
else
return this._extendedEuclidY(
b, a.minus(this._makeDivisible(a, b))
);
}
_extendedEuclidY(a, b) {
if (b.compare(0) === 0)
return Big(0);
else
return this._extendedEuclidX(
b, a.minus(this._makeDivisible(a, b))
).minus(this._extendedEuclidY(
b, a.minus(this._makeDivisible(a, b))
).times(a.divide(b)));
}
}
| src/index.js | import Big from 'big-integer';
export class Shuffler {
constructor({ a, c, m }) {
[this.A, this.C, this.M] = [a, c, m];
}
lcg(before) {
const after = this.A.times(before).add(this.C).mod(this.M);
return after;
}
r_lcg(after) {
const inverse = this._extendedEuclidX(this.A, this.M);
let before = after.minus(this.C).times(inverse).mod(this.M);
if (before.compare(0) === -1)
before = before.add(this.M);
return before;
}
_makeDivisible(a, b) {
return this._makeDivisible(a, b);
}
_extendedEuclidX(a, b) {
if (b.compare(0) === 0)
return Big(1);
else
return this._extendedEuclidY(
b, a.minus(this._makeDivisible(a, b))
);
}
_extendedEuclidY(a, b) {
if (b.compare(0) === 0)
return Big(0);
else
return this._extendedEuclidX(
b, a.minus(this._makeDivisible(a, b))
).minus(this._extendedEuclidY(
b, a.minus(this._makeDivisible(a, b))
).times(a.divide(b)));
}
}
| Fix recursive calling
| src/index.js | Fix recursive calling | <ide><path>rc/index.js
<ide> }
<ide>
<ide> _makeDivisible(a, b) {
<del> return this._makeDivisible(a, b);
<add> return a.divide(b).times(b);
<ide> }
<ide>
<ide> _extendedEuclidX(a, b) { |
|
JavaScript | mit | 7f76f5ad4e6ab769097e5088c677c5269fa95978 | 0 | nfroidure/TripStory,nfroidure/TripStory,nfroidure/hackthemobility,nfroidure/hackthemobility | 'use strict';
if(process.env.API_ANALYTICS_KEY) { // eslint-disable-line
var aac = require('@jbpionnier/api-analytics-client'); // eslint-disable-line
var analytics = require('@jbpionnier/api-analytics-client/express'); // eslint-disable-line
} // eslint-disable-line
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var express = require('express');
var initRoutes = require('./app/routes');
var Promise = require('bluebird');
var winston = require('winston');
var TokenService = require('sf-token');
var nodemailer = require('nodemailer');
var nodemailerMailgunTransport = require('nodemailer-mailgun-transport');
var Pusher = require('pusher');
var Twitter = require('twitter');
var initFacebookWorker = require('./workers/facebook/facebook.bin.js');
var initXeeWorker = require('./workers/xee/xee.bin.js');
var initPSAWorker = require('./workers/psa/psa.bin.js');
var initTwitterWorker = require('./workers/twitter/twitter.bin.js');
var initEmailWorker = require('./workers/email/email.bin.js');
var initPusherWorker = require('./workers/pusher/pusher.bin.js');
var context = {};
// Preparing services
context.env = process.env;
Promise.all([
MongoClient.connect(context.env.MONGODB_URL),
]).spread(function handleServerServices(db) {
// Services
context.time = Date.now.bind(Date);
context.db = db;
context.bus = {
consume: function busConsume(callback) {
process.on('bus-event', callback);
},
trigger: function busTrigger(event) {
process.emit('bus-event', event);
},
};
if(context.env.PUSHER_APP_ID) {
context.pusher = new Pusher({
appId: context.env.PUSHER_APP_ID,
key: context.env.PUSHER_KEY,
secret: context.env.PUSHER_SECRET,
cluster: context.env.PUSHER_CLUSTER,
encrypted: true,
});
}
if(context.env.TWITTER_ID) {
context.twitter = new Twitter({
consumer_key: process.env.TWITTER_ID,
consumer_secret: process.env.TWITTER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});
}
context.app = express();
context.createObjectId = ObjectId;
context.logger = new (winston.Logger)({
transports: [new (winston.transports.Console)({ level: 'silly' })],
});
context.tokens = new TokenService({
uniqueId: function createTokenUniqueId() {
return context.createObjectId().toString();
},
secret: context.env.TOKEN_SECRET,
time: context.time,
});
if(context.env.API_ANALYTICS_KEY) {
context.analyticsAgent = analytics({
apiKey: context.env.API_ANALYTICS_KEY,
uuidResolver: function agentUuidResolver(req) {
return req.user && req.user._id ? req.user._id.toString() : null;
},
});
}
if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {
context.sendMail = function initSendMail() {
var mailer = nodemailer.createTransport(
nodemailerMailgunTransport({
auth: {
api_key: context.env.MAILGUN_KEY,
domain: context.env.MAILGUN_DOMAIN,
},
})
);
return function sendEmail(contents) {
return new Promise(function(resolve, reject) {
mailer.sendMail(contents, function sendMailHandler(err, info) {
if(err) {
return reject(err);
}
resolve(info);
});
});
};
}();
}
context.protocol = context.env.PROTOCOL || 'http';
context.host = context.env.HOST || 'localhost';
context.domain = context.env.DOMAIN || '';
context.port = 'undefined' !== typeof context.env.PORT ?
parseInt(context.env.PORT, 10) :
3000;
context.base = context.protocol + '://' + (
context.domain ?
context.domain :
context.host + ':' + context.port
);
context.logger.debug('Env', context.env);
// Workers
initPSAWorker(context);
initFacebookWorker(context);
initTwitterWorker(context);
initXeeWorker(context);
if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {
initEmailWorker(context);
}
if(context.env.PUSHER_APP_ID) {
initPusherWorker(context);
}
// Routes
initRoutes(context);
// Starting the server
return new Promise(function handleServerPromise(resolve, reject) {
context.server = context.app.listen(context.port, function handleServerCb(err) {
if(err) {
return reject(err);
}
context.logger.debug(
'Server listening to \\o/ -> http://%s:%s - Pid: %s',
context.host, context.port, process.pid
);
resolve();
});
});
});
| backend/index.js | 'use strict';
if(process.env.API_ANALYTICS_KEY) { // eslint-disable-line
var aac = require('@jbpionnier/api-analytics-client'); // eslint-disable-line
var analytics = require('@jbpionnier/api-analytics-client/express'); // eslint-disable-line
} // eslint-disable-line
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var express = require('express');
var initRoutes = require('./app/routes');
var Promise = require('bluebird');
var winston = require('winston');
var TokenService = require('sf-token');
var nodemailer = require('nodemailer');
var nodemailerMailgunTransport = require('nodemailer-mailgun-transport');
var Pusher = require('pusher');
var Twitter = require('twitter');
var initFacebookWorker = require('./workers/facebook/facebook.bin.js');
var initXeeWorker = require('./workers/xee/xee.bin.js');
var initPSAWorker = require('./workers/psa/psa.bin.js');
var initTwitterWorker = require('./workers/twitter/twitter.bin.js');
var initEmailWorker = require('./workers/email/email.bin.js');
var initPusherWorker = require('./workers/pusher/pusher.bin.js');
var context = {};
// Preparing services
context.env = process.env;
Promise.all([
MongoClient.connect(context.env.MONGODB_URL),
]).spread(function handleServerServices(db) {
// Services
context.time = Date.now.bind(Date);
context.db = db;
context.bus = {
consume: function busConsume(callback) {
process.on('bus-event', callback);
},
trigger: function busTrigger(event) {
process.emit('bus-event', event);
},
};
if(context.env.PUSHER_APP_ID) {
context.pusher = new Pusher({
appId: context.env.PUSHER_APP_ID,
key: context.env.PUSHER_KEY,
secret: context.env.PUSHER_SECRET,
cluster: context.env.PUSHER_CLUSTER,
encrypted: true,
});
}
if(context.env.TWITTER_ID) {
context.twitter = new Twitter({
consumer_key: process.env.TWITTER_ID,
consumer_secret: process.env.TWITTER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});
}
context.app = express();
context.createObjectId = ObjectId;
context.logger = new (winston.Logger)({
transports: [new (winston.transports.Console)({ level: 'silly' })],
});
context.tokens = new TokenService({
uniqueId: function createTokenUniqueId() {
return context.createObjectId().toString();
},
secret: context.env.TOKEN_SECRET,
time: context.time,
});
if(context.env.API_ANALYTICS_KEY) {
context.analyticsAgent = analytics({
apiKey: context.env.API_ANALYTICS_KEY,
uuidResolver: function agentUuidResolver(req) {
return req.user ? req.user._id : null;
},
});
}
if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {
context.sendMail = function initSendMail() {
var mailer = nodemailer.createTransport(
nodemailerMailgunTransport({
auth: {
api_key: context.env.MAILGUN_KEY,
domain: context.env.MAILGUN_DOMAIN,
},
})
);
return function sendEmail(contents) {
return new Promise(function(resolve, reject) {
mailer.sendMail(contents, function sendMailHandler(err, info) {
if(err) {
return reject(err);
}
resolve(info);
});
});
};
}();
}
context.protocol = context.env.PROTOCOL || 'http';
context.host = context.env.HOST || 'localhost';
context.domain = context.env.DOMAIN || '';
context.port = 'undefined' !== typeof context.env.PORT ?
parseInt(context.env.PORT, 10) :
3000;
context.base = context.protocol + '://' + (
context.domain ?
context.domain :
context.host + ':' + context.port
);
context.logger.debug('Env', context.env);
// Workers
initPSAWorker(context);
initFacebookWorker(context);
initTwitterWorker(context);
initXeeWorker(context);
if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {
initEmailWorker(context);
}
if(context.env.PUSHER_APP_ID) {
initPusherWorker(context);
}
// Routes
initRoutes(context);
// Starting the server
return new Promise(function handleServerPromise(resolve, reject) {
context.server = context.app.listen(context.port, function handleServerCb(err) {
if(err) {
return reject(err);
}
context.logger.debug(
'Server listening to \\o/ -> http://%s:%s - Pid: %s',
context.host, context.port, process.pid
);
resolve();
});
});
});
| (api-analytics) uuid must be a string or a number | backend/index.js | (api-analytics) uuid must be a string or a number | <ide><path>ackend/index.js
<ide> context.analyticsAgent = analytics({
<ide> apiKey: context.env.API_ANALYTICS_KEY,
<ide> uuidResolver: function agentUuidResolver(req) {
<del> return req.user ? req.user._id : null;
<add> return req.user && req.user._id ? req.user._id.toString() : null;
<ide> },
<ide> });
<ide> } |
|
Java | apache-2.0 | 1752dfd10e8242d6e017b3828c7d6e94f044691c | 0 | androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.internal.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.ColorUtils;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.util.LruCache;
import android.support.v7.appcompat.R;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
import static android.support.v7.internal.widget.ThemeUtils.getDisabledThemeAttrColor;
import static android.support.v7.internal.widget.ThemeUtils.getThemeAttrColor;
import static android.support.v7.internal.widget.ThemeUtils.getThemeAttrColorStateList;
/**
* @hide
*/
public final class TintManager {
public static final boolean SHOULD_BE_USED = Build.VERSION.SDK_INT < 21;
private static final String TAG = "TintManager";
private static final boolean DEBUG = false;
private static final PorterDuff.Mode DEFAULT_MODE = PorterDuff.Mode.SRC_IN;
private static final WeakHashMap<Context, TintManager> INSTANCE_CACHE = new WeakHashMap<>();
private static final ColorFilterLruCache COLOR_FILTER_CACHE = new ColorFilterLruCache(6);
/**
* Drawables which should be tinted with the value of {@code R.attr.colorControlNormal},
* using the default mode using a raw color filter.
*/
private static final int[] COLORFILTER_TINT_COLOR_CONTROL_NORMAL = {
R.drawable.abc_textfield_search_default_mtrl_alpha,
R.drawable.abc_textfield_default_mtrl_alpha,
R.drawable.abc_ab_share_pack_mtrl_alpha
};
/**
* Drawables which should be tinted with the value of {@code R.attr.colorControlNormal}, using
* {@link DrawableCompat}'s tinting functionality.
*/
private static final int[] TINT_COLOR_CONTROL_NORMAL = {
R.drawable.abc_ic_ab_back_mtrl_am_alpha,
R.drawable.abc_ic_go_search_api_mtrl_alpha,
R.drawable.abc_ic_search_api_mtrl_alpha,
R.drawable.abc_ic_commit_search_api_mtrl_alpha,
R.drawable.abc_ic_clear_mtrl_alpha,
R.drawable.abc_ic_menu_share_mtrl_alpha,
R.drawable.abc_ic_menu_copy_mtrl_am_alpha,
R.drawable.abc_ic_menu_cut_mtrl_alpha,
R.drawable.abc_ic_menu_selectall_mtrl_alpha,
R.drawable.abc_ic_menu_paste_mtrl_am_alpha,
R.drawable.abc_ic_menu_moreoverflow_mtrl_alpha,
R.drawable.abc_ic_voice_search_api_mtrl_alpha
};
/**
* Drawables which should be tinted with the value of {@code R.attr.colorControlActivated},
* using a color filter.
*/
private static final int[] COLORFILTER_COLOR_CONTROL_ACTIVATED = {
R.drawable.abc_textfield_activated_mtrl_alpha,
R.drawable.abc_textfield_search_activated_mtrl_alpha,
R.drawable.abc_cab_background_top_mtrl_alpha,
R.drawable.abc_text_cursor_mtrl_alpha
};
/**
* Drawables which should be tinted with the value of {@code android.R.attr.colorBackground},
* using the {@link android.graphics.PorterDuff.Mode#MULTIPLY} mode and a color filter.
*/
private static final int[] COLORFILTER_COLOR_BACKGROUND_MULTIPLY = {
R.drawable.abc_popup_background_mtrl_mult,
R.drawable.abc_cab_background_internal_bg,
R.drawable.abc_menu_hardkey_panel_mtrl_mult
};
/**
* Drawables which should be tinted using a state list containing values of
* {@code R.attr.colorControlNormal} and {@code R.attr.colorControlActivated}
*/
private static final int[] TINT_COLOR_CONTROL_STATE_LIST = {
R.drawable.abc_edit_text_material,
R.drawable.abc_tab_indicator_material,
R.drawable.abc_textfield_search_material,
R.drawable.abc_spinner_mtrl_am_alpha,
R.drawable.abc_spinner_textfield_background_material,
R.drawable.abc_ratingbar_full_material,
R.drawable.abc_switch_track_mtrl_alpha,
R.drawable.abc_switch_thumb_material,
R.drawable.abc_btn_default_mtrl_shape,
R.drawable.abc_btn_borderless_material
};
/**
* Drawables which should be tinted using a state list containing values of
* {@code R.attr.colorControlNormal} and {@code R.attr.colorControlActivated} for the checked
* state.
*/
private static final int[] TINT_CHECKABLE_BUTTON_LIST = {
R.drawable.abc_btn_check_material,
R.drawable.abc_btn_radio_material
};
private final WeakReference<Context> mContextRef;
private SparseArray<ColorStateList> mTintLists;
private ColorStateList mDefaultColorStateList;
/**
* A helper method to get a {@link TintManager} and then call {@link #getDrawable(int)}.
* This method should not be used routinely.
*/
public static Drawable getDrawable(Context context, int resId) {
if (isInTintList(resId)) {
return TintManager.get(context).getDrawable(resId);
} else {
return ContextCompat.getDrawable(context, resId);
}
}
/**
* Get a {@link android.support.v7.internal.widget.TintManager} instance.
*/
public static TintManager get(Context context) {
TintManager tm = INSTANCE_CACHE.get(context);
if (tm == null) {
tm = new TintManager(context);
INSTANCE_CACHE.put(context, tm);
}
return tm;
}
private TintManager(Context context) {
mContextRef = new WeakReference<>(context);
}
public Drawable getDrawable(int resId) {
return getDrawable(resId, false);
}
public Drawable getDrawable(int resId, boolean failIfNotKnown) {
final Context context = mContextRef.get();
if (context == null) return null;
Drawable drawable = ContextCompat.getDrawable(context, resId);
if (drawable != null) {
if (Build.VERSION.SDK_INT >= 8) {
// Mutate can cause NPEs on 2.1
drawable = drawable.mutate();
}
final ColorStateList tintList = getTintList(resId);
if (tintList != null) {
// First wrap the Drawable and set the tint list
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTintList(drawable, tintList);
// If there is a blending mode specified for the drawable, use it
final PorterDuff.Mode tintMode = getTintMode(resId);
if (tintMode != null) {
DrawableCompat.setTintMode(drawable, tintMode);
}
} else if (resId == R.drawable.abc_cab_background_top_material) {
return new LayerDrawable(new Drawable[] {
getDrawable(R.drawable.abc_cab_background_internal_bg),
getDrawable(R.drawable.abc_cab_background_top_mtrl_alpha)
});
} else {
final boolean usedColorFilter = tintDrawableUsingColorFilter(resId, drawable);
if (!usedColorFilter && failIfNotKnown) {
// If we didn't tint using a ColorFilter, and we're set to fail if we don't
// know the id, return null
drawable = null;
}
}
}
return drawable;
}
public final boolean tintDrawableUsingColorFilter(final int resId, Drawable drawable) {
final Context context = mContextRef.get();
if (context == null) return false;
PorterDuff.Mode tintMode = null;
boolean colorAttrSet = false;
int colorAttr = 0;
int alpha = -1;
if (arrayContains(COLORFILTER_TINT_COLOR_CONTROL_NORMAL, resId)) {
colorAttr = R.attr.colorControlNormal;
colorAttrSet = true;
} else if (arrayContains(COLORFILTER_COLOR_CONTROL_ACTIVATED, resId)) {
colorAttr = R.attr.colorControlActivated;
colorAttrSet = true;
} else if (arrayContains(COLORFILTER_COLOR_BACKGROUND_MULTIPLY, resId)) {
colorAttr = android.R.attr.colorBackground;
colorAttrSet = true;
tintMode = PorterDuff.Mode.MULTIPLY;
} else if (resId == R.drawable.abc_list_divider_mtrl_alpha) {
colorAttr = android.R.attr.colorForeground;
colorAttrSet = true;
alpha = Math.round(0.16f * 255);
}
if (colorAttrSet) {
final int color = getThemeAttrColor(context, colorAttr);
setPorterDuffColorFilter(drawable, color, tintMode);
if (alpha != -1) {
drawable.setAlpha(alpha);
}
if (DEBUG) {
Log.d(TAG, "Tinted Drawable: " + context.getResources().getResourceName(resId) +
" with color: #" + Integer.toHexString(color));
}
return true;
}
return false;
}
private static boolean arrayContains(int[] array, int value) {
for (int id : array) {
if (id == value) {
return true;
}
}
return false;
}
private static boolean isInTintList(int drawableId) {
return arrayContains(TINT_COLOR_CONTROL_NORMAL, drawableId) ||
arrayContains(COLORFILTER_TINT_COLOR_CONTROL_NORMAL, drawableId) ||
arrayContains(COLORFILTER_COLOR_CONTROL_ACTIVATED, drawableId) ||
arrayContains(TINT_COLOR_CONTROL_STATE_LIST, drawableId) ||
arrayContains(COLORFILTER_COLOR_BACKGROUND_MULTIPLY, drawableId) ||
arrayContains(TINT_CHECKABLE_BUTTON_LIST, drawableId) ||
drawableId == R.drawable.abc_cab_background_top_material;
}
final PorterDuff.Mode getTintMode(final int resId) {
PorterDuff.Mode mode = null;
if (resId == R.drawable.abc_switch_thumb_material) {
mode = PorterDuff.Mode.MULTIPLY;
}
return mode;
}
public final ColorStateList getTintList(int resId) {
final Context context = mContextRef.get();
if (context == null) return null;
// Try the cache first (if it exists)
ColorStateList tint = mTintLists != null ? mTintLists.get(resId) : null;
if (tint == null) {
// ...if the cache did not contain a color state list, try and create one
if (resId == R.drawable.abc_edit_text_material) {
tint = createEditTextColorStateList(context);
} else if (resId == R.drawable.abc_switch_track_mtrl_alpha) {
tint = createSwitchTrackColorStateList(context);
} else if (resId == R.drawable.abc_switch_thumb_material) {
tint = createSwitchThumbColorStateList(context);
} else if (resId == R.drawable.abc_btn_default_mtrl_shape
|| resId == R.drawable.abc_btn_borderless_material) {
tint = createButtonColorStateList(context);
} else if (resId == R.drawable.abc_spinner_mtrl_am_alpha
|| resId == R.drawable.abc_spinner_textfield_background_material) {
tint = createSpinnerColorStateList(context);
} else if (arrayContains(TINT_COLOR_CONTROL_NORMAL, resId)) {
tint = getThemeAttrColorStateList(context, R.attr.colorControlNormal);
} else if (arrayContains(TINT_COLOR_CONTROL_STATE_LIST, resId)) {
tint = getDefaultColorStateList(context);
} else if (arrayContains(TINT_CHECKABLE_BUTTON_LIST, resId)) {
tint = createCheckableButtonColorStateList(context);
}
if (tint != null) {
if (mTintLists == null) {
// If our tint list cache hasn't been set up yet, create it
mTintLists = new SparseArray<>();
}
// Add any newly created ColorStateList to the cache
mTintLists.append(resId, tint);
}
}
return tint;
}
private ColorStateList getDefaultColorStateList(Context context) {
if (mDefaultColorStateList == null) {
/**
* Generate the default color state list which uses the colorControl attributes.
* Order is important here. The default enabled state needs to go at the bottom.
*/
final int colorControlNormal = getThemeAttrColor(context, R.attr.colorControlNormal);
final int colorControlActivated = getThemeAttrColor(context,
R.attr.colorControlActivated);
final int[][] states = new int[7][];
final int[] colors = new int[7];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.FOCUSED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.ACTIVATED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.PRESSED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.SELECTED_STATE_SET;
colors[i] = colorControlActivated;
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = colorControlNormal;
i++;
mDefaultColorStateList = new ColorStateList(states, colors);
}
return mDefaultColorStateList;
}
private ColorStateList createCheckableButtonColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlNormal);
i++;
return new ColorStateList(states, colors);
}
private ColorStateList createSwitchTrackColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getThemeAttrColor(context, android.R.attr.colorForeground, 0.1f);
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated, 0.3f);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, android.R.attr.colorForeground, 0.3f);
i++;
return new ColorStateList(states, colors);
}
private ColorStateList createSwitchThumbColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
final ColorStateList thumbColor = getThemeAttrColorStateList(context,
R.attr.colorSwitchThumbNormal);
if (thumbColor != null && thumbColor.isStateful()) {
// If colorSwitchThumbNormal is a valid ColorStateList, extract the default and
// disabled colors from it
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = thumbColor.getColorForState(states[i], 0);
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = thumbColor.getDefaultColor();
i++;
} else {
// Else we'll use an approximation using the default disabled alpha
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorSwitchThumbNormal);
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorSwitchThumbNormal);
i++;
}
return new ColorStateList(states, colors);
}
private ColorStateList createEditTextColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.NOT_PRESSED_OR_FOCUSED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlNormal);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
return new ColorStateList(states, colors);
}
private ColorStateList createButtonColorStateList(Context context) {
final int[][] states = new int[4][];
final int[] colors = new int[4];
int i = 0;
final int colorButtonNormal = getThemeAttrColor(context, R.attr.colorButtonNormal);
final int colorControlHighlight = getThemeAttrColor(context, R.attr.colorControlHighlight);
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorButtonNormal);
i++;
states[i] = ThemeUtils.PRESSED_STATE_SET;
colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
i++;
states[i] = ThemeUtils.FOCUSED_STATE_SET;
colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = colorButtonNormal;
i++;
return new ColorStateList(states, colors);
}
private ColorStateList createSpinnerColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.NOT_PRESSED_OR_FOCUSED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
return new ColorStateList(states, colors);
}
private static class ColorFilterLruCache extends LruCache<Integer, PorterDuffColorFilter> {
public ColorFilterLruCache(int maxSize) {
super(maxSize);
}
PorterDuffColorFilter get(int color, PorterDuff.Mode mode) {
return get(generateCacheKey(color, mode));
}
PorterDuffColorFilter put(int color, PorterDuff.Mode mode, PorterDuffColorFilter filter) {
return put(generateCacheKey(color, mode), filter);
}
private static int generateCacheKey(int color, PorterDuff.Mode mode) {
int hashCode = 1;
hashCode = 31 * hashCode + color;
hashCode = 31 * hashCode + mode.hashCode();
return hashCode;
}
}
public static void tintViewBackground(View view, TintInfo tint) {
final Drawable background = view.getBackground();
if (tint.mHasTintList) {
setPorterDuffColorFilter(
background,
tint.mTintList.getColorForState(view.getDrawableState(),
tint.mTintList.getDefaultColor()),
tint.mHasTintMode ? tint.mTintMode : null);
} else {
background.clearColorFilter();
}
if (Build.VERSION.SDK_INT <= 10) {
// On Gingerbread, GradientDrawable does not invalidate itself when it's ColorFilter
// has changed, so we need to force an invalidation
view.invalidate();
}
}
private static void setPorterDuffColorFilter(Drawable d, int color, PorterDuff.Mode mode) {
if (mode == null) {
// If we don't have a blending mode specified, use our default
mode = DEFAULT_MODE;
}
// First, lets see if the cache already contains the color filter
PorterDuffColorFilter filter = COLOR_FILTER_CACHE.get(color, mode);
if (filter == null) {
// Cache miss, so create a color filter and add it to the cache
filter = new PorterDuffColorFilter(color, mode);
COLOR_FILTER_CACHE.put(color, mode, filter);
}
d.setColorFilter(filter);
}
}
| v7/appcompat/src/android/support/v7/internal/widget/TintManager.java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.internal.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.ColorUtils;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.util.LruCache;
import android.support.v7.appcompat.R;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
import static android.support.v7.internal.widget.ThemeUtils.getDisabledThemeAttrColor;
import static android.support.v7.internal.widget.ThemeUtils.getThemeAttrColor;
import static android.support.v7.internal.widget.ThemeUtils.getThemeAttrColorStateList;
/**
* @hide
*/
public final class TintManager {
public static final boolean SHOULD_BE_USED = Build.VERSION.SDK_INT < 21;
private static final String TAG = "TintManager";
private static final boolean DEBUG = false;
private static final PorterDuff.Mode DEFAULT_MODE = PorterDuff.Mode.SRC_IN;
private static final WeakHashMap<Context, TintManager> INSTANCE_CACHE = new WeakHashMap<>();
private static final ColorFilterLruCache COLOR_FILTER_CACHE = new ColorFilterLruCache(6);
/**
* Drawables which should be tinted with the value of {@code R.attr.colorControlNormal},
* using the default mode using a raw color filter.
*/
private static final int[] COLORFILTER_TINT_COLOR_CONTROL_NORMAL = {
R.drawable.abc_textfield_search_default_mtrl_alpha,
R.drawable.abc_textfield_default_mtrl_alpha,
R.drawable.abc_ab_share_pack_mtrl_alpha
};
/**
* Drawables which should be tinted with the value of {@code R.attr.colorControlNormal}, using
* {@link DrawableCompat}'s tinting functionality.
*/
private static final int[] TINT_COLOR_CONTROL_NORMAL = {
R.drawable.abc_ic_ab_back_mtrl_am_alpha,
R.drawable.abc_ic_go_search_api_mtrl_alpha,
R.drawable.abc_ic_search_api_mtrl_alpha,
R.drawable.abc_ic_commit_search_api_mtrl_alpha,
R.drawable.abc_ic_clear_mtrl_alpha,
R.drawable.abc_ic_menu_share_mtrl_alpha,
R.drawable.abc_ic_menu_copy_mtrl_am_alpha,
R.drawable.abc_ic_menu_cut_mtrl_alpha,
R.drawable.abc_ic_menu_selectall_mtrl_alpha,
R.drawable.abc_ic_menu_paste_mtrl_am_alpha,
R.drawable.abc_ic_menu_moreoverflow_mtrl_alpha,
R.drawable.abc_ic_voice_search_api_mtrl_alpha
};
/**
* Drawables which should be tinted with the value of {@code R.attr.colorControlActivated},
* using a color filter.
*/
private static final int[] COLORFILTER_COLOR_CONTROL_ACTIVATED = {
R.drawable.abc_textfield_activated_mtrl_alpha,
R.drawable.abc_textfield_search_activated_mtrl_alpha,
R.drawable.abc_cab_background_top_mtrl_alpha,
R.drawable.abc_text_cursor_mtrl_alpha
};
/**
* Drawables which should be tinted with the value of {@code android.R.attr.colorBackground},
* using the {@link android.graphics.PorterDuff.Mode#MULTIPLY} mode and a color filter.
*/
private static final int[] COLORFILTER_COLOR_BACKGROUND_MULTIPLY = {
R.drawable.abc_popup_background_mtrl_mult,
R.drawable.abc_cab_background_internal_bg,
R.drawable.abc_menu_hardkey_panel_mtrl_mult
};
/**
* Drawables which should be tinted using a state list containing values of
* {@code R.attr.colorControlNormal} and {@code R.attr.colorControlActivated}
*/
private static final int[] TINT_COLOR_CONTROL_STATE_LIST = {
R.drawable.abc_edit_text_material,
R.drawable.abc_tab_indicator_material,
R.drawable.abc_textfield_search_material,
R.drawable.abc_spinner_mtrl_am_alpha,
R.drawable.abc_btn_check_material,
R.drawable.abc_btn_radio_material,
R.drawable.abc_spinner_textfield_background_material,
R.drawable.abc_ratingbar_full_material,
R.drawable.abc_switch_track_mtrl_alpha,
R.drawable.abc_switch_thumb_material,
R.drawable.abc_btn_default_mtrl_shape,
R.drawable.abc_btn_borderless_material
};
private final WeakReference<Context> mContextRef;
private SparseArray<ColorStateList> mTintLists;
private ColorStateList mDefaultColorStateList;
/**
* A helper method to get a {@link TintManager} and then call {@link #getDrawable(int)}.
* This method should not be used routinely.
*/
public static Drawable getDrawable(Context context, int resId) {
if (isInTintList(resId)) {
return TintManager.get(context).getDrawable(resId);
} else {
return ContextCompat.getDrawable(context, resId);
}
}
/**
* Get a {@link android.support.v7.internal.widget.TintManager} instance.
*/
public static TintManager get(Context context) {
TintManager tm = INSTANCE_CACHE.get(context);
if (tm == null) {
tm = new TintManager(context);
INSTANCE_CACHE.put(context, tm);
}
return tm;
}
private TintManager(Context context) {
mContextRef = new WeakReference<>(context);
}
public Drawable getDrawable(int resId) {
return getDrawable(resId, false);
}
public Drawable getDrawable(int resId, boolean failIfNotKnown) {
final Context context = mContextRef.get();
if (context == null) return null;
Drawable drawable = ContextCompat.getDrawable(context, resId);
if (drawable != null) {
if (Build.VERSION.SDK_INT >= 8) {
// Mutate can cause NPEs on 2.1
drawable = drawable.mutate();
}
final ColorStateList tintList = getTintList(resId);
if (tintList != null) {
// First wrap the Drawable and set the tint list
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTintList(drawable, tintList);
// If there is a blending mode specified for the drawable, use it
final PorterDuff.Mode tintMode = getTintMode(resId);
if (tintMode != null) {
DrawableCompat.setTintMode(drawable, tintMode);
}
} else if (resId == R.drawable.abc_cab_background_top_material) {
return new LayerDrawable(new Drawable[] {
getDrawable(R.drawable.abc_cab_background_internal_bg),
getDrawable(R.drawable.abc_cab_background_top_mtrl_alpha)
});
} else {
final boolean usedColorFilter = tintDrawableUsingColorFilter(resId, drawable);
if (!usedColorFilter && failIfNotKnown) {
// If we didn't tint using a ColorFilter, and we're set to fail if we don't
// know the id, return null
drawable = null;
}
}
}
return drawable;
}
public final boolean tintDrawableUsingColorFilter(final int resId, Drawable drawable) {
final Context context = mContextRef.get();
if (context == null) return false;
PorterDuff.Mode tintMode = null;
boolean colorAttrSet = false;
int colorAttr = 0;
int alpha = -1;
if (arrayContains(COLORFILTER_TINT_COLOR_CONTROL_NORMAL, resId)) {
colorAttr = R.attr.colorControlNormal;
colorAttrSet = true;
} else if (arrayContains(COLORFILTER_COLOR_CONTROL_ACTIVATED, resId)) {
colorAttr = R.attr.colorControlActivated;
colorAttrSet = true;
} else if (arrayContains(COLORFILTER_COLOR_BACKGROUND_MULTIPLY, resId)) {
colorAttr = android.R.attr.colorBackground;
colorAttrSet = true;
tintMode = PorterDuff.Mode.MULTIPLY;
} else if (resId == R.drawable.abc_list_divider_mtrl_alpha) {
colorAttr = android.R.attr.colorForeground;
colorAttrSet = true;
alpha = Math.round(0.16f * 255);
}
if (colorAttrSet) {
final int color = getThemeAttrColor(context, colorAttr);
setPorterDuffColorFilter(drawable, color, tintMode);
if (alpha != -1) {
drawable.setAlpha(alpha);
}
if (DEBUG) {
Log.d(TAG, "Tinted Drawable: " + context.getResources().getResourceName(resId) +
" with color: #" + Integer.toHexString(color));
}
return true;
}
return false;
}
private static boolean arrayContains(int[] array, int value) {
for (int id : array) {
if (id == value) {
return true;
}
}
return false;
}
private static boolean isInTintList(int drawableId) {
return arrayContains(TINT_COLOR_CONTROL_NORMAL, drawableId) ||
arrayContains(COLORFILTER_TINT_COLOR_CONTROL_NORMAL, drawableId) ||
arrayContains(COLORFILTER_COLOR_CONTROL_ACTIVATED, drawableId) ||
arrayContains(TINT_COLOR_CONTROL_STATE_LIST, drawableId) ||
arrayContains(COLORFILTER_COLOR_BACKGROUND_MULTIPLY, drawableId) ||
drawableId == R.drawable.abc_cab_background_top_material;
}
final PorterDuff.Mode getTintMode(final int resId) {
PorterDuff.Mode mode = null;
if (resId == R.drawable.abc_switch_thumb_material) {
mode = PorterDuff.Mode.MULTIPLY;
}
return mode;
}
public final ColorStateList getTintList(int resId) {
final Context context = mContextRef.get();
if (context == null) return null;
// Try the cache first (if it exists)
ColorStateList tint = mTintLists != null ? mTintLists.get(resId) : null;
if (tint == null) {
// ...if the cache did not contain a color state list, try and create one
if (resId == R.drawable.abc_edit_text_material) {
tint = createEditTextColorStateList(context);
} else if (resId == R.drawable.abc_switch_track_mtrl_alpha) {
tint = createSwitchTrackColorStateList(context);
} else if (resId == R.drawable.abc_switch_thumb_material) {
tint = createSwitchThumbColorStateList(context);
} else if (resId == R.drawable.abc_btn_default_mtrl_shape
|| resId == R.drawable.abc_btn_borderless_material) {
tint = createButtonColorStateList(context);
} else if (resId == R.drawable.abc_spinner_mtrl_am_alpha
|| resId == R.drawable.abc_spinner_textfield_background_material) {
tint = createSpinnerColorStateList(context);
} else if (arrayContains(TINT_COLOR_CONTROL_NORMAL, resId)) {
tint = getThemeAttrColorStateList(context, R.attr.colorControlNormal);
} else if (arrayContains(TINT_COLOR_CONTROL_STATE_LIST, resId)) {
tint = getDefaultColorStateList(context);
}
if (tint != null) {
if (mTintLists == null) {
// If our tint list cache hasn't been set up yet, create it
mTintLists = new SparseArray<>();
}
// Add any newly created ColorStateList to the cache
mTintLists.append(resId, tint);
}
}
return tint;
}
private ColorStateList getDefaultColorStateList(Context context) {
if (mDefaultColorStateList == null) {
/**
* Generate the default color state list which uses the colorControl attributes.
* Order is important here. The default enabled state needs to go at the bottom.
*/
final int colorControlNormal = getThemeAttrColor(context, R.attr.colorControlNormal);
final int colorControlActivated = getThemeAttrColor(context,
R.attr.colorControlActivated);
final int[][] states = new int[7][];
final int[] colors = new int[7];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.FOCUSED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.ACTIVATED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.PRESSED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = colorControlActivated;
i++;
states[i] = ThemeUtils.SELECTED_STATE_SET;
colors[i] = colorControlActivated;
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = colorControlNormal;
i++;
mDefaultColorStateList = new ColorStateList(states, colors);
}
return mDefaultColorStateList;
}
private ColorStateList createSwitchTrackColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getThemeAttrColor(context, android.R.attr.colorForeground, 0.1f);
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated, 0.3f);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, android.R.attr.colorForeground, 0.3f);
i++;
return new ColorStateList(states, colors);
}
private ColorStateList createSwitchThumbColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
final ColorStateList thumbColor = getThemeAttrColorStateList(context,
R.attr.colorSwitchThumbNormal);
if (thumbColor != null && thumbColor.isStateful()) {
// If colorSwitchThumbNormal is a valid ColorStateList, extract the default and
// disabled colors from it
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = thumbColor.getColorForState(states[i], 0);
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = thumbColor.getDefaultColor();
i++;
} else {
// Else we'll use an approximation using the default disabled alpha
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorSwitchThumbNormal);
i++;
states[i] = ThemeUtils.CHECKED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorSwitchThumbNormal);
i++;
}
return new ColorStateList(states, colors);
}
private ColorStateList createEditTextColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.NOT_PRESSED_OR_FOCUSED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlNormal);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
return new ColorStateList(states, colors);
}
private ColorStateList createButtonColorStateList(Context context) {
final int[][] states = new int[4][];
final int[] colors = new int[4];
int i = 0;
final int colorButtonNormal = getThemeAttrColor(context, R.attr.colorButtonNormal);
final int colorControlHighlight = getThemeAttrColor(context, R.attr.colorControlHighlight);
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorButtonNormal);
i++;
states[i] = ThemeUtils.PRESSED_STATE_SET;
colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
i++;
states[i] = ThemeUtils.FOCUSED_STATE_SET;
colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
i++;
// Default enabled state
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = colorButtonNormal;
i++;
return new ColorStateList(states, colors);
}
private ColorStateList createSpinnerColorStateList(Context context) {
final int[][] states = new int[3][];
final int[] colors = new int[3];
int i = 0;
// Disabled state
states[i] = ThemeUtils.DISABLED_STATE_SET;
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.NOT_PRESSED_OR_FOCUSED_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlNormal);
i++;
states[i] = ThemeUtils.EMPTY_STATE_SET;
colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
i++;
return new ColorStateList(states, colors);
}
private static class ColorFilterLruCache extends LruCache<Integer, PorterDuffColorFilter> {
public ColorFilterLruCache(int maxSize) {
super(maxSize);
}
PorterDuffColorFilter get(int color, PorterDuff.Mode mode) {
return get(generateCacheKey(color, mode));
}
PorterDuffColorFilter put(int color, PorterDuff.Mode mode, PorterDuffColorFilter filter) {
return put(generateCacheKey(color, mode), filter);
}
private static int generateCacheKey(int color, PorterDuff.Mode mode) {
int hashCode = 1;
hashCode = 31 * hashCode + color;
hashCode = 31 * hashCode + mode.hashCode();
return hashCode;
}
}
public static void tintViewBackground(View view, TintInfo tint) {
final Drawable background = view.getBackground();
if (tint.mHasTintList) {
setPorterDuffColorFilter(
background,
tint.mTintList.getColorForState(view.getDrawableState(),
tint.mTintList.getDefaultColor()),
tint.mHasTintMode ? tint.mTintMode : null);
} else {
background.clearColorFilter();
}
if (Build.VERSION.SDK_INT <= 10) {
// On Gingerbread, GradientDrawable does not invalidate itself when it's ColorFilter
// has changed, so we need to force an invalidation
view.invalidate();
}
}
private static void setPorterDuffColorFilter(Drawable d, int color, PorterDuff.Mode mode) {
if (mode == null) {
// If we don't have a blending mode specified, use our default
mode = DEFAULT_MODE;
}
// First, lets see if the cache already contains the color filter
PorterDuffColorFilter filter = COLOR_FILTER_CACHE.get(color, mode);
if (filter == null) {
// Cache miss, so create a color filter and add it to the cache
filter = new PorterDuffColorFilter(color, mode);
COLOR_FILTER_CACHE.put(color, mode, filter);
}
d.setColorFilter(filter);
}
}
| Fix CheckBox and RadioButton pre-v21 drawable tint
They were previously a bit eager to show the activated
tint.
BUG: 20934571
Change-Id: Id1e9efc930a58d8fc63bbb5e4a9406c6c93d2141
| v7/appcompat/src/android/support/v7/internal/widget/TintManager.java | Fix CheckBox and RadioButton pre-v21 drawable tint | <ide><path>7/appcompat/src/android/support/v7/internal/widget/TintManager.java
<ide> R.drawable.abc_tab_indicator_material,
<ide> R.drawable.abc_textfield_search_material,
<ide> R.drawable.abc_spinner_mtrl_am_alpha,
<del> R.drawable.abc_btn_check_material,
<del> R.drawable.abc_btn_radio_material,
<ide> R.drawable.abc_spinner_textfield_background_material,
<ide> R.drawable.abc_ratingbar_full_material,
<ide> R.drawable.abc_switch_track_mtrl_alpha,
<ide> R.drawable.abc_switch_thumb_material,
<ide> R.drawable.abc_btn_default_mtrl_shape,
<ide> R.drawable.abc_btn_borderless_material
<add> };
<add>
<add> /**
<add> * Drawables which should be tinted using a state list containing values of
<add> * {@code R.attr.colorControlNormal} and {@code R.attr.colorControlActivated} for the checked
<add> * state.
<add> */
<add> private static final int[] TINT_CHECKABLE_BUTTON_LIST = {
<add> R.drawable.abc_btn_check_material,
<add> R.drawable.abc_btn_radio_material
<ide> };
<ide>
<ide> private final WeakReference<Context> mContextRef;
<ide> arrayContains(COLORFILTER_COLOR_CONTROL_ACTIVATED, drawableId) ||
<ide> arrayContains(TINT_COLOR_CONTROL_STATE_LIST, drawableId) ||
<ide> arrayContains(COLORFILTER_COLOR_BACKGROUND_MULTIPLY, drawableId) ||
<add> arrayContains(TINT_CHECKABLE_BUTTON_LIST, drawableId) ||
<ide> drawableId == R.drawable.abc_cab_background_top_material;
<ide> }
<ide>
<ide> tint = getThemeAttrColorStateList(context, R.attr.colorControlNormal);
<ide> } else if (arrayContains(TINT_COLOR_CONTROL_STATE_LIST, resId)) {
<ide> tint = getDefaultColorStateList(context);
<add> } else if (arrayContains(TINT_CHECKABLE_BUTTON_LIST, resId)) {
<add> tint = createCheckableButtonColorStateList(context);
<ide> }
<ide>
<ide> if (tint != null) {
<ide> mDefaultColorStateList = new ColorStateList(states, colors);
<ide> }
<ide> return mDefaultColorStateList;
<add> }
<add>
<add> private ColorStateList createCheckableButtonColorStateList(Context context) {
<add> final int[][] states = new int[3][];
<add> final int[] colors = new int[3];
<add> int i = 0;
<add>
<add> // Disabled state
<add> states[i] = ThemeUtils.DISABLED_STATE_SET;
<add> colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal);
<add> i++;
<add>
<add> states[i] = ThemeUtils.CHECKED_STATE_SET;
<add> colors[i] = getThemeAttrColor(context, R.attr.colorControlActivated);
<add> i++;
<add>
<add> // Default enabled state
<add> states[i] = ThemeUtils.EMPTY_STATE_SET;
<add> colors[i] = getThemeAttrColor(context, R.attr.colorControlNormal);
<add> i++;
<add>
<add> return new ColorStateList(states, colors);
<ide> }
<ide>
<ide> private ColorStateList createSwitchTrackColorStateList(Context context) { |
|
JavaScript | mit | ec1c1514b28f50d23238ba8dbccf3d6822f15b47 | 0 | msakuta/WebGL-Orbiter,msakuta/WebGL-Orbiter,msakuta/WebGL-Orbiter | ;(function(){
'use strict'
var container, stats;
var camera, scene, renderer;
var group;
var background;
var overlay, overlayCamera;
var navballMesh, prograde, retrograde;
var timescaleControl;
var throttleControl;
var speedControl;
var orbitalElementControl;
var statsControl;
var settingsControl;
var altitudeControl;
var messageControl;
var mouseX = 0, mouseY = 0;
var cameraControls;
var grids;
var scenarioSelectorControl;
var saveControl;
var loadControl;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var viewScale = 100;
var simTime, startTime;
var realTime;
var center_select = false;
var select_idx = 0;
var select_obj = null;
var nlips_enable = true;
var grid_enable = false;
var units_km = true;
var sync_rotate = false;
var buttons = {
up: false,
down: false,
left: false,
right: false,
counterclockwise: false,
clockwise: false,
};
var accelerate = false;
var decelerate = false;
var sun;
var light;
var celestialBodies = {};
var selectedOrbitMaterial;
var AU = 149597871; // Astronomical unit in kilometers
var GMsun = 1.327124400e11 / AU / AU/ AU; // Product of gravitational constant (G) and Sun's mass (Msun)
var epsilon = 1e-40; // Doesn't the machine epsilon depend on browsers!??
var timescale = 1e0; // This is not a constant; it can be changed by the user
var rad_per_deg = Math.PI / 180; // Radians per degrees
var navballRadius = 64;
function AxisAngleQuaternion(x, y, z, angle){
var q = new THREE.Quaternion();
q.setFromAxisAngle(new THREE.Vector3(x, y, z), angle);
return q;
}
// CelestialBody class
function CelestialBody(parent, position, vertex, orbitColor, GM, name){
this.position = position;
this.velocity = new THREE.Vector3();
this.quaternion = new THREE.Quaternion();
this.angularVelocity = new THREE.Vector3();
if(orbitColor) this.orbitMaterial = new THREE.LineBasicMaterial({color: orbitColor});
this.children = [];
this.parent = parent;
this.GM = GM || GMsun;
if(parent) parent.children.push(this);
this.radius = 1 / AU;
this.controllable = false;
this.throttle = 0.;
this.totalDeltaV = 0.;
this.ignitionCount = 0;
this.name = name;
celestialBodies[name] = this;
}
CelestialBody.prototype.init = function(){
this.ascending_node = Math.random() * Math.PI * 2;
this.epoch = Math.random();
this.mean_anomaly = Math.random();
this.update();
};
CelestialBody.prototype.get_eccentric_anomaly = function(time){
// Calculates eccentric anomaly from mean anomaly in first order approximation
// see http://en.wikipedia.org/wiki/Eccentric_anomaly
var td = time - this.epoch;
var period = 2 * Math.PI * Math.sqrt(Math.pow(this.semimajor_axis * AU, 3) / this.parent.GM);
var now_anomaly = this.mean_anomaly + td * 2 * Math.PI / period;
return now_anomaly + this.eccentricity * Math.sin(now_anomaly);
};
CelestialBody.prototype.getWorldPosition = function(){
if(this.parent)
return this.parent.getWorldPosition().clone().add(this.position);
else
return this.position;
};
CelestialBody.prototype.setOrbitingVelocity = function(semimajor_axis, rotation){
this.velocity = new THREE.Vector3(1, 0, 0)
.multiplyScalar(Math.sqrt(this.parent.GM * (2 / this.position.length() - 1 / semimajor_axis)))
.applyQuaternion(rotation);
}
function deserializeVector3(json){
return new THREE.Vector3(json.x, json.y, json.z);
}
function deserializeQuaternion(json){
return new THREE.Quaternion(json._x, json._y, json._z, json._w);
}
CelestialBody.prototype.serialize = function(){
return {
name: this.name,
parent: this.parent.name,
position: this.position,
velocity: this.velocity,
quaternion: this.quaternion,
angularVelocity: this.angularVelocity,
};
};
CelestialBody.prototype.deserialize = function(json){
this.name = json.name;
this.setParent(celestialBodies[json.parent] || sun);
this.position = deserializeVector3(json.position);
this.velocity = deserializeVector3(json.velocity);
this.quaternion = deserializeQuaternion(json.quaternion);
this.angularVelocity = deserializeVector3(json.angularVelocity);
};
CelestialBody.prototype.setParent = function(newParent){
if(this.parent === newParent) return;
if(this.parent){
var j = this.parent.children.indexOf(this);
if(0 <= j) this.parent.children.splice(j, 1);
}
this.parent = newParent;
if(this.parent)
this.parent.children.push(this);
}
// Update orbital elements from position and velocity.
// The whole discussion is found in chapter 4.4 in
// https://www.academia.edu/8612052/ORBITAL_MECHANICS_FOR_ENGINEERING_STUDENTS
CelestialBody.prototype.update = function(){
function visualPosition(o){
var position = o.getWorldPosition();
if(select_obj && center_select)
position.sub(select_obj.getWorldPosition());
position.multiplyScalar(viewScale);
return position;
}
/// NLIPS: Non-Linear Inverse Perspective Scrolling
/// Idea originally found in a game Homeworld that enable
/// distant small objects to appear on screen in recognizable size
/// but still renders in real scale when zoomed up.
function nlipsFactor(o){
if(!nlips_enable)
return 1;
var g_nlips_factor = 1e6;
var d = visualPosition(o).distanceTo(camera.position) / viewScale;
var f = d / o.radius * g_nlips_factor + 1;
return f;
}
/// Calculate position of periapsis and apoapsis on the screen
/// for placing overlay icons.
/// peri = -1 if periapsis, otherwise 1
function calcApsePosition(peri, apsis){
var worldPos = e.clone().normalize().multiplyScalar(peri * scope.semimajor_axis * (1 - peri * scope.eccentricity)).sub(scope.position);
var cameraPos = worldPos.multiplyScalar(viewScale).applyMatrix4(camera.matrixWorldInverse);
var persPos = cameraPos.applyProjection(camera.projectionMatrix);
persPos.x *= windowHalfX;
persPos.y *= windowHalfY;
persPos.y -= peri * 8;
if(0 < persPos.z && persPos.z < 1){
apsis.position.copy(persPos);
apsis.visible = true;
}
else
apsis.visible = false;
};
var scope = this;
if(this.vertex)
this.vertex.copy(visualPosition(this));
if(this.model){
this.model.position.copy(visualPosition(this));
this.model.scale.set(1,1,1).multiplyScalar(nlipsFactor(this));
this.model.quaternion.copy(this.quaternion);
}
if(this.parent){
// Angular momentum vectors
var ang = this.velocity.clone().cross(this.position);
var r = this.position.length();
var v = this.velocity.length();
// Node vector
var N = (new THREE.Vector3(0, 0, 1)).cross(ang);
// Eccentricity vector
var e = this.position.clone().multiplyScalar(1 / this.parent.GM * ((v * v - this.parent.GM / r))).sub(this.velocity.clone().multiplyScalar(this.position.dot(this.velocity) / this.parent.GM));
this.eccentricity = e.length();
this.inclination = Math.acos(-ang.z / ang.length());
// Avoid zero division
if(N.lengthSq() <= epsilon)
this.ascending_node = 0;
else{
this.ascending_node = Math.acos(N.x / N.length());
if(N.y < 0) this.ascending_node = 2 * Math.PI - this.ascending_node;
}
this.semimajor_axis = 1 / (2 / r - v * v / this.parent.GM);
// Rotation to perifocal frame
var planeRot = AxisAngleQuaternion(0, 0, 1, this.ascending_node - Math.PI / 2).multiply(AxisAngleQuaternion(0, 1, 0, Math.PI - this.inclination));
var headingApoapsis = -this.position.dot(this.velocity)/Math.abs(this.position.dot(this.velocity));
// Avoid zero division and still get the correct answer when N == 0.
// This is necessary to draw orbit with zero inclination and nonzero eccentricity.
if(N.lengthSq() <= epsilon || e.lengthSq() <= epsilon)
this.argument_of_perihelion = Math.atan2(-e.y, e.x);
else{
this.argument_of_perihelion = Math.acos(N.dot(e) / N.length() / e.length());
if(e.z < 0) this.argument_of_perihelion = 2 * Math.PI - this.argument_of_perihelion;
}
// Total rotation of the orbit
var rotation = planeRot.clone().multiply(AxisAngleQuaternion(0, 0, 1, this.argument_of_perihelion));
// Convert length of unit au into a fixed-length string considering user unit selection.
// Also appends unit string for clarity.
function unitConvLength(au){
if(units_km)
return (au * AU).toPrecision(10) + ' km';
else
return au.toFixed(10) + ' AU';
}
// Show orbit information
if(this === select_obj){
// Yes, building a whole table markup by string manipulation.
// I know it's inefficient, but it's easy to implement. I'm lazy.
orbitalElementControl.setText(
'<table class="table1">'
+ ' <tr><td>e</td><td>' + this.eccentricity.toFixed(10) + '</td></tr>'
+ ' <tr><td>a</td><td>' + unitConvLength(this.semimajor_axis) + '</td></tr>'
+ ' <tr><td>i</td><td>' + (this.inclination / Math.PI).toFixed(10) + '</td></tr>'
+ ' <tr><td>Omega</td><td>' + (this.ascending_node / Math.PI).toFixed(10) + '</td></tr>'
+ ' <tr><td>w</td><td>' + (this.argument_of_perihelion / Math.PI).toFixed(10) + '</td></tr>'
+ ' <tr><td>Periapsis</td><td>' + unitConvLength(scope.semimajor_axis * (1 - scope.eccentricity)) + '</td></tr>'
+ ' <tr><td>Apoapsis</td><td>' + unitConvLength(scope.semimajor_axis * (1 + scope.eccentricity)) + '</td></tr>'
+ ' <tr><td>head</td><td>' + headingApoapsis.toFixed(5) + '</td></tr>'
// + ' omega=' + this.angularVelocity.x.toFixed(10) + ',' + '<br>' + this.angularVelocity.y.toFixed(10) + ',' + '<br>' + this.angularVelocity.z.toFixed(10)
+'</table>'
);
}
// If eccentricity is over 1, the trajectory is a hyperbola.
// It could be parabola in case of eccentricity == 1, but we ignore
// this impractical case for now.
if(1 < this.eccentricity){
// Allocate the hyperbolic shape and mesh only if necessary,
// since most of celestial bodies are all on permanent elliptical orbit.
if(!this.hyperbolicGeometry)
this.hyperbolicGeometry = new THREE.Geometry();
// Calculate the vertices every frame since the hyperbola changes shape
// depending on orbital elements.
var thetaInf = Math.acos(-1 / this.eccentricity);
this.hyperbolicGeometry.vertices.length = 0;
var h2 = ang.lengthSq();
for(var i = -19; i < 20; i++){
// Transform by square root to make far side of the hyperbola less "polygonic"
var isign = i < 0 ? -1 : 1;
var theta = thetaInf * isign * Math.sqrt(Math.abs(i) / 20);
this.hyperbolicGeometry.vertices.push(
new THREE.Vector3( Math.sin(theta), Math.cos(theta), 0 )
.multiplyScalar(h2 / this.parent.GM / (1 + this.eccentricity * Math.cos(theta))) );
}
// Signal three.js to update the vertices
this.hyperbolicGeometry.verticesNeedUpdate = true;
// Allocate hyperbola mesh and add it to the scene.
if(!this.hyperbolicMesh){
this.hyperbolicMesh = new THREE.Line(this.hyperbolicGeometry, this.orbitMaterial);
scene.add(this.hyperbolicMesh);
}
this.hyperbolicMesh.quaternion.copy(rotation);
this.hyperbolicMesh.scale.x = viewScale;
this.hyperbolicMesh.scale.y = viewScale;
this.hyperbolicMesh.position.copy(this.parent.getWorldPosition());
if(select_obj && center_select)
this.hyperbolicMesh.position.sub(select_obj.getWorldPosition());
this.hyperbolicMesh.position.multiplyScalar(viewScale);
// Switch from ellipse to hyperbola
this.hyperbolicMesh.visible = true;
if(this.orbit)
this.orbit.visible = false;
}
else if(this.hyperbolicMesh){
// Switch back to ellipse from hyperbola
if(this.orbit)
this.orbit.visible = true;
this.hyperbolicMesh.visible = false;
}
// Apply transformation to orbit mesh
if(this.orbit){
this.orbit.quaternion.copy(rotation);
this.orbit.scale.x = this.semimajor_axis * viewScale * Math.sqrt(1. - this.eccentricity * this.eccentricity);
this.orbit.scale.y = this.semimajor_axis * viewScale;
this.orbit.position.copy(new THREE.Vector3(0, -this.semimajor_axis * this.eccentricity, 0).applyQuaternion(rotation).add(this.parent.getWorldPosition()));
if(select_obj && center_select)
this.orbit.position.sub(select_obj.getWorldPosition());
this.orbit.position.multiplyScalar(viewScale);
}
if(this.apoapsis){
// if eccentricity is zero or more than 1, apoapsis is not defined
if(this === select_obj && 0 < this.eccentricity && this.eccentricity < 1)
calcApsePosition(-1, this.apoapsis);
else
this.apoapsis.visible = false;
}
if(this.periapsis){
// if eccentricity is zero, periapsis is not defined
if(this === select_obj && 0 < this.eccentricity)
calcApsePosition(1, this.periapsis);
else
this.periapsis.visible = false;
}
}
for(var i = 0; i < this.children.length; i++){
var a = this.children[i];
a.update();
}
};
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.y = 300;
camera.position.z = 1000;
camera.up.set(0,0,1);
background = new THREE.Scene();
background.rotation.x = Math.PI / 2;
var loader = new THREE.TextureLoader();
loader.load( 'images/hipparcoscyl1.jpg', function ( texture ) {
var geometry = new THREE.SphereGeometry( 2, 20, 20 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5, depthTest: false, depthWrite: false, side: THREE.BackSide } );
material.depthWrite = false;
var mesh = new THREE.Mesh(geometry, material);
background.add(mesh);
} );
overlayCamera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, -1000, 1000 );
window.addEventListener('resize', function(){
overlayCamera.left = window.innerWidth / - 2;
overlayCamera.right = window.innerWidth / 2;
overlayCamera.top = window.innerHeight / 2;
overlayCamera.bottom = window.innerHeight / - 2;
overlayCamera.updateProjectionMatrix();
});
overlay = new THREE.Scene();
var loader = new THREE.TextureLoader();
loader.load( 'images/navball.png', function ( texture ) {
var geometry = new THREE.SphereGeometry( navballRadius, 20, 20 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5, depthTest: false, depthWrite: false } );
navballMesh = new THREE.Mesh(geometry, material);
overlay.add(navballMesh);
var spriteMaterial = new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture( "images/watermark.png" ),
depthTest: false,
depthWrite: false,
transparent: true,
});
var watermark = new THREE.Sprite(spriteMaterial);
watermark.scale.set(64, 32, 64);
navballMesh.add(watermark);
} );
var spriteGeometry = new THREE.PlaneGeometry( 40, 40 );
prograde = new THREE.Mesh(spriteGeometry,
new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture( "images/prograde.png" ),
color: 0xffffff,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false,
transparent: true,
} )
);
overlay.add(prograde);
retrograde = new THREE.Mesh(spriteGeometry,
new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture( "images/retrograde.png" ),
color: 0xffffff,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false,
transparent: true,
} )
);
overlay.add(retrograde);
scene = new THREE.Scene();
group = new THREE.Object3D();
scene.add( group );
var material = new THREE.ParticleSystemMaterial( { size: 0.1 } );
// Sun
var Rsun = 695800.;
var sgeometry = new THREE.SphereGeometry( Rsun / AU * viewScale, 20, 20 );
var sunMesh = new THREE.Mesh( sgeometry, material );
group.add( sunMesh );
// Sun light
light = new THREE.PointLight( 0xffffff, 1, 0, 1e-6 );
scene.add( light );
scene.add( new THREE.AmbientLight( 0x202020 ) );
var meshMaterial = new THREE.LineBasicMaterial({color: 0x3f3f3f});
var meshGeometry = new THREE.Geometry();
for(var x = -10; x <= 10; x++)
meshGeometry.vertices.push( new THREE.Vector3( -10, x, 0 ), new THREE.Vector3(10, x, 0));
for(var x = -10; x <= 10; x++)
meshGeometry.vertices.push( new THREE.Vector3( x, -10, 0 ), new THREE.Vector3(x, 10, 0));
grids = new THREE.Object3D();
var mesh = new THREE.LineSegments(meshGeometry, meshMaterial);
mesh.scale.x = mesh.scale.y = 100;
grids.add(mesh);
var mesh2 = new THREE.LineSegments(meshGeometry, meshMaterial);
mesh2.scale.x = mesh2.scale.y = 10000 / AU * 100;
grids.add(mesh2);
function addAxis(axisVector, color){
var axisXMaterial = new THREE.LineBasicMaterial({color: color});
var axisXGeometry = new THREE.Geometry();
axisXGeometry.vertices.push(new THREE.Vector3(0,0,0), axisVector);
var axisX = new THREE.Line(axisXGeometry, axisXMaterial);
axisX.scale.multiplyScalar(100);
grids.add(axisX);
}
addAxis(new THREE.Vector3(100,0,0), 0xff0000);
addAxis(new THREE.Vector3(0,100,0), 0x00ff00);
addAxis(new THREE.Vector3(0,0,100), 0x0000ff);
scene.add(grids);
var orbitMaterial = new THREE.LineBasicMaterial({color: 0x3f3f7f});
CelestialBody.prototype.orbitMaterial = orbitMaterial; // Default orbit material
selectedOrbitMaterial = new THREE.LineBasicMaterial({color: 0xff7fff});
var orbitGeometry = new THREE.Geometry();
var curve = new THREE.EllipseCurve(0, 0, 1, 1,
0, Math.PI * 2, false, 90);
var path = new THREE.Path( curve.getPoints( 256 ) );
var orbitGeometry = path.createPointsGeometry( 256 );
// Add a planet having desired orbital elements. Note that there's no way to specify anomaly (phase) on the orbit right now.
// It's a bit difficult to calculate in Newtonian dynamics simulation.
function AddPlanet(semimajor_axis, eccentricity, inclination, ascending_node, argument_of_perihelion, color, GM, parent, texture, radius, params, name){
var rotation = AxisAngleQuaternion(0, 0, 1, ascending_node - Math.PI / 2)
.multiply(AxisAngleQuaternion(0, 1, 0, Math.PI - inclination))
.multiply(AxisAngleQuaternion(0, 0, 1, argument_of_perihelion));
var group = new THREE.Object3D();
var ret = new CelestialBody(parent || sun, new THREE.Vector3(0, 1 - eccentricity, 0).multiplyScalar(semimajor_axis).applyQuaternion(rotation), group.position, color, GM, name);
ret.model = group;
ret.radius = radius;
scene.add( group );
if(texture){
var loader = new THREE.TextureLoader();
loader.load( texture || 'images/land_ocean_ice_cloud_2048.jpg', function ( texture ) {
var geometry = new THREE.SphereGeometry( 1, 20, 20 );
var material = new THREE.MeshLambertMaterial( { map: texture, color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 } );
var mesh = new THREE.Mesh( geometry, material );
var radiusInAu = viewScale * (radius || 6534) / AU;
mesh.scale.set(radiusInAu, radiusInAu, radiusInAu);
mesh.rotation.x = Math.PI / 2;
group.add( mesh );
} );
}
else if(params.modelName){
var loader = new THREE.OBJLoader();
loader.load( params.modelName, function ( object ) {
var radiusInAu = 100 * (radius || 6534) / AU;
object.scale.set(radiusInAu, radiusInAu, radiusInAu);
group.add( object );
} );
var blastGroup = new THREE.Object3D();
group.add(blastGroup);
blastGroup.visible = false;
blastGroup.position.x = -60 / AU;
ret.blastModel = blastGroup;
var spriteMaterial = new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture( "images/blast.png" ),
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true,
});
var blast = new THREE.Sprite(spriteMaterial);
blast.position.x = -30 / AU;
blast.scale.multiplyScalar(100 / AU);
blastGroup.add(blast);
var blast2 = new THREE.Sprite(spriteMaterial);
blast2.position.x = -60 / AU;
blast2.scale.multiplyScalar(50 / AU);
blastGroup.add(blast2);
var blast2 = new THREE.Sprite(spriteMaterial);
blast2.position.x = -80 / AU;
blast2.scale.multiplyScalar(30 / AU);
blastGroup.add(blast2);
}
if(params && params.controllable)
ret.controllable = params.controllable;
ret.soi = params && params.soi ? params.soi / AU : 0;
ret.apoapsis = new THREE.Sprite(new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture('images/apoapsis.png'),
transparent: true,
}));
ret.apoapsis.scale.set(16,16,16);
overlay.add(ret.apoapsis);
ret.periapsis = new THREE.Sprite(new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture('images/periapsis.png'),
transparent: true,
}));
ret.periapsis.scale.set(16,16,16);
overlay.add(ret.periapsis);
// Orbital speed at given position and eccentricity can be calculated by v = \sqrt(\mu (2 / r - 1 / a))
// https://en.wikipedia.org/wiki/Orbital_speed
ret.setOrbitingVelocity(semimajor_axis, rotation);
if(params && params.axialTilt && params.rotationPeriod){
ret.quaternion = AxisAngleQuaternion(1, 0, 0, params.axialTilt);
ret.angularVelocity = new THREE.Vector3(0, 0, 2 * Math.PI / params.rotationPeriod).applyQuaternion(ret.quaternion);
}
if(params && params.angularVelocity) ret.angularVelocity = params.angularVelocity;
if(params && params.quaternion) ret.quaternion = params.quaternion;
var orbitMesh = new THREE.Line(orbitGeometry, ret.orbitMaterial);
ret.orbit = orbitMesh;
scene.add(orbitMesh);
ret.init();
ret.update();
return ret;
}
sun = new CelestialBody(null, new THREE.Vector3(), null, 0xffffff, GMsun, "sun");
sun.radius = Rsun;
sun.model = group;
var mercury = AddPlanet(0.387098, 0.205630, 7.005 * rad_per_deg, 48.331 * rad_per_deg, 29.124 * rad_per_deg, 0x3f7f7f, 22032 / AU / AU / AU, sun, 'images/mercury.jpg', 2439.7, {soi: 2e5}, "mercury");
var venus = AddPlanet(0.723332, 0.00677323, 3.39458 * rad_per_deg, 76.678 * rad_per_deg, 55.186 * rad_per_deg, 0x7f7f3f, 324859 / AU / AU / AU, sun, 'images/venus.jpg', 6051.8, {soi: 5e5}, "mars");
// Earth is at 1 AU (which is the AU's definition) and orbits around the ecliptic.
var earth = AddPlanet(1, 0.0167086, 0, -11.26064 * rad_per_deg, 114.20783 * rad_per_deg, 0x3f7f3f, 398600 / AU / AU / AU, sun, 'images/land_ocean_ice_cloud_2048.jpg', 6534,
{axialTilt: 23.4392811 * rad_per_deg,
rotationPeriod: ((23 * 60 + 56) * 60 + 4.10),
soi: 5e5}, "earth");
var rocket = AddPlanet(10000 / AU, 0., 0, 0, 0, 0x3f7f7f, 100 / AU / AU / AU, earth, undefined, 0.1, {modelName: 'rocket.obj', controllable: true}, "rocket");
rocket.quaternion.multiply(AxisAngleQuaternion(1, 0, 0, Math.PI / 2)).multiply(AxisAngleQuaternion(0, 1, 0, Math.PI / 2));
var moon = AddPlanet(384399 / AU, 0.0167086, 0, -11.26064 * rad_per_deg, 114.20783 * rad_per_deg, 0x5f5f5f, 4904.8695 / AU / AU / AU, earth, 'images/moon.png', 1737.1, {soi: 1e5}, "moon");
var mars = AddPlanet(1.523679, 0.0935, 1.850 * rad_per_deg, 49.562 * rad_per_deg, 286.537 * rad_per_deg, 0x7f3f3f, 42828 / AU / AU / AU, sun, 'images/mars.jpg', 3389.5, {soi: 3e5}, "mars");
var jupiter = AddPlanet(5.204267, 0.048775, 1.305 * rad_per_deg, 100.492 * rad_per_deg, 275.066 * rad_per_deg, 0x7f7f3f, 126686534 / AU / AU / AU, sun, 'images/jupiter.jpg', 69911, {soi: 10e6}, "jupiter");
select_obj = rocket;
center_select = true;
camera.position.set(0.005, 0.003, 0.005);
// Use icosahedron instead of sphere to make it look like uniform
var asteroidGeometry = new THREE.IcosahedronGeometry( 1, 2 );
// Modulate the vertices randomly to make it look like an asteroid. Simplex noise is desirable.
for(var i = 0; i < asteroidGeometry.vertices.length; i++){
asteroidGeometry.vertices[i].multiplyScalar(0.3 * (Math.random() - 0.5) + 1);
}
// Recalculate normal vectors according to updated vertices
asteroidGeometry.computeFaceNormals();
asteroidGeometry.computeVertexNormals();
// Perlin noise is applied as detail texture.
// It's asynchrnonous because it's shared by multiple asteroids.
var asteroidTexture = THREE.ImageUtils.loadTexture('images/perlin.jpg');
asteroidTexture.wrapS = THREE.RepeatWrapping;
asteroidTexture.wrapT = THREE.RepeatWrapping;
asteroidTexture.repeat.set(4, 4);
var asteroidMaterial = new THREE.MeshLambertMaterial( {
map: asteroidTexture,
color: 0xffaf7f, shading: THREE.SmoothShading, overdraw: 0.5
} );
// Randomly generate asteroids
for ( i = 0; i < 10; i ++ ) {
var angle = Math.random() * Math.PI * 2;
var position = new THREE.Vector3();
position.x = 0.1 * (Math.random() - 0.5);
position.y = 0.1 * (Math.random() - 0.5) + 1;
position.z = 0.1 * (Math.random() - 0.5);
position.applyQuaternion(AxisAngleQuaternion(0, 0, 1, angle));
position.multiplyScalar(2.5);
var asteroid = new CelestialBody(sun, position);
asteroid.velocity = new THREE.Vector3((Math.random() - 0.5) * 0.3 - 1, (Math.random() - 0.5) * 0.3, (Math.random() - 0.5) * 0.3)
.multiplyScalar(Math.sqrt(GMsun / position.length())).applyQuaternion(AxisAngleQuaternion(0, 0, 1, angle));
asteroid.radius = Math.random() * 1 + 0.1;
// We need nested Object3D for NLIPS
asteroid.model = new THREE.Object3D();
// The inner Mesh object has scale determined by radius
var shape = new THREE.Mesh( asteroidGeometry, asteroidMaterial );
asteroid.model.add(shape);
var radiusInAu = viewScale * asteroid.radius / AU;
shape.scale.set(radiusInAu, radiusInAu, radiusInAu);
shape.up.set(0,0,1);
scene.add( asteroid.model );
var orbitMesh = new THREE.Line(orbitGeometry, asteroid.orbitMaterial);
asteroid.orbit = orbitMesh;
scene.add(orbitMesh);
asteroid.init();
asteroid.update();
}
renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0x000000 );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
cameraControls = new THREE.OrbitControls(camera, renderer.domElement);
cameraControls.target.set( 0, 0, 0);
cameraControls.noPan = true;
cameraControls.maxDistance = 4000;
cameraControls.minDistance = 1 / AU;
cameraControls.zoomSpeed = 5.;
cameraControls.update();
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
timescaleControl = new (function(){
function clickForward(number){
if(select_obj && 0 < select_obj.throttle){
messageControl.setText('You cannot timewarp while accelerating');
return;
}
for(var i = 0; i < forwards.length; i++)
forwards[i].src = i <= number ? 'images/forward.png' : 'images/forward-inactive.png';
text.innerHTML = 'Timescale: x' + series[number];
timescale = series[number];
timeIndex = number;
}
this.domElement = document.createElement('div');
this.domElement.style.position = 'absolute';
this.domElement.style.top = '50px';
this.domElement.style.background = '#7f7f7f';
this.domElement.style.zIndex = 10;
var forwards = [];
var series = [1, 5, 10, 100, 1e3, 1e4, 1e5, 1e6];
var timeIndex = 0;
for(var i = 0; i < series.length; i++){
var forward = document.createElement('img');
forward.src = i <= timeIndex ? 'images/forward.png' : 'images/forward-inactive.png';
forward.style.width = '15px';
forward.style.height = '20px';
forward.number = i;
forward.addEventListener('click', function(e){clickForward(this.number)});
this.domElement.appendChild(forward);
forwards.push(forward);
}
var text = document.createElement('div');
text.innerHTML = 'Timescale: x1';
this.domElement.appendChild(text);
var date = document.createElement('div');
this.domElement.appendChild(date);
this.setDate = function(text){
date.innerHTML = text;
}
this.increment = function(){
if(select_obj && 0 < select_obj.throttle){
messageControl.setText('You cannot timewarp while accelerating');
return;
}
if(timeIndex + 1 < series.length)
timeIndex++;
clickForward(timeIndex);
}
this.decrement = function(){
if(0 <= timeIndex - 1)
timeIndex--;
clickForward(timeIndex);
}
})();
container.appendChild( timescaleControl.domElement );
throttleControl = new (function(){
function updatePosition(pos){
if(1 < timescale && 0 < pos){
messageControl.setText('You cannot accelerate while timewarping');
return;
}
visualizePosition(pos);
}
function visualizePosition(pos){
var backRect = element.getBoundingClientRect();
var rect = throttleBack.getBoundingClientRect();
var handleRect = handle.getBoundingClientRect();
var max = rect.height - handleRect.height;
handle.style.top = (1 - pos) * max + (rect.top - backRect.top) + 'px';
if(select_obj.throttle === 0. && 0. < pos)
select_obj.ignitionCount++;
select_obj.throttle = pos;
if(select_obj && select_obj.blastModel){
select_obj.blastModel.visible = 0 < select_obj.throttle;
var size = (select_obj.throttle + 0.1) / 1.1;
select_obj.blastModel.scale.set(size, size, size);
}
}
function movePosition(event){
var rect = throttleBack.getBoundingClientRect();
var handleRect = handle.getBoundingClientRect();
var max = rect.height - handleRect.height;
var pos = Math.min(max, Math.max(0, (event.clientY - rect.top) - handleRect.height / 2));
updatePosition(1 - pos / max);
}
var guideHeight = 128;
var guideWidth = 32;
this.domElement = document.createElement('div');
this.domElement.style.position = 'absolute';
this.domElement.style.top = (window.innerHeight - guideHeight) + 'px';
this.domElement.style.left = (windowHalfX - navballRadius - guideWidth) + 'px';
this.domElement.style.background = '#7f7f7f';
this.domElement.style.zIndex = 10;
var element = this.domElement;
var dragging = false;
var scope = this;
var throttleMax = document.createElement('img');
throttleMax.src = 'images/throttle-max.png';
throttleMax.style.position = "absolute";
throttleMax.style.left = '0px';
throttleMax.style.top = '0px';
throttleMax.onmousedown = function(event){
scope.setThrottle(1);
};
throttleMax.ondragstart = function(event){
event.preventDefault();
};
this.domElement.appendChild(throttleMax);
var throttleBack = document.createElement('img');
throttleBack.src = 'images/throttle-back.png';
throttleBack.style.position = "absolute";
throttleBack.style.left = '0px';
throttleBack.style.top = '25px';
throttleBack.onmousedown = function(event){
dragging = true;
movePosition(event);
};
throttleBack.onmousemove = function(event){
if(dragging && event.buttons & 1)
movePosition(event);
};
throttleBack.onmouseup = function(event){
dragging = false;
}
throttleBack.draggable = true;
throttleBack.ondragstart = function(event){
event.preventDefault();
};
this.domElement.appendChild(throttleBack);
var throttleMin = document.createElement('img');
throttleMin.src = 'images/throttle-min.png';
throttleMin.style.position = "absolute";
throttleMin.style.left = '0px';
throttleMin.style.top = '106px';
throttleMin.onmousedown = function(event){
scope.setThrottle(0);
};
throttleMin.ondragstart = function(event){
event.preventDefault();
};
this.domElement.appendChild(throttleMin);
var handle = document.createElement('img');
handle.src = 'images/throttle-handle.png';
handle.style.position = 'absolute';
handle.style.top = (guideHeight - 16) + 'px';
handle.style.left = '0px';
handle.onmousemove = throttleBack.onmousemove;
handle.onmousedown = throttleBack.onmousedown;
handle.onmouseup = throttleBack.onmouseup;
handle.ondragstart = throttleBack.ondragstart;
this.domElement.appendChild(handle);
this.increment = function(delta){
if(select_obj)
updatePosition(Math.min(1, select_obj.throttle + delta));
}
this.decrement = function(delta){
if(select_obj)
updatePosition(Math.max(0, select_obj.throttle - delta));
}
this.setThrottle = function(value){
updatePosition(value);
}
window.addEventListener('resize', function(){
element.style.top = (window.innerHeight - guideHeight) + 'px';
element.style.left = (window.innerWidth / 2 - navballRadius - guideWidth) + 'px';
});
window.addEventListener('load', function(){
visualizePosition(select_obj.throttle);
});
})();
container.appendChild( throttleControl.domElement );
var rotationControl = new (function(){
function setSize(){
rootElement.style.top = (window.innerHeight - 2 * navballRadius) + 'px';
rootElement.style.left = (window.innerWidth / 2 - navballRadius) + 'px';
}
function absorbEvent_(event) {
var e = event || window.event;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
function addArrow(src, key, left, top){
var button = document.createElement('img');
button.src = src;
button.width = buttonWidth;
button.height = buttonHeight;
button.style.position = 'absolute';
button.style.top = top + 'px';
button.style.left = left + 'px';
button.onmousedown = function(event){
buttons[key] = true;
};
button.onmouseup = function(event){
buttons[key] = false;
button.style.boxShadow = '';
}
button.ondragstart = function(event){
event.preventDefault();
};
button.ontouchstart = function(event){
buttons[key] = true;
event.preventDefault();
event.stopPropagation();
};
button.ontouchmove = absorbEvent_;
button.ontouchend = function(event){
buttons[key] = false;
button.style.boxShadow = '';
event.preventDefault();
event.stopPropagation();
};
button.ontouchcancel = absorbEvent_;
element.appendChild(button);
}
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var rootElement = this.domElement;
this.domElement.style.position = 'absolute';
this.domElement.style.width = (navballRadius * 2) + 'px';
this.domElement.style.height = (navballRadius * 2) + 'px';
setSize();
this.domElement.style.zIndex = 5;
// Introduce internal 'div' because the outer 'div' cannot be
// hidden since it need to receive mouseenter event.
var element = document.createElement('div');
element.style.width = '100%';
element.style.height = '100%';
element.style.display = 'none';
this.domElement.appendChild(element);
this.domElement.onmouseenter = function(event){
element.style.display = 'block';
};
this.domElement.onmouseleave = function(event){
element.style.display = 'none';
up = down = left = right = false;
};
addArrow('images/rotate-up.png', 'up', navballRadius - buttonWidth / 2, 0);
addArrow('images/rotate-down.png', 'down', navballRadius - buttonWidth / 2, 2 * navballRadius - buttonHeight);
addArrow('images/rotate-left.png', 'left', 0, navballRadius - buttonHeight / 2);
addArrow('images/rotate-right.png', 'right', 2 * navballRadius - buttonWidth, navballRadius - buttonHeight / 2);
addArrow('images/rotate-cw.png', 'clockwise', 2 * navballRadius - buttonWidth, 0);
addArrow('images/rotate-ccw.png', 'counterclockwise', 0, 0);
window.addEventListener('resize', setSize);
})();
container.appendChild( rotationControl.domElement );
speedControl = new (function(){
function setSize(){
element.style.top = (window.innerHeight - 2 * navballRadius - 32) + 'px';
element.style.left = (window.innerWidth / 2 - element.getBoundingClientRect().width / 2) + 'px';
}
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
setSize();
element.style.zIndex = 7;
element.style.background = 'rgba(0, 0, 0, 0.5)';
window.addEventListener('resize', setSize);
var title = document.createElement('div');
title.innerHTML = 'Orbit';
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
this.setSpeed = function(){
if(select_obj){
var value = select_obj.velocity.length() * AU;
if(value < 1)
valueElement.innerHTML = (value * 1000).toFixed(4) + 'm/s';
else
valueElement.innerHTML = value.toFixed(4) + 'km/s';
}
else
valueElement.innerHTML = '';
element.style.left = (window.innerWidth / 2 - element.getBoundingClientRect().width / 2) + 'px';
}
})();
container.appendChild( speedControl.domElement );
orbitalElementControl = new (function(){
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = 120 + 'px';
element.style.left = 0 + 'px';
element.style.zIndex = 7;
var visible = false;
var icon = document.createElement('img');
icon.src = 'images/orbitIcon.png';
element.appendChild(icon);
var title = document.createElement('div');
title.innerHTML = 'Orbital Elements';
title.style.display = 'none';
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
valueElement.id = 'orbit';
valueElement.style.display = 'none';
// Register event handlers
icon.ondragstart = function(event){
event.preventDefault();
};
icon.onclick = function(event){
visible = !visible;
if(visible){
valueElement.style.display = 'block';
element.style.background = 'rgba(0, 0, 0, 0.5)';
}
else{
valueElement.style.display = 'none';
element.style.background = 'rgba(0, 0, 0, 0)';
}
};
icon.onmouseenter = function(event){
if(!visible)
title.style.display = 'block';
};
icon.onmouseleave = function(event){
if(!visible)
title.style.display = 'none';
};
this.setText = function(text){
valueElement.innerHTML = text;
}
})();
container.appendChild( orbitalElementControl.domElement );
function rightTitleSetSize(title, icon){
var r = title.getBoundingClientRect();
var iconRect = icon.getBoundingClientRect()
title.style.top = (iconRect.height - r.height) + 'px';
title.style.right = iconRect.width + 'px';
}
statsControl = new (function(){
function setSize(){
element.style.left = (window.innerWidth - buttonWidth) + 'px';
rightTitleSetSize(title, icon);
}
var buttonTop = 120;
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = buttonTop + 'px';
element.style.left = 0 + 'px';
element.style.zIndex = 7;
var visible = false;
var icon = document.createElement('img');
icon.src = 'images/statsIcon.png';
icon.style.width = buttonWidth + 'px';
icon.style.height = buttonHeight + 'px';
element.appendChild(icon);
var title = document.createElement('div');
title.innerHTML = 'Statistics';
title.style.display = 'none';
title.style.position = 'absolute';
title.style.top = buttonTop + 'px';
title.style.background = 'rgba(0, 0, 0, 0.5)';
title.style.zIndex = 20;
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
valueElement.style.display = 'none';
valueElement.style.position = 'absolute';
valueElement.style.background = 'rgba(0, 0, 0, 0.5)';
valueElement.style.border = '3px ridge #7f3f3f';
valueElement.style.padding = '3px';
var valueElements = [];
for(var i = 0; i < 3; i++){
var titleElement = document.createElement('div');
titleElement.innerHTML = ['Mission Time', 'Delta-V', 'Ignition Count'][i];
titleElement.style.fontWeight = 'bold';
titleElement.style.paddingRight = '1em';
valueElement.appendChild(titleElement);
var valueElementChild = document.createElement('div');
valueElementChild.style.textAlign = 'right';
valueElements.push(valueElementChild);
valueElement.appendChild(valueElementChild);
}
setSize();
// Register event handlers
window.addEventListener('resize', setSize);
icon.ondragstart = function(event){
event.preventDefault();
};
icon.onclick = function(event){
visible = !visible;
if(visible){
valueElement.style.display = 'block';
element.style.background = 'rgba(0, 0, 0, 0.5)';
}
else{
valueElement.style.display = 'none';
element.style.background = 'rgba(0, 0, 0, 0)';
settingsControl.domElement.style.top = element.getBoundingClientRect().bottom + 'px';
}
};
icon.onmouseenter = function(event){
if(!visible)
title.style.display = 'block';
rightTitleSetSize(title, icon);
};
icon.onmouseleave = function(event){
if(!visible)
title.style.display = 'none';
};
this.setText = function(text){
if(!visible)
return;
if(!select_obj){
valueElements[3].innerHTML = valueElements[2] = '';
return;
}
var totalSeconds = (simTime.getTime() - startTime.getTime()) / 1e3;
var seconds = Math.floor(totalSeconds) % 60;
var minutes = Math.floor(totalSeconds / 60) % 60;
var hours = Math.floor(totalSeconds / 60 / 60) % 24;
var days = Math.floor(totalSeconds / 60 / 60 / 24);
valueElements[0].innerHTML = days + 'd ' + zerofill(hours) + ':' + zerofill(minutes) + ':' + zerofill(seconds);
var deltaVkm = select_obj.totalDeltaV * AU;
var deltaV;
if(deltaVkm < 10)
deltaV = (deltaVkm * 1e3).toFixed(1) + 'm/s';
else
deltaV = deltaVkm.toFixed(4) + 'km/s';
valueElements[1].innerHTML = deltaV;
valueElements[2].innerHTML = select_obj.ignitionCount;
valueElement.style.marginLeft = (buttonWidth - valueElement.getBoundingClientRect().width) + 'px';
settingsControl.domElement.style.top = valueElement.getBoundingClientRect().bottom + 'px';
}
})();
container.appendChild( statsControl.domElement );
settingsControl = new (function(){
function setSize(){
element.style.left = (window.innerWidth - buttonWidth) + 'px';
rightTitleSetSize(title, icon);
}
var buttonTop = 154;
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = buttonTop + 'px';
element.style.left = 0 + 'px';
element.style.zIndex = 7;
var visible = false;
var icon = document.createElement('img');
icon.src = 'images/settingsIcon.png';
icon.style.width = buttonWidth + 'px';
icon.style.height = buttonHeight + 'px';
element.appendChild(icon);
var title = document.createElement('div');
title.innerHTML = 'Settings';
title.style.display = 'none';
title.style.position = 'absolute';
title.style.background = 'rgba(0, 0, 0, 0.5)';
title.style.zIndex = 20;
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
valueElement.style.display = 'none';
valueElement.style.position = 'absolute';
valueElement.style.background = 'rgba(0, 0, 0, 0.5)';
valueElement.style.border = '3px ridge #7f3f3f';
valueElement.style.padding = '3px';
// The settings variables are function local variables, so we can't just pass this pointer
// and parameter name and do something like `this[name] = !this[name]`.
var toggleFuncs = [
function(){grid_enable = !grid_enable},
function(){sync_rotate = !sync_rotate},
function(){nlips_enable = !nlips_enable},
function(){units_km = !units_km}
];
var checkElements = [];
for(var i = 0; i < toggleFuncs.length; i++){
var lineElement = document.createElement('div');
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.onclick = toggleFuncs[i];
var id = 'settings_check_' + i;
checkbox.setAttribute('id', id);
lineElement.appendChild(checkbox);
checkElements.push(checkbox);
var label = document.createElement('label');
label.setAttribute('for', id);
label.innerHTML = [
'Show grid (G)',
'Chase camera (H)',
'Nonlinear scale (N)',
'Units in KM (K)'][i];
lineElement.appendChild(label);
lineElement.style.fontWeight = 'bold';
lineElement.style.paddingRight = '1em';
lineElement.style.whiteSpace = 'nowrap';
valueElement.appendChild(lineElement);
}
setSize();
// Register event handlers
window.addEventListener('resize', setSize);
icon.ondragstart = function(event){
event.preventDefault();
};
icon.onclick = function(event){
visible = !visible;
if(visible){
valueElement.style.display = 'block';
element.style.background = 'rgba(0, 0, 0, 0.5)';
}
else{
valueElement.style.display = 'none';
element.style.background = 'rgba(0, 0, 0, 0)';
}
};
icon.onmouseenter = function(event){
if(!visible)
title.style.display = 'block';
rightTitleSetSize(title, icon);
};
icon.onmouseleave = function(event){
if(!visible)
title.style.display = 'none';
};
this.setText = function(text){
if(!visible)
return;
checkElements[0].checked = grid_enable;
checkElements[1].checked = sync_rotate;
checkElements[2].checked = nlips_enable;
checkElements[3].checked = units_km;
valueElement.style.marginLeft = (buttonWidth - valueElement.getBoundingClientRect().width) + 'px';
}
})();
container.appendChild( settingsControl.domElement );
altitudeControl = new (function(){
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.top = '2em';
element.style.left = '50%';
element.style.background = 'rgba(0,0,0,0.5)';
element.style.zIndex = 8;
var visible = false;
// Register event handlers
element.ondragstart = function(event){
event.preventDefault();
};
this.setText = function(value){
var text;
if(value < 1e5)
text = value.toFixed(4) + 'km';
else if(value < 1e8)
text = (value / 1000).toFixed(4) + 'Mm';
else
text = (value / AU).toFixed(4) + 'AU';
element.innerHTML = text;
element.style.marginLeft = -element.getBoundingClientRect().width / 2 + 'px';
};
})();
container.appendChild( altitudeControl.domElement );
messageControl = new (function(){
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.top = '25%';
element.style.left = '50%';
element.style.fontSize = '20px';
element.style.fontWeight = 'bold';
element.style.textShadow = '0px 0px 5px rgba(0,0,0,1)';
element.style.zIndex = 20;
var showTime = 0;
// Register event handlers
element.ondragstart = function(event){
event.preventDefault();
};
// Disable text selection
element.onselectstart = function(){ return false; }
this.setText = function(text){
element.innerHTML = text;
element.style.display = 'block';
element.style.opacity = '1';
element.style.marginTop = -element.getBoundingClientRect().height / 2 + 'px';
element.style.marginLeft = -element.getBoundingClientRect().width / 2 + 'px';
showTime = 5; // Seconds to show should depend on text length!
};
this.timeStep = function(deltaTime){
if(showTime < deltaTime){
element.style.display = 'none';
showTime = 0;
return;
}
showTime -= deltaTime;
if(showTime < 2);
element.style.opacity = (showTime / 2).toString();
}
})
container.appendChild( messageControl.domElement );
function MenuControl(titleString, iconSrc, config){
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = config.buttonTop + 'px';
element.style.right = 0 + 'px';
element.style.zIndex = 7;
this.icon = document.createElement('img');
this.icon.src = iconSrc;
this.icon.style.width = config.buttonWidth + 'px';
this.icon.style.height = config.buttonHeight + 'px';
var scope = this;
this.iconMouseOver = false;
this.icon.ondragstart = function(event){
event.preventDefault();
};
this.icon.onclick = function(event){
scope.setVisible(!scope.visible);
};
this.icon.onmouseenter = function(event){
if(!scope.visible)
scope.title.style.display = 'block';
rightTitleSetSize(scope.title, scope.icon);
scope.iconMouseOver = true;
};
this.icon.onmouseleave = function(event){
if(!scope.visible)
scope.title.style.display = 'none';
scope.iconMouseOver = false;
};
element.appendChild(this.icon);
var title = document.createElement('div');
title.innerHTML = titleString;
title.style.display = 'none';
title.style.position = 'absolute';
title.style.background = 'rgba(0, 0, 0, 0.5)';
title.style.zIndex = 20;
element.appendChild(title);
this.title = title;
this.visible = false;
var valueElement = document.createElement('div');
valueElement.style.cssText = "display: none; position: fixed; left: 50%;"
+ "width: 300px; top: 50%; background-color: rgba(0,0,0,0.85); border: 5px ridge #7fff7f;"
+ "font-size: 15px; text-align: center";
this.valueElement = valueElement;
var titleElem = document.createElement('div');
titleElem.style.margin = "15px";
titleElem.style.padding = "15px";
titleElem.style.fontSize = '25px';
titleElem.innerHTML = config.innerTitle || titleString;
this.valueElement.appendChild(titleElem);
this.domElement.appendChild(this.valueElement);
};
MenuControl.prototype.setVisible = function(v){
this.visible = v;
if(this.visible){
this.valueElement.style.display = 'block';
var rect = this.valueElement.getBoundingClientRect();
this.valueElement.style.marginLeft = -rect.width / 2 + "px";
this.valueElement.style.marginTop = -rect.height / 2 + "px";
}
else{
this.valueElement.style.display = 'none';
if(!this.iconMouseOver)
this.title.style.display = 'none';
}
};
scenarioSelectorControl = new (function(){
var config = {
buttonTop: 0,
buttonHeight: 32,
buttonWidth: 32,
innerTitle: "Scenario Selector",
};
var scope = this;
MenuControl.call(this, 'Scenarios', 'images/menuIcon.png', config);
this.valueElement.style.border = "5px ridge #ffff7f";
var scenarios = [
{title: "Earth orbit", parent: earth, semimajor_axis: 10000 / AU},
{title: "Moon orbit", parent: moon, semimajor_axis: 3000 / AU},
{title: "Mars orbit", parent: mars, semimajor_axis: 5000 / AU},
{title: "Venus orbit", parent: venus, semimajor_axis: 10000 / AU, ascending_node: Math.PI},
{title: "Jupiter orbit", parent: jupiter, semimajor_axis: 100000 / AU},
];
for(var i = 0; i < scenarios.length; i++){
var elem = document.createElement('div');
elem.style.margin = "15px";
elem.style.padding = "15px";
elem.style.border = "1px solid #ffff00";
elem.innerHTML = scenarios[i].title;
elem.onclick = (function(scenario){
return function(){
var ascending_node = scenario.ascending_node || 0.;
var eccentricity = scenario.eccentricity || 0.;
var rotation = scenario.rotation || (function(){
var rotation = AxisAngleQuaternion(0, 0, 1, ascending_node - Math.PI / 2);
rotation.multiply(AxisAngleQuaternion(0, 1, 0, Math.PI));
return rotation;
})();
rocket.setParent(scenario.parent);
rocket.position = new THREE.Vector3(0, 1 - eccentricity, 0)
.multiplyScalar(scenario.semimajor_axis).applyQuaternion(rotation);
rocket.quaternion = rotation.clone();
rocket.quaternion.multiply(AxisAngleQuaternion(1, 0, 0, -Math.PI / 2));
rocket.angularVelocity = new THREE.Vector3();
throttleControl.setThrottle(0);
rocket.setOrbitingVelocity(scenario.semimajor_axis, rotation);
messageControl.setText('Scenario ' + scenario.title + ' Loaded!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
}
})(scenarios[i]);
this.valueElement.appendChild(elem);
}
this.setVisible = function(v){
MenuControl.prototype.setVisible.call(this, v);
if(this.visible){
[saveControl, loadControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
}
}
});
container.appendChild( scenarioSelectorControl.domElement );
saveControl = new (function(){
var config = {
buttonTop: 34,
buttonHeight: 32,
buttonWidth: 32,
};
var scope = this;
MenuControl.call(this, 'Save data', 'images/saveIcon.png', config);
var inputContainer = document.createElement('div');
inputContainer.style.border = "1px solid #7fff7f";
inputContainer.style.margin = "5px";
inputContainer.style.padding = "5px";
var inputTitle = document.createElement('div');
inputTitle.innerHTML = 'New Save Name';
var inputElement = document.createElement('input');
inputElement.setAttribute('type', 'text');
var inputButton = document.createElement('button');
inputButton.innerHTML = 'save'
inputButton.onclick = function(event){
var saveData = localStorage.getItem('WebGLOrbiterSavedData') ? JSON.parse(localStorage.getItem('WebGLOrbiterSavedData')) : [];
saveData.push({title: inputElement.value, state: rocket.serialize()});
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Saved!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
};
inputElement.onkeydown = function(e){
e.stopPropagation();
}
inputContainer.appendChild(inputTitle);
inputContainer.appendChild(inputElement);
inputContainer.appendChild(inputButton);
this.valueElement.appendChild(inputContainer);
var saveContainer = document.createElement('div');
function updateSaveDataList(){
while(0 < saveContainer.children.length) saveContainer.removeChild(saveContainer.children[0]);
var saveData = localStorage.getItem('WebGLOrbiterSavedData') ? JSON.parse(localStorage.getItem('WebGLOrbiterSavedData')) : [];
for(var i = 0; i < saveData.length; i++){
var elem = document.createElement('div');
elem.style.margin = "5px";
elem.style.padding = "5px";
elem.style.border = "1px solid #00ff00";
var labelElem = document.createElement('div');
labelElem.innerHTML = saveData[i].title;
labelElem.style.cssText = "width: 100%; margin-right: -32px; display: inline-block; text-align: overflow: auto;";
elem.appendChild(labelElem);
var deleteElem = document.createElement('img');
deleteElem.setAttribute('src', 'images/trashcan.png');
deleteElem.style.width = '32px';
deleteElem.onclick = (function(i){
return function(e){
saveData.splice(i, 1);
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Deleted!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
e.stopPropagation();
}
})(i);
elem.appendChild(deleteElem);
elem.onclick = (function(save){
return function(){
save.state = rocket.serialize();
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Saved!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
}
})(saveData[i]);
saveContainer.appendChild(elem);
}
}
this.valueElement.appendChild(saveContainer);
this.setVisible = function(v){
MenuControl.prototype.setVisible.call(this, v);
if(this.visible){
[scenarioSelectorControl, loadControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
updateSaveDataList();
}
}
});
container.appendChild( saveControl.domElement );
loadControl = new (function(){
var config = {
buttonTop: 34 * 2,
buttonHeight: 32,
buttonWidth: 32,
};
MenuControl.call(this, 'Load data', 'images/loadIcon.png', config);
var scope = this;
this.valueElement.style.border = "5px ridge #ff7fff";
var saveContainer = document.createElement('div');
function updateSaveDataList(){
while(0 < saveContainer.children.length) saveContainer.removeChild(saveContainer.children[0]);
var saveData = localStorage.getItem('WebGLOrbiterSavedData') ? JSON.parse(localStorage.getItem('WebGLOrbiterSavedData')) : [];
for(var i = 0; i < saveData.length; i++){
var elem = document.createElement('div');
elem.style.margin = "5px";
elem.style.padding = "5px";
elem.style.border = "1px solid #ffff00";
var labelElem = document.createElement('div');
labelElem.innerHTML = saveData[i].title;
labelElem.style.cssText = "width: 100%; margin-right: -32px; display: inline-block; text-align: overflow: auto;";
elem.appendChild(labelElem);
var deleteElem = document.createElement('img');
deleteElem.setAttribute('src', 'images/trashcan.png');
deleteElem.style.width = '32px';
deleteElem.onclick = (function(i){
return function(e){
saveData.splice(i, 1);
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Deleted!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
e.stopPropagation();
}
})(i);
elem.appendChild(deleteElem);
elem.onclick = (function(save){
return function(){
rocket.deserialize(save.state);
throttleControl.setThrottle(rocket.throttle);
messageControl.setText('Game State Loaded!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
}
})(saveData[i]);
saveContainer.appendChild(elem);
}
}
this.valueElement.appendChild(saveContainer);
this.setVisible = function(v){
MenuControl.prototype.setVisible.call(this, v);
if(scope.visible){
[scenarioSelectorControl, saveControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
updateSaveDataList();
}
}
});
container.appendChild( loadControl.domElement );
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener( 'keydown', onKeyDown, false );
window.addEventListener( 'keyup', onKeyUp, false );
// Start the clock after the initialization is finished, otherwise
// the very first frame of simulation can be long.
simTime = new Date();
realTime = simTime;
startTime = simTime;
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
// Fills leading zero if the value is less than 10, making the returned string always two characters long.
// Note that values not less than 100 or negative values are not guaranteed to be two characters wide.
// This function is for date time formatting purpose only.
function zerofill(v){
if(v < 10)
return "0" + v;
else
return v;
}
function render() {
var now = new Date();
var realDeltaTimeMilliSec = now.getTime() - realTime.getTime();
var time = new Date(simTime.getTime() + realDeltaTimeMilliSec * timescale);
var deltaTime = (time.getTime() - simTime.getTime()) * 1e-3;
realTime = now;
simTime = time;
timescaleControl.setDate(time.getFullYear() + '/' + zerofill(time.getMonth() + 1) + '/' + zerofill(time.getDate())
+ ' ' + zerofill(time.getHours()) + ':' + zerofill(time.getMinutes()) + ':' + zerofill(time.getSeconds()));
speedControl.setSpeed();
statsControl.setText();
settingsControl.setText();
messageControl.timeStep(realDeltaTimeMilliSec * 1e-3);
camera.near = Math.min(1, cameraControls.target.distanceTo(camera.position) / 10);
camera.updateProjectionMatrix();
var acceleration = 5e-10;
var div = 100; // We should pick subdivide simulation step count by angular speed!
function simulateBody(parent){
var children = parent.children;
for(var i = 0; i < children.length;){
var a = children[i];
var sl = a.position.lengthSq();
if(sl !== 0){
var angleAcceleration = 1e-0;
var accel = a.position.clone().negate().normalize().multiplyScalar(deltaTime / div * a.parent.GM / sl);
if(select_obj === a && select_obj.controllable && timescale <= 1){
if(buttons.up) select_obj.angularVelocity.add(new THREE.Vector3(0, 0, 1).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.down) select_obj.angularVelocity.add(new THREE.Vector3(0, 0, -1).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.left) select_obj.angularVelocity.add(new THREE.Vector3(0, 1, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.right) select_obj.angularVelocity.add(new THREE.Vector3(0, -1, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.counterclockwise) select_obj.angularVelocity.add(new THREE.Vector3(1, 0, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.clockwise) select_obj.angularVelocity.add(new THREE.Vector3(-1, 0, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(!buttons.up && !buttons.down && !buttons.left && !buttons.right && !buttons.counterclockwise && !buttons.clockwise){
// Immediately stop micro-rotation if the body is controlled.
// This is done to make it still in larger timescale, since micro-rotation cannot be canceled
// by product of angularVelocity and quaternion which underflows by square.
// Think that the vehicle has a momentum wheels that cancels micro-rotation continuously working.
if(1e-6 < select_obj.angularVelocity.lengthSq())
select_obj.angularVelocity.add(select_obj.angularVelocity.clone().normalize().multiplyScalar(-angleAcceleration * deltaTime / div));
else
select_obj.angularVelocity.set(0, 0, 0);
}
if(0 < select_obj.throttle){
var deltaV = acceleration * select_obj.throttle * deltaTime / div;
select_obj.velocity.add(new THREE.Vector3(1, 0, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(deltaV));
select_obj.totalDeltaV += deltaV;
}
}
var dvelo = accel.clone().multiplyScalar(0.5);
var vec0 = a.position.clone().add(a.velocity.clone().multiplyScalar(deltaTime / div / 2.));
var accel1 = vec0.clone().negate().normalize().multiplyScalar(deltaTime / div * a.parent.GM / vec0.lengthSq());
var velo1 = a.velocity.clone().add(dvelo);
a.velocity.add(accel1);
a.position.add(velo1.multiplyScalar(deltaTime / div));
if(0 < a.angularVelocity.lengthSq()){
var axis = a.angularVelocity.clone().normalize();
// We have to multiply in this order!
a.quaternion.multiplyQuaternions(AxisAngleQuaternion(axis.x, axis.y, axis.z, a.angularVelocity.length() * deltaTime / div), a.quaternion);
}
}
// Only controllable objects can change orbiting body
if(a.controllable){
// Check if we are leaving sphere of influence of current parent.
if(a.parent.parent && a.parent.soi && a.parent.soi * 1.01 < a.position.length()){
a.position.add(parent.position);
a.velocity.add(parent.velocity);
var j = children.indexOf(a);
if(0 <= j)
children.splice(j, 1);
a.parent = parent.parent;
a.parent.children.push(a);
continue; // Continue but not increment i
}
var skip = false;
// Check if we are entering sphere of influence of another sibling.
for(var j = 0; j < children.length; j++){
var aj = children[j];
if(aj === a)
continue;
if(!aj.soi)
continue;
if(aj.position.distanceTo(a.position) < aj.soi * .99){
a.position.sub(aj.position);
a.velocity.sub(aj.velocity);
var k = children.indexOf(a);
if(0 <= k)
children.splice(k, 1);
a.parent = aj;
aj.children.push(a);
skip = true;
break;
}
}
if(skip)
continue; // Continue but not increment i
}
simulateBody(a);
i++;
}
}
for(var d = 0; d < div; d++){
// Allow trying to increase throttle when timewarping in order to show the message
if(accelerate) throttleControl.increment(deltaTime / div);
if(decelerate) throttleControl.decrement(deltaTime / div);
simulateBody(sun);
}
sun.update();
var irotate = AxisAngleQuaternion(-1, 0, 0, Math.PI / 2);
// offset sun position
light.position.copy(sun.model.position);
grids.visible = grid_enable;
// camera.up.copy(new THREE.Vector3(0,0,1)); // This did't work with OrbitControls
cameraControls.update();
var oldPosition = camera.position.clone();
var oldQuaternion = camera.quaternion.clone();
if(sync_rotate && select_obj){
camera.quaternion.copy(
select_obj.quaternion.clone()
.multiply(AxisAngleQuaternion(0, 1, 0, -1*Math.PI / 2)));
camera.position.copy(new THREE.Vector3(0, 0.2, 1).normalize().multiplyScalar(camera.position.length()).applyQuaternion(camera.quaternion));
}
var position = camera.position.clone();
camera.position.set(0,0,0);
renderer.render( background, camera);
camera.position.copy(position);
renderer.render( scene, camera );
if(navballMesh && select_obj && select_obj.controllable){
// First, calculate the quaternion for rotating the system so that
// X axis points north, Y axis points east and Z axis points zenith.
var north = new THREE.Vector3(0, 0, 1).applyQuaternion(select_obj.parent.quaternion);
var tangent = north.cross(select_obj.position).normalize();
var qball = new THREE.Quaternion();
var mat = new THREE.Matrix4();
var normal = select_obj.position.clone().normalize().negate();
mat.makeBasis(tangent.clone().cross(normal), tangent, normal);
qball.setFromRotationMatrix (mat);
navballMesh.quaternion.copy(
AxisAngleQuaternion(0, 1, 0, -1*Math.PI / 2)
.multiply(AxisAngleQuaternion(0, 0, 1, Math.PI))
.multiply(select_obj.quaternion.clone().conjugate())
.multiply(qball)
.multiply(AxisAngleQuaternion(1, 0, 0, Math.PI / 2))
);
navballMesh.position.y = -window.innerHeight / 2 + navballRadius;
var grade;
var factor;
if(new THREE.Vector3(1, 0, 0).applyQuaternion(select_obj.quaternion).dot(select_obj.velocity) < 0){
grade = retrograde;
prograde.visible = false;
factor = -1.;
}
else{
grade = prograde;
retrograde.visible = false;
factor = 1.;
}
grade.visible = true;
grade.position.y = -window.innerHeight / 2 + navballRadius + factor * new THREE.Vector3(0, 1, 0).applyQuaternion(select_obj.quaternion).dot(select_obj.velocity) / select_obj.velocity.length() * navballRadius;
grade.position.x = factor * new THREE.Vector3(0, 0, 1).applyQuaternion(select_obj.quaternion).dot(select_obj.velocity) / select_obj.velocity.length() * navballRadius;
camera.position.set(0,0,0);
camera.quaternion.set(1,0,0,0);
renderer.render( overlay, overlayCamera);
}
// Restore the original state because cameraControls expect these variables unchanged
camera.quaternion.copy(oldQuaternion);
camera.position.copy(oldPosition);
if(select_obj && select_obj.parent){
altitudeControl.setText(select_obj.position.length() * AU - select_obj.parent.radius);
}
else
altitudeControl.setText(0);
}
function onKeyDown( event ) {
var char = String.fromCharCode(event.which || event.keyCode).toLowerCase();
switch ( char ) {
case 'i':
if(select_obj === null)
select_obj = sun.children[0];
else{
// Some objects do not have an orbit
if(select_obj.orbit)
select_obj.orbit.material = select_obj.orbitMaterial;
var objs = select_obj.children;
if(0 < objs.length){
select_obj = objs[0];
}
else{
var selected = false;
var prev = select_obj;
for(var parent = select_obj.parent; parent; parent = parent.parent){
objs = parent.children;
for(var i = 0; i < objs.length; i++){
var o = objs[i];
if(o === prev && i + 1 < objs.length){
select_obj = objs[i+1];
selected = true;
break;
}
}
if(selected)
break;
prev = parent;
}
if(!parent)
select_obj = sun;
}
}
if(select_obj.orbit)
select_obj.orbit.material = selectedOrbitMaterial;
break;
case 'c':
center_select = !center_select;
break;
case 'n': // toggle NLIPS
nlips_enable = !nlips_enable;
break;
case 'g':
grid_enable = !grid_enable;
break;
case 'h':
sync_rotate = !sync_rotate;
break;
case 'k':
units_km = !units_km;
break;
}
if(select_obj && select_obj.controllable) switch( char ){
case 'w': // prograde
buttons.up = true;
// prograde = true;
break;
case 's': // retrograde
buttons.down = true;
// retrograde = true;
break;
case 'q': // normal
buttons.counterclockwise = true;
// normal = true;
break;
case 'e': // normal negative
buttons.clockwise = true;
// antinormal = true;
break;
case 'a': // orbit plane normal
buttons.left = true;
// incline = true;
break;
case 'd': // orbit plane normal negative
buttons.right = true;
// antiincline = true;
break;
case 'z':
throttleControl.setThrottle(1);
break;
case 'x':
throttleControl.setThrottle(0);
break;
}
// Annoying browser incompatibilities
var code = event.which || event.keyCode;
// Also support numpad plus and minus
if(code === 107 || code === 187 && event.shiftKey)
timescaleControl.increment();
if(code === 109 || code === 189)
timescaleControl.decrement();
if(code === 16)
accelerate = true;
if(code === 17)
decelerate = true;
}
function onKeyUp( event ) {
switch ( String.fromCharCode(event.which || event.keyCode).toLowerCase() ) {
case 'w': // prograde
buttons.up = false;
// prograde = false;
break;
case 's':
buttons.down = false;
// retrograde = false;
break;
case 'q': // prograde
buttons.counterclockwise = false;
// normal = false;
break;
case 'e':
buttons.clockwise = false;
// antinormal = false;
break;
case 'a': // orbit plane normal
buttons.left = false;
// incline = false;
break;
case 'd': // orbit plane normal negative
buttons.right = false;
// antiincline = false;
break;
}
// Annoying browser incompatibilities
var code = event.which || event.keyCode;
if(code === 16)
accelerate = false;
if(code === 17)
decelerate = false;
}
init();
animate();
})()
| orbiter.js | ;(function(){
'use strict'
var container, stats;
var camera, scene, renderer;
var group;
var background;
var overlay, overlayCamera;
var navballMesh, prograde, retrograde;
var timescaleControl;
var throttleControl;
var speedControl;
var orbitalElementControl;
var statsControl;
var settingsControl;
var altitudeControl;
var messageControl;
var mouseX = 0, mouseY = 0;
var cameraControls;
var grids;
var scenarioSelectorControl;
var saveControl;
var loadControl;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var viewScale = 100;
var simTime, startTime;
var realTime;
var center_select = false;
var select_idx = 0;
var select_obj = null;
var nlips_enable = true;
var grid_enable = false;
var units_km = true;
var sync_rotate = false;
var buttons = {
up: false,
down: false,
left: false,
right: false,
counterclockwise: false,
clockwise: false,
};
var accelerate = false;
var decelerate = false;
var sun;
var light;
var celestialBodies = {};
var selectedOrbitMaterial;
var AU = 149597871; // Astronomical unit in kilometers
var GMsun = 1.327124400e11 / AU / AU/ AU; // Product of gravitational constant (G) and Sun's mass (Msun)
var epsilon = 1e-40; // Doesn't the machine epsilon depend on browsers!??
var timescale = 1e0; // This is not a constant; it can be changed by the user
var rad_per_deg = Math.PI / 180; // Radians per degrees
var navballRadius = 64;
function AxisAngleQuaternion(x, y, z, angle){
var q = new THREE.Quaternion();
q.setFromAxisAngle(new THREE.Vector3(x, y, z), angle);
return q;
}
// CelestialBody class
function CelestialBody(parent, position, vertex, orbitColor, GM, name){
this.position = position;
this.velocity = new THREE.Vector3();
this.quaternion = new THREE.Quaternion();
this.angularVelocity = new THREE.Vector3();
if(orbitColor) this.orbitMaterial = new THREE.LineBasicMaterial({color: orbitColor});
this.children = [];
this.parent = parent;
this.GM = GM || GMsun;
if(parent) parent.children.push(this);
this.radius = 1 / AU;
this.controllable = false;
this.throttle = 0.;
this.totalDeltaV = 0.;
this.ignitionCount = 0;
this.name = name;
celestialBodies[name] = this;
}
CelestialBody.prototype.init = function(){
this.ascending_node = Math.random() * Math.PI * 2;
this.epoch = Math.random();
this.mean_anomaly = Math.random();
this.update();
};
CelestialBody.prototype.get_eccentric_anomaly = function(time){
// Calculates eccentric anomaly from mean anomaly in first order approximation
// see http://en.wikipedia.org/wiki/Eccentric_anomaly
var td = time - this.epoch;
var period = 2 * Math.PI * Math.sqrt(Math.pow(this.semimajor_axis * AU, 3) / this.parent.GM);
var now_anomaly = this.mean_anomaly + td * 2 * Math.PI / period;
return now_anomaly + this.eccentricity * Math.sin(now_anomaly);
};
CelestialBody.prototype.getWorldPosition = function(){
if(this.parent)
return this.parent.getWorldPosition().clone().add(this.position);
else
return this.position;
};
CelestialBody.prototype.setOrbitingVelocity = function(semimajor_axis, rotation){
this.velocity = new THREE.Vector3(1, 0, 0)
.multiplyScalar(Math.sqrt(this.parent.GM * (2 / this.position.length() - 1 / semimajor_axis)))
.applyQuaternion(rotation);
}
function deserializeVector3(json){
return new THREE.Vector3(json.x, json.y, json.z);
}
function deserializeQuaternion(json){
return new THREE.Quaternion(json._x, json._y, json._z, json._w);
}
CelestialBody.prototype.serialize = function(){
return {
name: this.name,
parent: this.parent.name,
position: this.position,
velocity: this.velocity,
quaternion: this.quaternion,
angularVelocity: this.angularVelocity,
};
};
CelestialBody.prototype.deserialize = function(json){
this.name = json.name;
this.setParent(celestialBodies[json.parent] || sun);
this.position = deserializeVector3(json.position);
this.velocity = deserializeVector3(json.velocity);
this.quaternion = deserializeQuaternion(json.quaternion);
this.angularVelocity = deserializeVector3(json.angularVelocity);
};
CelestialBody.prototype.setParent = function(newParent){
if(this.parent === newParent) return;
if(this.parent){
var j = this.parent.children.indexOf(this);
if(0 <= j) this.parent.children.splice(j, 1);
}
this.parent = newParent;
if(this.parent)
this.parent.children.push(this);
}
// Update orbital elements from position and velocity.
// The whole discussion is found in chapter 4.4 in
// https://www.academia.edu/8612052/ORBITAL_MECHANICS_FOR_ENGINEERING_STUDENTS
CelestialBody.prototype.update = function(){
function visualPosition(o){
var position = o.getWorldPosition();
if(select_obj && center_select)
position.sub(select_obj.getWorldPosition());
position.multiplyScalar(viewScale);
return position;
}
/// NLIPS: Non-Linear Inverse Perspective Scrolling
/// Idea originally found in a game Homeworld that enable
/// distant small objects to appear on screen in recognizable size
/// but still renders in real scale when zoomed up.
function nlipsFactor(o){
if(!nlips_enable)
return 1;
var g_nlips_factor = 1e6;
var d = visualPosition(o).distanceTo(camera.position) / viewScale;
var f = d / o.radius * g_nlips_factor + 1;
return f;
}
/// Calculate position of periapsis and apoapsis on the screen
/// for placing overlay icons.
/// peri = -1 if periapsis, otherwise 1
function calcApsePosition(peri, apsis){
var worldPos = e.clone().normalize().multiplyScalar(peri * scope.semimajor_axis * (1 - peri * scope.eccentricity)).sub(scope.position);
var cameraPos = worldPos.multiplyScalar(viewScale).applyMatrix4(camera.matrixWorldInverse);
var persPos = cameraPos.applyProjection(camera.projectionMatrix);
persPos.x *= windowHalfX;
persPos.y *= windowHalfY;
persPos.y -= peri * 8;
if(0 < persPos.z && persPos.z < 1){
apsis.position.copy(persPos);
apsis.visible = true;
}
else
apsis.visible = false;
};
var scope = this;
if(this.vertex)
this.vertex.copy(visualPosition(this));
if(this.model){
this.model.position.copy(visualPosition(this));
this.model.scale.set(1,1,1).multiplyScalar(nlipsFactor(this));
this.model.quaternion.copy(this.quaternion);
}
if(this.parent){
// Angular momentum vectors
var ang = this.velocity.clone().cross(this.position);
var r = this.position.length();
var v = this.velocity.length();
// Node vector
var N = (new THREE.Vector3(0, 0, 1)).cross(ang);
// Eccentricity vector
var e = this.position.clone().multiplyScalar(1 / this.parent.GM * ((v * v - this.parent.GM / r))).sub(this.velocity.clone().multiplyScalar(this.position.dot(this.velocity) / this.parent.GM));
this.eccentricity = e.length();
this.inclination = Math.acos(-ang.z / ang.length());
// Avoid zero division
if(N.lengthSq() <= epsilon)
this.ascending_node = 0;
else{
this.ascending_node = Math.acos(N.x / N.length());
if(N.y < 0) this.ascending_node = 2 * Math.PI - this.ascending_node;
}
this.semimajor_axis = 1 / (2 / r - v * v / this.parent.GM);
// Rotation to perifocal frame
var planeRot = AxisAngleQuaternion(0, 0, 1, this.ascending_node - Math.PI / 2).multiply(AxisAngleQuaternion(0, 1, 0, Math.PI - this.inclination));
var headingApoapsis = -this.position.dot(this.velocity)/Math.abs(this.position.dot(this.velocity));
// Avoid zero division and still get the correct answer when N == 0.
// This is necessary to draw orbit with zero inclination and nonzero eccentricity.
if(N.lengthSq() <= epsilon || e.lengthSq() <= epsilon)
this.argument_of_perihelion = Math.atan2(-e.y, e.x);
else{
this.argument_of_perihelion = Math.acos(N.dot(e) / N.length() / e.length());
if(e.z < 0) this.argument_of_perihelion = 2 * Math.PI - this.argument_of_perihelion;
}
// Total rotation of the orbit
var rotation = planeRot.clone().multiply(AxisAngleQuaternion(0, 0, 1, this.argument_of_perihelion));
// Convert length of unit au into a fixed-length string considering user unit selection.
// Also appends unit string for clarity.
function unitConvLength(au){
if(units_km)
return (au * AU).toPrecision(10) + ' km';
else
return au.toFixed(10) + ' AU';
}
// Show orbit information
if(this === select_obj){
// Yes, building a whole table markup by string manipulation.
// I know it's inefficient, but it's easy to implement. I'm lazy.
orbitalElementControl.setText(
'<table class="table1">'
+ ' <tr><td>e</td><td>' + this.eccentricity.toFixed(10) + '</td></tr>'
+ ' <tr><td>a</td><td>' + unitConvLength(this.semimajor_axis) + '</td></tr>'
+ ' <tr><td>i</td><td>' + (this.inclination / Math.PI).toFixed(10) + '</td></tr>'
+ ' <tr><td>Omega</td><td>' + (this.ascending_node / Math.PI).toFixed(10) + '</td></tr>'
+ ' <tr><td>w</td><td>' + (this.argument_of_perihelion / Math.PI).toFixed(10) + '</td></tr>'
+ ' <tr><td>Periapsis</td><td>' + unitConvLength(scope.semimajor_axis * (1 - scope.eccentricity)) + '</td></tr>'
+ ' <tr><td>Apoapsis</td><td>' + unitConvLength(scope.semimajor_axis * (1 + scope.eccentricity)) + '</td></tr>'
+ ' <tr><td>head</td><td>' + headingApoapsis.toFixed(5) + '</td></tr>'
// + ' omega=' + this.angularVelocity.x.toFixed(10) + ',' + '<br>' + this.angularVelocity.y.toFixed(10) + ',' + '<br>' + this.angularVelocity.z.toFixed(10)
+'</table>'
);
}
// If eccentricity is over 1, the trajectory is a hyperbola.
// It could be parabola in case of eccentricity == 1, but we ignore
// this impractical case for now.
if(1 < this.eccentricity){
// Allocate the hyperbolic shape and mesh only if necessary,
// since most of celestial bodies are all on permanent elliptical orbit.
if(!this.hyperbolicGeometry)
this.hyperbolicGeometry = new THREE.Geometry();
// Calculate the vertices every frame since the hyperbola changes shape
// depending on orbital elements.
var thetaInf = Math.acos(-1 / this.eccentricity);
this.hyperbolicGeometry.vertices.length = 0;
var h2 = ang.lengthSq();
for(var i = -19; i < 20; i++){
// Transform by square root to make far side of the hyperbola less "polygonic"
var isign = i < 0 ? -1 : 1;
var theta = thetaInf * isign * Math.sqrt(Math.abs(i) / 20);
this.hyperbolicGeometry.vertices.push(
new THREE.Vector3( Math.sin(theta), Math.cos(theta), 0 )
.multiplyScalar(h2 / this.parent.GM / (1 + this.eccentricity * Math.cos(theta))) );
}
// Signal three.js to update the vertices
this.hyperbolicGeometry.verticesNeedUpdate = true;
// Allocate hyperbola mesh and add it to the scene.
if(!this.hyperbolicMesh){
this.hyperbolicMesh = new THREE.Line(this.hyperbolicGeometry, this.orbitMaterial);
scene.add(this.hyperbolicMesh);
}
this.hyperbolicMesh.quaternion.copy(rotation);
this.hyperbolicMesh.scale.x = viewScale;
this.hyperbolicMesh.scale.y = viewScale;
this.hyperbolicMesh.position.copy(this.parent.getWorldPosition());
if(select_obj && center_select)
this.hyperbolicMesh.position.sub(select_obj.getWorldPosition());
this.hyperbolicMesh.position.multiplyScalar(viewScale);
// Switch from ellipse to hyperbola
this.hyperbolicMesh.visible = true;
if(this.orbit)
this.orbit.visible = false;
}
else if(this.hyperbolicMesh){
// Switch back to ellipse from hyperbola
if(this.orbit)
this.orbit.visible = true;
this.hyperbolicMesh.visible = false;
}
// Apply transformation to orbit mesh
if(this.orbit){
this.orbit.quaternion.copy(rotation);
this.orbit.scale.x = this.semimajor_axis * viewScale * Math.sqrt(1. - this.eccentricity * this.eccentricity);
this.orbit.scale.y = this.semimajor_axis * viewScale;
this.orbit.position.copy(new THREE.Vector3(0, -this.semimajor_axis * this.eccentricity, 0).applyQuaternion(rotation).add(this.parent.getWorldPosition()));
if(select_obj && center_select)
this.orbit.position.sub(select_obj.getWorldPosition());
this.orbit.position.multiplyScalar(viewScale);
}
if(this.apoapsis){
// if eccentricity is zero or more than 1, apoapsis is not defined
if(this === select_obj && 0 < this.eccentricity && this.eccentricity < 1)
calcApsePosition(-1, this.apoapsis);
else
this.apoapsis.visible = false;
}
if(this.periapsis){
// if eccentricity is zero, periapsis is not defined
if(this === select_obj && 0 < this.eccentricity)
calcApsePosition(1, this.periapsis);
else
this.periapsis.visible = false;
}
}
for(var i = 0; i < this.children.length; i++){
var a = this.children[i];
a.update();
}
};
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.y = 300;
camera.position.z = 1000;
camera.up.set(0,0,1);
background = new THREE.Scene();
background.rotation.x = Math.PI / 2;
var loader = new THREE.TextureLoader();
loader.load( 'images/hipparcoscyl1.jpg', function ( texture ) {
var geometry = new THREE.SphereGeometry( 2, 20, 20 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5, depthTest: false, depthWrite: false, side: THREE.BackSide } );
material.depthWrite = false;
var mesh = new THREE.Mesh(geometry, material);
background.add(mesh);
} );
overlayCamera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, -1000, 1000 );
window.addEventListener('resize', function(){
overlayCamera.left = window.innerWidth / - 2;
overlayCamera.right = window.innerWidth / 2;
overlayCamera.top = window.innerHeight / 2;
overlayCamera.bottom = window.innerHeight / - 2;
overlayCamera.updateProjectionMatrix();
});
overlay = new THREE.Scene();
var loader = new THREE.TextureLoader();
loader.load( 'images/navball.png', function ( texture ) {
var geometry = new THREE.SphereGeometry( navballRadius, 20, 20 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5, depthTest: false, depthWrite: false } );
navballMesh = new THREE.Mesh(geometry, material);
overlay.add(navballMesh);
var spriteMaterial = new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture( "images/watermark.png" ),
depthTest: false,
depthWrite: false,
transparent: true,
});
var watermark = new THREE.Sprite(spriteMaterial);
watermark.scale.set(64, 32, 64);
navballMesh.add(watermark);
} );
var spriteGeometry = new THREE.PlaneGeometry( 40, 40 );
prograde = new THREE.Mesh(spriteGeometry,
new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture( "images/prograde.png" ),
color: 0xffffff,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false,
transparent: true,
} )
);
overlay.add(prograde);
retrograde = new THREE.Mesh(spriteGeometry,
new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture( "images/retrograde.png" ),
color: 0xffffff,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false,
transparent: true,
} )
);
overlay.add(retrograde);
scene = new THREE.Scene();
group = new THREE.Object3D();
scene.add( group );
var material = new THREE.ParticleSystemMaterial( { size: 0.1 } );
// Sun
var Rsun = 695800.;
var sgeometry = new THREE.SphereGeometry( Rsun / AU * viewScale, 20, 20 );
var sunMesh = new THREE.Mesh( sgeometry, material );
group.add( sunMesh );
// Sun light
light = new THREE.PointLight( 0xffffff, 1, 0, 1e-6 );
scene.add( light );
scene.add( new THREE.AmbientLight( 0x202020 ) );
var meshMaterial = new THREE.LineBasicMaterial({color: 0x3f3f3f});
var meshGeometry = new THREE.Geometry();
for(var x = -10; x <= 10; x++)
meshGeometry.vertices.push( new THREE.Vector3( -10, x, 0 ), new THREE.Vector3(10, x, 0));
for(var x = -10; x <= 10; x++)
meshGeometry.vertices.push( new THREE.Vector3( x, -10, 0 ), new THREE.Vector3(x, 10, 0));
grids = new THREE.Object3D();
var mesh = new THREE.LineSegments(meshGeometry, meshMaterial);
mesh.scale.x = mesh.scale.y = 100;
grids.add(mesh);
var mesh2 = new THREE.LineSegments(meshGeometry, meshMaterial);
mesh2.scale.x = mesh2.scale.y = 10000 / AU * 100;
grids.add(mesh2);
function addAxis(axisVector, color){
var axisXMaterial = new THREE.LineBasicMaterial({color: color});
var axisXGeometry = new THREE.Geometry();
axisXGeometry.vertices.push(new THREE.Vector3(0,0,0), axisVector);
var axisX = new THREE.Line(axisXGeometry, axisXMaterial);
axisX.scale.multiplyScalar(100);
grids.add(axisX);
}
addAxis(new THREE.Vector3(100,0,0), 0xff0000);
addAxis(new THREE.Vector3(0,100,0), 0x00ff00);
addAxis(new THREE.Vector3(0,0,100), 0x0000ff);
scene.add(grids);
var orbitMaterial = new THREE.LineBasicMaterial({color: 0x3f3f7f});
CelestialBody.prototype.orbitMaterial = orbitMaterial; // Default orbit material
selectedOrbitMaterial = new THREE.LineBasicMaterial({color: 0xff7fff});
var orbitGeometry = new THREE.Geometry();
var curve = new THREE.EllipseCurve(0, 0, 1, 1,
0, Math.PI * 2, false, 90);
var path = new THREE.Path( curve.getPoints( 256 ) );
var orbitGeometry = path.createPointsGeometry( 256 );
// Add a planet having desired orbital elements. Note that there's no way to specify anomaly (phase) on the orbit right now.
// It's a bit difficult to calculate in Newtonian dynamics simulation.
function AddPlanet(semimajor_axis, eccentricity, inclination, ascending_node, argument_of_perihelion, color, GM, parent, texture, radius, params, name){
var rotation = AxisAngleQuaternion(0, 0, 1, ascending_node - Math.PI / 2)
.multiply(AxisAngleQuaternion(0, 1, 0, Math.PI - inclination))
.multiply(AxisAngleQuaternion(0, 0, 1, argument_of_perihelion));
var group = new THREE.Object3D();
var ret = new CelestialBody(parent || sun, new THREE.Vector3(0, 1 - eccentricity, 0).multiplyScalar(semimajor_axis).applyQuaternion(rotation), group.position, color, GM, name);
ret.model = group;
ret.radius = radius;
scene.add( group );
if(texture){
var loader = new THREE.TextureLoader();
loader.load( texture || 'images/land_ocean_ice_cloud_2048.jpg', function ( texture ) {
var geometry = new THREE.SphereGeometry( 1, 20, 20 );
var material = new THREE.MeshLambertMaterial( { map: texture, color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 } );
var mesh = new THREE.Mesh( geometry, material );
var radiusInAu = viewScale * (radius || 6534) / AU;
mesh.scale.set(radiusInAu, radiusInAu, radiusInAu);
mesh.rotation.x = Math.PI / 2;
group.add( mesh );
} );
}
else if(params.modelName){
var loader = new THREE.OBJLoader();
loader.load( params.modelName, function ( object ) {
var radiusInAu = 100 * (radius || 6534) / AU;
object.scale.set(radiusInAu, radiusInAu, radiusInAu);
group.add( object );
} );
var blastGroup = new THREE.Object3D();
group.add(blastGroup);
blastGroup.visible = false;
blastGroup.position.x = -60 / AU;
ret.blastModel = blastGroup;
var spriteMaterial = new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture( "images/blast.png" ),
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true,
});
var blast = new THREE.Sprite(spriteMaterial);
blast.position.x = -30 / AU;
blast.scale.multiplyScalar(100 / AU);
blastGroup.add(blast);
var blast2 = new THREE.Sprite(spriteMaterial);
blast2.position.x = -60 / AU;
blast2.scale.multiplyScalar(50 / AU);
blastGroup.add(blast2);
var blast2 = new THREE.Sprite(spriteMaterial);
blast2.position.x = -80 / AU;
blast2.scale.multiplyScalar(30 / AU);
blastGroup.add(blast2);
}
if(params && params.controllable)
ret.controllable = params.controllable;
ret.soi = params && params.soi ? params.soi / AU : 0;
ret.apoapsis = new THREE.Sprite(new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture('images/apoapsis.png'),
transparent: true,
}));
ret.apoapsis.scale.set(16,16,16);
overlay.add(ret.apoapsis);
ret.periapsis = new THREE.Sprite(new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture('images/periapsis.png'),
transparent: true,
}));
ret.periapsis.scale.set(16,16,16);
overlay.add(ret.periapsis);
// Orbital speed at given position and eccentricity can be calculated by v = \sqrt(\mu (2 / r - 1 / a))
// https://en.wikipedia.org/wiki/Orbital_speed
ret.setOrbitingVelocity(semimajor_axis, rotation);
if(params && params.axialTilt && params.rotationPeriod){
ret.quaternion = AxisAngleQuaternion(1, 0, 0, params.axialTilt);
ret.angularVelocity = new THREE.Vector3(0, 0, 2 * Math.PI / params.rotationPeriod).applyQuaternion(ret.quaternion);
}
if(params && params.angularVelocity) ret.angularVelocity = params.angularVelocity;
if(params && params.quaternion) ret.quaternion = params.quaternion;
var orbitMesh = new THREE.Line(orbitGeometry, ret.orbitMaterial);
ret.orbit = orbitMesh;
scene.add(orbitMesh);
ret.init();
ret.update();
return ret;
}
sun = new CelestialBody(null, new THREE.Vector3(), null, 0xffffff, GMsun, "sun");
sun.radius = Rsun;
sun.model = group;
var mercury = AddPlanet(0.387098, 0.205630, 7.005 * rad_per_deg, 48.331 * rad_per_deg, 29.124 * rad_per_deg, 0x3f7f7f, 22032 / AU / AU / AU, sun, 'images/mercury.jpg', 2439.7, {soi: 2e5}, "mercury");
var venus = AddPlanet(0.723332, 0.00677323, 3.39458 * rad_per_deg, 76.678 * rad_per_deg, 55.186 * rad_per_deg, 0x7f7f3f, 324859 / AU / AU / AU, sun, 'images/venus.jpg', 6051.8, {soi: 5e5}, "mars");
// Earth is at 1 AU (which is the AU's definition) and orbits around the ecliptic.
var earth = AddPlanet(1, 0.0167086, 0, -11.26064 * rad_per_deg, 114.20783 * rad_per_deg, 0x3f7f3f, 398600 / AU / AU / AU, sun, 'images/land_ocean_ice_cloud_2048.jpg', 6534,
{axialTilt: 23.4392811 * rad_per_deg,
rotationPeriod: ((23 * 60 + 56) * 60 + 4.10),
soi: 5e5}, "earth");
var rocket = AddPlanet(10000 / AU, 0., 0, 0, 0, 0x3f7f7f, 100 / AU / AU / AU, earth, undefined, 0.1, {modelName: 'rocket.obj', controllable: true}, "rocket");
rocket.quaternion.multiply(AxisAngleQuaternion(1, 0, 0, Math.PI / 2)).multiply(AxisAngleQuaternion(0, 1, 0, Math.PI / 2));
var moon = AddPlanet(384399 / AU, 0.0167086, 0, -11.26064 * rad_per_deg, 114.20783 * rad_per_deg, 0x5f5f5f, 4904.8695 / AU / AU / AU, earth, 'images/moon.png', 1737.1, {soi: 1e5}, "moon");
var mars = AddPlanet(1.523679, 0.0935, 1.850 * rad_per_deg, 49.562 * rad_per_deg, 286.537 * rad_per_deg, 0x7f3f3f, 42828 / AU / AU / AU, sun, 'images/mars.jpg', 3389.5, {soi: 3e5}, "mars");
var jupiter = AddPlanet(5.204267, 0.048775, 1.305 * rad_per_deg, 100.492 * rad_per_deg, 275.066 * rad_per_deg, 0x7f7f3f, 126686534 / AU / AU / AU, sun, 'images/jupiter.jpg', 69911, {soi: 10e6}, "jupiter");
select_obj = rocket;
center_select = true;
camera.position.set(0.005, 0.003, 0.005);
// Use icosahedron instead of sphere to make it look like uniform
var asteroidGeometry = new THREE.IcosahedronGeometry( 1, 2 );
// Modulate the vertices randomly to make it look like an asteroid. Simplex noise is desirable.
for(var i = 0; i < asteroidGeometry.vertices.length; i++){
asteroidGeometry.vertices[i].multiplyScalar(0.3 * (Math.random() - 0.5) + 1);
}
// Recalculate normal vectors according to updated vertices
asteroidGeometry.computeFaceNormals();
asteroidGeometry.computeVertexNormals();
// Perlin noise is applied as detail texture.
// It's asynchrnonous because it's shared by multiple asteroids.
var asteroidTexture = THREE.ImageUtils.loadTexture('images/perlin.jpg');
asteroidTexture.wrapS = THREE.RepeatWrapping;
asteroidTexture.wrapT = THREE.RepeatWrapping;
asteroidTexture.repeat.set(4, 4);
var asteroidMaterial = new THREE.MeshLambertMaterial( {
map: asteroidTexture,
color: 0xffaf7f, shading: THREE.SmoothShading, overdraw: 0.5
} );
// Randomly generate asteroids
for ( i = 0; i < 10; i ++ ) {
var angle = Math.random() * Math.PI * 2;
var position = new THREE.Vector3();
position.x = 0.1 * (Math.random() - 0.5);
position.y = 0.1 * (Math.random() - 0.5) + 1;
position.z = 0.1 * (Math.random() - 0.5);
position.applyQuaternion(AxisAngleQuaternion(0, 0, 1, angle));
position.multiplyScalar(2.5);
var asteroid = new CelestialBody(sun, position);
asteroid.velocity = new THREE.Vector3((Math.random() - 0.5) * 0.3 - 1, (Math.random() - 0.5) * 0.3, (Math.random() - 0.5) * 0.3)
.multiplyScalar(Math.sqrt(GMsun / position.length())).applyQuaternion(AxisAngleQuaternion(0, 0, 1, angle));
asteroid.radius = Math.random() * 1 + 0.1;
// We need nested Object3D for NLIPS
asteroid.model = new THREE.Object3D();
// The inner Mesh object has scale determined by radius
var shape = new THREE.Mesh( asteroidGeometry, asteroidMaterial );
asteroid.model.add(shape);
var radiusInAu = viewScale * asteroid.radius / AU;
shape.scale.set(radiusInAu, radiusInAu, radiusInAu);
shape.up.set(0,0,1);
scene.add( asteroid.model );
var orbitMesh = new THREE.Line(orbitGeometry, asteroid.orbitMaterial);
asteroid.orbit = orbitMesh;
scene.add(orbitMesh);
asteroid.init();
asteroid.update();
}
renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0x000000 );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
cameraControls = new THREE.OrbitControls(camera, renderer.domElement);
cameraControls.target.set( 0, 0, 0);
cameraControls.noPan = true;
cameraControls.maxDistance = 4000;
cameraControls.minDistance = 1 / AU;
cameraControls.zoomSpeed = 5.;
cameraControls.update();
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
timescaleControl = new (function(){
function clickForward(number){
if(select_obj && 0 < select_obj.throttle){
messageControl.setText('You cannot timewarp while accelerating');
return;
}
for(var i = 0; i < forwards.length; i++)
forwards[i].src = i <= number ? 'images/forward.png' : 'images/forward-inactive.png';
text.innerHTML = 'Timescale: x' + series[number];
timescale = series[number];
timeIndex = number;
}
this.domElement = document.createElement('div');
this.domElement.style.position = 'absolute';
this.domElement.style.top = '50px';
this.domElement.style.background = '#7f7f7f';
this.domElement.style.zIndex = 10;
var forwards = [];
var series = [1, 5, 10, 100, 1e3, 1e4, 1e5, 1e6];
var timeIndex = 0;
for(var i = 0; i < series.length; i++){
var forward = document.createElement('img');
forward.src = i <= timeIndex ? 'images/forward.png' : 'images/forward-inactive.png';
forward.style.width = '15px';
forward.style.height = '20px';
forward.number = i;
forward.addEventListener('click', function(e){clickForward(this.number)});
this.domElement.appendChild(forward);
forwards.push(forward);
}
var text = document.createElement('div');
text.innerHTML = 'Timescale: x1';
this.domElement.appendChild(text);
var date = document.createElement('div');
this.domElement.appendChild(date);
this.setDate = function(text){
date.innerHTML = text;
}
this.increment = function(){
if(select_obj && 0 < select_obj.throttle){
messageControl.setText('You cannot timewarp while accelerating');
return;
}
if(timeIndex + 1 < series.length)
timeIndex++;
clickForward(timeIndex);
}
this.decrement = function(){
if(0 <= timeIndex - 1)
timeIndex--;
clickForward(timeIndex);
}
})();
container.appendChild( timescaleControl.domElement );
throttleControl = new (function(){
function updatePosition(pos){
if(1 < timescale && 0 < pos){
messageControl.setText('You cannot accelerate while timewarping');
return;
}
visualizePosition(pos);
}
function visualizePosition(pos){
var backRect = element.getBoundingClientRect();
var rect = throttleBack.getBoundingClientRect();
var handleRect = handle.getBoundingClientRect();
var max = rect.height - handleRect.height;
handle.style.top = (1 - pos) * max + (rect.top - backRect.top) + 'px';
if(select_obj.throttle === 0. && 0. < pos)
select_obj.ignitionCount++;
select_obj.throttle = pos;
if(select_obj && select_obj.blastModel){
select_obj.blastModel.visible = 0 < select_obj.throttle;
var size = (select_obj.throttle + 0.1) / 1.1;
select_obj.blastModel.scale.set(size, size, size);
}
}
function movePosition(event){
var rect = throttleBack.getBoundingClientRect();
var handleRect = handle.getBoundingClientRect();
var max = rect.height - handleRect.height;
var pos = Math.min(max, Math.max(0, (event.clientY - rect.top) - handleRect.height / 2));
updatePosition(1 - pos / max);
}
var guideHeight = 128;
var guideWidth = 32;
this.domElement = document.createElement('div');
this.domElement.style.position = 'absolute';
this.domElement.style.top = (window.innerHeight - guideHeight) + 'px';
this.domElement.style.left = (windowHalfX - navballRadius - guideWidth) + 'px';
this.domElement.style.background = '#7f7f7f';
this.domElement.style.zIndex = 10;
var element = this.domElement;
var dragging = false;
var scope = this;
var throttleMax = document.createElement('img');
throttleMax.src = 'images/throttle-max.png';
throttleMax.style.position = "absolute";
throttleMax.style.left = '0px';
throttleMax.style.top = '0px';
throttleMax.onmousedown = function(event){
scope.setThrottle(1);
};
throttleMax.ondragstart = function(event){
event.preventDefault();
};
this.domElement.appendChild(throttleMax);
var throttleBack = document.createElement('img');
throttleBack.src = 'images/throttle-back.png';
throttleBack.style.position = "absolute";
throttleBack.style.left = '0px';
throttleBack.style.top = '25px';
throttleBack.onmousedown = function(event){
dragging = true;
movePosition(event);
};
throttleBack.onmousemove = function(event){
if(dragging && event.buttons & 1)
movePosition(event);
};
throttleBack.onmouseup = function(event){
dragging = false;
}
throttleBack.draggable = true;
throttleBack.ondragstart = function(event){
event.preventDefault();
};
this.domElement.appendChild(throttleBack);
var throttleMin = document.createElement('img');
throttleMin.src = 'images/throttle-min.png';
throttleMin.style.position = "absolute";
throttleMin.style.left = '0px';
throttleMin.style.top = '106px';
throttleMin.onmousedown = function(event){
scope.setThrottle(0);
};
throttleMin.ondragstart = function(event){
event.preventDefault();
};
this.domElement.appendChild(throttleMin);
var handle = document.createElement('img');
handle.src = 'images/throttle-handle.png';
handle.style.position = 'absolute';
handle.style.top = (guideHeight - 16) + 'px';
handle.style.left = '0px';
handle.onmousemove = throttleBack.onmousemove;
handle.onmousedown = throttleBack.onmousedown;
handle.onmouseup = throttleBack.onmouseup;
handle.ondragstart = throttleBack.ondragstart;
this.domElement.appendChild(handle);
this.increment = function(delta){
if(select_obj)
updatePosition(Math.min(1, select_obj.throttle + delta));
}
this.decrement = function(delta){
if(select_obj)
updatePosition(Math.max(0, select_obj.throttle - delta));
}
this.setThrottle = function(value){
updatePosition(value);
}
window.addEventListener('resize', function(){
element.style.top = (window.innerHeight - guideHeight) + 'px';
element.style.left = (window.innerWidth / 2 - navballRadius - guideWidth) + 'px';
});
window.addEventListener('load', function(){
visualizePosition(select_obj.throttle);
});
})();
container.appendChild( throttleControl.domElement );
var rotationControl = new (function(){
function setSize(){
rootElement.style.top = (window.innerHeight - 2 * navballRadius) + 'px';
rootElement.style.left = (window.innerWidth / 2 - navballRadius) + 'px';
}
function absorbEvent_(event) {
var e = event || window.event;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
function addArrow(src, key, left, top){
var button = document.createElement('img');
button.src = src;
button.width = buttonWidth;
button.height = buttonHeight;
button.style.position = 'absolute';
button.style.top = top + 'px';
button.style.left = left + 'px';
button.onmousedown = function(event){
buttons[key] = true;
};
button.onmouseup = function(event){
buttons[key] = false;
button.style.boxShadow = '';
}
button.ondragstart = function(event){
event.preventDefault();
};
button.ontouchstart = function(event){
buttons[key] = true;
event.preventDefault();
event.stopPropagation();
};
button.ontouchmove = absorbEvent_;
button.ontouchend = function(event){
buttons[key] = false;
button.style.boxShadow = '';
event.preventDefault();
event.stopPropagation();
};
button.ontouchcancel = absorbEvent_;
element.appendChild(button);
}
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var rootElement = this.domElement;
this.domElement.style.position = 'absolute';
this.domElement.style.width = (navballRadius * 2) + 'px';
this.domElement.style.height = (navballRadius * 2) + 'px';
setSize();
this.domElement.style.zIndex = 5;
// Introduce internal 'div' because the outer 'div' cannot be
// hidden since it need to receive mouseenter event.
var element = document.createElement('div');
element.style.width = '100%';
element.style.height = '100%';
element.style.display = 'none';
this.domElement.appendChild(element);
this.domElement.onmouseenter = function(event){
element.style.display = 'block';
};
this.domElement.onmouseleave = function(event){
element.style.display = 'none';
up = down = left = right = false;
};
addArrow('images/rotate-up.png', 'up', navballRadius - buttonWidth / 2, 0);
addArrow('images/rotate-down.png', 'down', navballRadius - buttonWidth / 2, 2 * navballRadius - buttonHeight);
addArrow('images/rotate-left.png', 'left', 0, navballRadius - buttonHeight / 2);
addArrow('images/rotate-right.png', 'right', 2 * navballRadius - buttonWidth, navballRadius - buttonHeight / 2);
addArrow('images/rotate-cw.png', 'clockwise', 2 * navballRadius - buttonWidth, 0);
addArrow('images/rotate-ccw.png', 'counterclockwise', 0, 0);
window.addEventListener('resize', setSize);
})();
container.appendChild( rotationControl.domElement );
speedControl = new (function(){
function setSize(){
element.style.top = (window.innerHeight - 2 * navballRadius - 32) + 'px';
element.style.left = (window.innerWidth / 2 - element.getBoundingClientRect().width / 2) + 'px';
}
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
setSize();
element.style.zIndex = 7;
element.style.background = 'rgba(0, 0, 0, 0.5)';
window.addEventListener('resize', setSize);
var title = document.createElement('div');
title.innerHTML = 'Orbit';
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
this.setSpeed = function(){
if(select_obj){
var value = select_obj.velocity.length() * AU;
if(value < 1)
valueElement.innerHTML = (value * 1000).toFixed(4) + 'm/s';
else
valueElement.innerHTML = value.toFixed(4) + 'km/s';
}
else
valueElement.innerHTML = '';
element.style.left = (window.innerWidth / 2 - element.getBoundingClientRect().width / 2) + 'px';
}
})();
container.appendChild( speedControl.domElement );
orbitalElementControl = new (function(){
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = 120 + 'px';
element.style.left = 0 + 'px';
element.style.zIndex = 7;
var visible = false;
var icon = document.createElement('img');
icon.src = 'images/orbitIcon.png';
element.appendChild(icon);
var title = document.createElement('div');
title.innerHTML = 'Orbital Elements';
title.style.display = 'none';
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
valueElement.id = 'orbit';
valueElement.style.display = 'none';
// Register event handlers
icon.ondragstart = function(event){
event.preventDefault();
};
icon.onclick = function(event){
visible = !visible;
if(visible){
valueElement.style.display = 'block';
element.style.background = 'rgba(0, 0, 0, 0.5)';
}
else{
valueElement.style.display = 'none';
element.style.background = 'rgba(0, 0, 0, 0)';
}
};
icon.onmouseenter = function(event){
if(!visible)
title.style.display = 'block';
};
icon.onmouseleave = function(event){
if(!visible)
title.style.display = 'none';
};
this.setText = function(text){
valueElement.innerHTML = text;
}
})();
container.appendChild( orbitalElementControl.domElement );
function rightTitleSetSize(title, icon){
var r = title.getBoundingClientRect();
var iconRect = icon.getBoundingClientRect()
title.style.top = (iconRect.height - r.height) + 'px';
title.style.right = iconRect.width + 'px';
}
statsControl = new (function(){
function setSize(){
element.style.left = (window.innerWidth - buttonWidth) + 'px';
rightTitleSetSize(title, icon);
}
var buttonTop = 120;
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = buttonTop + 'px';
element.style.left = 0 + 'px';
element.style.zIndex = 7;
var visible = false;
var icon = document.createElement('img');
icon.src = 'images/statsIcon.png';
icon.style.width = buttonWidth + 'px';
icon.style.height = buttonHeight + 'px';
element.appendChild(icon);
var title = document.createElement('div');
title.innerHTML = 'Statistics';
title.style.display = 'none';
title.style.position = 'absolute';
title.style.top = buttonTop + 'px';
title.style.background = 'rgba(0, 0, 0, 0.5)';
title.style.zIndex = 20;
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
valueElement.style.display = 'none';
valueElement.style.position = 'absolute';
valueElement.style.background = 'rgba(0, 0, 0, 0.5)';
valueElement.style.border = '3px ridge #7f3f3f';
valueElement.style.padding = '3px';
var valueElements = [];
for(var i = 0; i < 3; i++){
var titleElement = document.createElement('div');
titleElement.innerHTML = ['Mission Time', 'Delta-V', 'Ignition Count'][i];
titleElement.style.fontWeight = 'bold';
titleElement.style.paddingRight = '1em';
valueElement.appendChild(titleElement);
var valueElementChild = document.createElement('div');
valueElementChild.style.textAlign = 'right';
valueElements.push(valueElementChild);
valueElement.appendChild(valueElementChild);
}
setSize();
// Register event handlers
window.addEventListener('resize', setSize);
icon.ondragstart = function(event){
event.preventDefault();
};
icon.onclick = function(event){
visible = !visible;
if(visible){
valueElement.style.display = 'block';
element.style.background = 'rgba(0, 0, 0, 0.5)';
}
else{
valueElement.style.display = 'none';
element.style.background = 'rgba(0, 0, 0, 0)';
settingsControl.domElement.style.top = element.getBoundingClientRect().bottom + 'px';
}
};
icon.onmouseenter = function(event){
if(!visible)
title.style.display = 'block';
rightTitleSetSize(title, icon);
};
icon.onmouseleave = function(event){
if(!visible)
title.style.display = 'none';
};
this.setText = function(text){
if(!visible)
return;
if(!select_obj){
valueElements[3].innerHTML = valueElements[2] = '';
return;
}
var totalSeconds = (simTime.getTime() - startTime.getTime()) / 1e3;
var seconds = Math.floor(totalSeconds) % 60;
var minutes = Math.floor(totalSeconds / 60) % 60;
var hours = Math.floor(totalSeconds / 60 / 60) % 24;
var days = Math.floor(totalSeconds / 60 / 60 / 24);
valueElements[0].innerHTML = days + 'd ' + zerofill(hours) + ':' + zerofill(minutes) + ':' + zerofill(seconds);
var deltaVkm = select_obj.totalDeltaV * AU;
var deltaV;
if(deltaVkm < 10)
deltaV = (deltaVkm * 1e3).toFixed(1) + 'm/s';
else
deltaV = deltaVkm.toFixed(4) + 'km/s';
valueElements[1].innerHTML = deltaV;
valueElements[2].innerHTML = select_obj.ignitionCount;
valueElement.style.marginLeft = (buttonWidth - valueElement.getBoundingClientRect().width) + 'px';
settingsControl.domElement.style.top = valueElement.getBoundingClientRect().bottom + 'px';
}
})();
container.appendChild( statsControl.domElement );
settingsControl = new (function(){
function setSize(){
element.style.left = (window.innerWidth - buttonWidth) + 'px';
rightTitleSetSize(title, icon);
}
var buttonTop = 154;
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = buttonTop + 'px';
element.style.left = 0 + 'px';
element.style.zIndex = 7;
var visible = false;
var icon = document.createElement('img');
icon.src = 'images/settingsIcon.png';
icon.style.width = buttonWidth + 'px';
icon.style.height = buttonHeight + 'px';
element.appendChild(icon);
var title = document.createElement('div');
title.innerHTML = 'Settings';
title.style.display = 'none';
title.style.position = 'absolute';
title.style.background = 'rgba(0, 0, 0, 0.5)';
title.style.zIndex = 20;
element.appendChild(title);
var valueElement = document.createElement('div');
element.appendChild(valueElement);
valueElement.style.display = 'none';
valueElement.style.position = 'absolute';
valueElement.style.background = 'rgba(0, 0, 0, 0.5)';
valueElement.style.border = '3px ridge #7f3f3f';
valueElement.style.padding = '3px';
// The settings variables are function local variables, so we can't just pass this pointer
// and parameter name and do something like `this[name] = !this[name]`.
var toggleFuncs = [
function(){grid_enable = !grid_enable},
function(){sync_rotate = !sync_rotate},
function(){nlips_enable = !nlips_enable},
function(){units_km = !units_km}
];
var checkElements = [];
for(var i = 0; i < toggleFuncs.length; i++){
var lineElement = document.createElement('div');
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.onclick = toggleFuncs[i];
var id = 'settings_check_' + i;
checkbox.setAttribute('id', id);
lineElement.appendChild(checkbox);
checkElements.push(checkbox);
var label = document.createElement('label');
label.setAttribute('for', id);
label.innerHTML = [
'Show grid (G)',
'Chase camera (H)',
'Nonlinear scale (N)',
'Units in KM (K)'][i];
lineElement.appendChild(label);
lineElement.style.fontWeight = 'bold';
lineElement.style.paddingRight = '1em';
lineElement.style.whiteSpace = 'nowrap';
valueElement.appendChild(lineElement);
}
setSize();
// Register event handlers
window.addEventListener('resize', setSize);
icon.ondragstart = function(event){
event.preventDefault();
};
icon.onclick = function(event){
visible = !visible;
if(visible){
valueElement.style.display = 'block';
element.style.background = 'rgba(0, 0, 0, 0.5)';
}
else{
valueElement.style.display = 'none';
element.style.background = 'rgba(0, 0, 0, 0)';
}
};
icon.onmouseenter = function(event){
if(!visible)
title.style.display = 'block';
rightTitleSetSize(title, icon);
};
icon.onmouseleave = function(event){
if(!visible)
title.style.display = 'none';
};
this.setText = function(text){
if(!visible)
return;
checkElements[0].checked = grid_enable;
checkElements[1].checked = sync_rotate;
checkElements[2].checked = nlips_enable;
checkElements[3].checked = units_km;
valueElement.style.marginLeft = (buttonWidth - valueElement.getBoundingClientRect().width) + 'px';
}
})();
container.appendChild( settingsControl.domElement );
altitudeControl = new (function(){
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.top = '2em';
element.style.left = '50%';
element.style.background = 'rgba(0,0,0,0.5)';
element.style.zIndex = 8;
var visible = false;
// Register event handlers
element.ondragstart = function(event){
event.preventDefault();
};
this.setText = function(value){
var text;
if(value < 1e5)
text = value.toFixed(4) + 'km';
else if(value < 1e8)
text = (value / 1000).toFixed(4) + 'Mm';
else
text = (value / AU).toFixed(4) + 'AU';
element.innerHTML = text;
element.style.marginLeft = -element.getBoundingClientRect().width / 2 + 'px';
};
})();
container.appendChild( altitudeControl.domElement );
messageControl = new (function(){
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.top = '25%';
element.style.left = '50%';
element.style.fontSize = '20px';
element.style.fontWeight = 'bold';
element.style.textShadow = '0px 0px 5px rgba(0,0,0,1)';
element.style.zIndex = 20;
var showTime = 0;
// Register event handlers
element.ondragstart = function(event){
event.preventDefault();
};
// Disable text selection
element.onselectstart = function(){ return false; }
this.setText = function(text){
element.innerHTML = text;
element.style.display = 'block';
element.style.opacity = '1';
element.style.marginTop = -element.getBoundingClientRect().height / 2 + 'px';
element.style.marginLeft = -element.getBoundingClientRect().width / 2 + 'px';
showTime = 5; // Seconds to show should depend on text length!
};
this.timeStep = function(deltaTime){
if(showTime < deltaTime){
element.style.display = 'none';
showTime = 0;
return;
}
showTime -= deltaTime;
if(showTime < 2);
element.style.opacity = (showTime / 2).toString();
}
})
container.appendChild( messageControl.domElement );
scenarioSelectorControl = new (function(){
var buttonTop = 0;
var buttonHeight = 32;
var buttonWidth = 32;
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = buttonTop + 'px';
element.style.right = 0 + 'px';
element.style.zIndex = 7;
var icon = document.createElement('img');
icon.src = 'images/menuIcon.png';
icon.style.width = buttonWidth + 'px';
icon.style.height = buttonHeight + 'px';
var visible = false;
element.appendChild(icon);
var title = document.createElement('div');
title.innerHTML = 'Scenarios';
title.style.display = 'none';
title.style.position = 'absolute';
title.style.background = 'rgba(0, 0, 0, 0.5)';
title.style.zIndex = 20;
element.appendChild(title);
var valueElement = document.createElement('div');
// valueElement.style.display = "none";
// valueElement.style.position = "fixed";
valueElement.style.cssText = "display: none; position: fixed; left: 50%;"
+ "width: 300px; top: 50%; background-color: rgba(0,0,0,0.85); border: 5px ridge #ffff7f;"
+ "font-size: 25px; text-align: center";
var scenarios = [
{title: "Earth orbit", parent: earth, semimajor_axis: 10000 / AU},
{title: "Moon orbit", parent: moon, semimajor_axis: 3000 / AU},
{title: "Mars orbit", parent: mars, semimajor_axis: 5000 / AU},
{title: "Venus orbit", parent: venus, semimajor_axis: 10000 / AU, ascending_node: Math.PI},
{title: "Jupiter orbit", parent: jupiter, semimajor_axis: 100000 / AU},
];
var elem = document.createElement('div');
elem.style.margin = "15px";
elem.style.padding = "15px";
elem.innerHTML = "Scenario Selector";
valueElement.appendChild(elem);
for(var i = 0; i < scenarios.length; i++){
var elem = document.createElement('div');
elem.style.margin = "15px";
elem.style.padding = "15px";
elem.style.border = "1px solid #ffff00";
elem.innerHTML = scenarios[i].title;
elem.onclick = (function(scenario){
return function(){
var ascending_node = scenario.ascending_node || 0.;
var eccentricity = scenario.eccentricity || 0.;
var rotation = scenario.rotation || (function(){
var rotation = AxisAngleQuaternion(0, 0, 1, ascending_node - Math.PI / 2);
rotation.multiply(AxisAngleQuaternion(0, 1, 0, Math.PI));
return rotation;
})();
rocket.setParent(scenario.parent);
rocket.position = new THREE.Vector3(0, 1 - eccentricity, 0)
.multiplyScalar(scenario.semimajor_axis).applyQuaternion(rotation);
rocket.quaternion = rotation.clone();
rocket.quaternion.multiply(AxisAngleQuaternion(1, 0, 0, -Math.PI / 2));
rocket.angularVelocity = new THREE.Vector3();
throttleControl.setThrottle(0);
rocket.setOrbitingVelocity(scenario.semimajor_axis, rotation);
title.style.display = 'none';
visible = false;
valueElement.style.display = 'none';
}
})(scenarios[i]);
valueElement.appendChild(elem);
}
this.domElement.appendChild(valueElement);
icon.ondragstart = function(event){
event.preventDefault();
};
icon.onclick = function(event){
visible = !visible;
if(visible){
valueElement.style.display = 'block';
var rect = valueElement.getBoundingClientRect();
valueElement.style.marginLeft = -rect.width / 2 + "px";
valueElement.style.marginTop = -rect.height / 2 + "px";
}
else{
valueElement.style.display = 'none';
}
};
icon.onmouseenter = function(event){
if(!visible)
title.style.display = 'block';
rightTitleSetSize(title, icon);
};
icon.onmouseleave = function(event){
if(!visible)
title.style.display = 'none';
};
});
container.appendChild( scenarioSelectorControl.domElement );
function MenuControl(titleString, iconSrc, config){
this.domElement = document.createElement('div');
var element = this.domElement;
element.style.position = 'absolute';
element.style.textAlign = 'left';
element.style.top = config.buttonTop + 'px';
element.style.right = 0 + 'px';
element.style.zIndex = 7;
this.icon = document.createElement('img');
this.icon.src = iconSrc;
this.icon.style.width = config.buttonWidth + 'px';
this.icon.style.height = config.buttonHeight + 'px';
var scope = this;
this.icon.ondragstart = function(event){
event.preventDefault();
};
this.icon.onclick = function(event){
scope.setVisible(!scope.visible);
};
this.icon.onmouseenter = function(event){
if(!scope.visible)
scope.title.style.display = 'block';
rightTitleSetSize(scope.title, scope.icon);
};
this.icon.onmouseleave = function(event){
if(!scope.visible)
scope.title.style.display = 'none';
};
element.appendChild(this.icon);
var title = document.createElement('div');
title.innerHTML = titleString;
title.style.display = 'none';
title.style.position = 'absolute';
title.style.background = 'rgba(0, 0, 0, 0.5)';
title.style.zIndex = 20;
element.appendChild(title);
this.title = title;
this.visible = false;
var valueElement = document.createElement('div');
valueElement.style.cssText = "display: none; position: fixed; left: 50%;"
+ "width: 300px; top: 50%; background-color: rgba(0,0,0,0.85); border: 5px ridge #7fff7f;"
+ "font-size: 15px; text-align: center";
this.valueElement = valueElement;
var titleElem = document.createElement('div');
titleElem.style.margin = "15px";
titleElem.style.padding = "15px";
titleElem.style.fontSize = '25px';
titleElem.innerHTML = titleString;
this.valueElement.appendChild(titleElem);
this.domElement.appendChild(this.valueElement);
}
saveControl = new (function(){
var config = {
buttonTop: 34,
buttonHeight: 32,
buttonWidth: 32,
};
var scope = this;
MenuControl.call(this, 'Save data', 'images/saveIcon.png', config);
var inputContainer = document.createElement('div');
inputContainer.style.border = "1px solid #7fff7f";
inputContainer.style.margin = "5px";
inputContainer.style.padding = "5px";
var inputTitle = document.createElement('div');
inputTitle.innerHTML = 'New Save Name';
var inputElement = document.createElement('input');
inputElement.setAttribute('type', 'text');
var inputButton = document.createElement('button');
inputButton.innerHTML = 'save'
inputButton.onclick = function(event){
var saveData = localStorage.getItem('WebGLOrbiterSavedData') ? JSON.parse(localStorage.getItem('WebGLOrbiterSavedData')) : [];
saveData.push({title: inputElement.value, state: rocket.serialize()});
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Saved!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
};
inputElement.onkeydown = function(e){
e.stopPropagation();
}
inputContainer.appendChild(inputTitle);
inputContainer.appendChild(inputElement);
inputContainer.appendChild(inputButton);
this.valueElement.appendChild(inputContainer);
var saveContainer = document.createElement('div');
function updateSaveDataList(){
while(0 < saveContainer.children.length) saveContainer.removeChild(saveContainer.children[0]);
var saveData = localStorage.getItem('WebGLOrbiterSavedData') ? JSON.parse(localStorage.getItem('WebGLOrbiterSavedData')) : [];
for(var i = 0; i < saveData.length; i++){
var elem = document.createElement('div');
elem.style.margin = "5px";
elem.style.padding = "5px";
elem.style.border = "1px solid #00ff00";
var labelElem = document.createElement('div');
labelElem.innerHTML = saveData[i].title;
labelElem.style.cssText = "width: 100%; margin-right: -32px; display: inline-block; text-align: overflow: auto;";
elem.appendChild(labelElem);
var deleteElem = document.createElement('img');
deleteElem.setAttribute('src', 'images/trashcan.png');
deleteElem.style.width = '32px';
deleteElem.onclick = (function(i){
return function(e){
saveData.splice(i, 1);
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Deleted!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
e.stopPropagation();
}
})(i);
elem.appendChild(deleteElem);
elem.onclick = (function(save){
return function(){
save.state = rocket.serialize();
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Saved!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
}
})(saveData[i]);
saveContainer.appendChild(elem);
}
}
this.valueElement.appendChild(saveContainer);
this.setVisible = function(v){
this.visible = v;
if(this.visible){
loadControl.setVisible(false); // Mutually exclusive
this.valueElement.style.display = 'block';
updateSaveDataList();
var rect = this.valueElement.getBoundingClientRect();
this.valueElement.style.marginLeft = -rect.width / 2 + "px";
this.valueElement.style.marginTop = -rect.height / 2 + "px";
}
else{
this.valueElement.style.display = 'none';
}
}
});
container.appendChild( saveControl.domElement );
loadControl = new (function(){
var config = {
buttonTop: 34 * 2,
buttonHeight: 32,
buttonWidth: 32,
};
MenuControl.call(this, 'Load data', 'images/loadIcon.png', config);
var scope = this;
this.valueElement.style.border = "5px ridge #ff7fff";
var saveContainer = document.createElement('div');
function updateSaveDataList(){
while(0 < saveContainer.children.length) saveContainer.removeChild(saveContainer.children[0]);
var saveData = localStorage.getItem('WebGLOrbiterSavedData') ? JSON.parse(localStorage.getItem('WebGLOrbiterSavedData')) : [];
for(var i = 0; i < saveData.length; i++){
var elem = document.createElement('div');
elem.style.margin = "5px";
elem.style.padding = "5px";
elem.style.border = "1px solid #ffff00";
var labelElem = document.createElement('div');
labelElem.innerHTML = saveData[i].title;
labelElem.style.cssText = "width: 100%; margin-right: -32px; display: inline-block; text-align: overflow: auto;";
elem.appendChild(labelElem);
var deleteElem = document.createElement('img');
deleteElem.setAttribute('src', 'images/trashcan.png');
deleteElem.style.width = '32px';
deleteElem.onclick = (function(i){
return function(e){
saveData.splice(i, 1);
localStorage.setItem('WebGLOrbiterSavedData', JSON.stringify(saveData));
messageControl.setText('Game State Deleted!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
e.stopPropagation();
}
})(i);
elem.appendChild(deleteElem);
elem.onclick = (function(save){
return function(){
rocket.deserialize(save.state);
throttleControl.setThrottle(rocket.throttle);
messageControl.setText('Game State Loaded!');
scope.title.style.display = 'none';
scope.visible = false;
scope.valueElement.style.display = 'none';
}
})(saveData[i]);
saveContainer.appendChild(elem);
}
}
this.valueElement.appendChild(saveContainer);
this.setVisible = function(v){
scope.visible = v;
if(scope.visible){
saveControl.setVisible(false); // Mutually exclusive
scope.valueElement.style.display = 'block';
updateSaveDataList();
var rect = scope.valueElement.getBoundingClientRect();
scope.valueElement.style.marginLeft = -rect.width / 2 + "px";
scope.valueElement.style.marginTop = -rect.height / 2 + "px";
}
else{
scope.valueElement.style.display = 'none';
}
}
});
container.appendChild( loadControl.domElement );
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener( 'keydown', onKeyDown, false );
window.addEventListener( 'keyup', onKeyUp, false );
// Start the clock after the initialization is finished, otherwise
// the very first frame of simulation can be long.
simTime = new Date();
realTime = simTime;
startTime = simTime;
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
// Fills leading zero if the value is less than 10, making the returned string always two characters long.
// Note that values not less than 100 or negative values are not guaranteed to be two characters wide.
// This function is for date time formatting purpose only.
function zerofill(v){
if(v < 10)
return "0" + v;
else
return v;
}
function render() {
var now = new Date();
var realDeltaTimeMilliSec = now.getTime() - realTime.getTime();
var time = new Date(simTime.getTime() + realDeltaTimeMilliSec * timescale);
var deltaTime = (time.getTime() - simTime.getTime()) * 1e-3;
realTime = now;
simTime = time;
timescaleControl.setDate(time.getFullYear() + '/' + zerofill(time.getMonth() + 1) + '/' + zerofill(time.getDate())
+ ' ' + zerofill(time.getHours()) + ':' + zerofill(time.getMinutes()) + ':' + zerofill(time.getSeconds()));
speedControl.setSpeed();
statsControl.setText();
settingsControl.setText();
messageControl.timeStep(realDeltaTimeMilliSec * 1e-3);
camera.near = Math.min(1, cameraControls.target.distanceTo(camera.position) / 10);
camera.updateProjectionMatrix();
var acceleration = 5e-10;
var div = 100; // We should pick subdivide simulation step count by angular speed!
function simulateBody(parent){
var children = parent.children;
for(var i = 0; i < children.length;){
var a = children[i];
var sl = a.position.lengthSq();
if(sl !== 0){
var angleAcceleration = 1e-0;
var accel = a.position.clone().negate().normalize().multiplyScalar(deltaTime / div * a.parent.GM / sl);
if(select_obj === a && select_obj.controllable && timescale <= 1){
if(buttons.up) select_obj.angularVelocity.add(new THREE.Vector3(0, 0, 1).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.down) select_obj.angularVelocity.add(new THREE.Vector3(0, 0, -1).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.left) select_obj.angularVelocity.add(new THREE.Vector3(0, 1, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.right) select_obj.angularVelocity.add(new THREE.Vector3(0, -1, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.counterclockwise) select_obj.angularVelocity.add(new THREE.Vector3(1, 0, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(buttons.clockwise) select_obj.angularVelocity.add(new THREE.Vector3(-1, 0, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(angleAcceleration * deltaTime / div));
if(!buttons.up && !buttons.down && !buttons.left && !buttons.right && !buttons.counterclockwise && !buttons.clockwise){
// Immediately stop micro-rotation if the body is controlled.
// This is done to make it still in larger timescale, since micro-rotation cannot be canceled
// by product of angularVelocity and quaternion which underflows by square.
// Think that the vehicle has a momentum wheels that cancels micro-rotation continuously working.
if(1e-6 < select_obj.angularVelocity.lengthSq())
select_obj.angularVelocity.add(select_obj.angularVelocity.clone().normalize().multiplyScalar(-angleAcceleration * deltaTime / div));
else
select_obj.angularVelocity.set(0, 0, 0);
}
if(0 < select_obj.throttle){
var deltaV = acceleration * select_obj.throttle * deltaTime / div;
select_obj.velocity.add(new THREE.Vector3(1, 0, 0).applyQuaternion(select_obj.quaternion).multiplyScalar(deltaV));
select_obj.totalDeltaV += deltaV;
}
}
var dvelo = accel.clone().multiplyScalar(0.5);
var vec0 = a.position.clone().add(a.velocity.clone().multiplyScalar(deltaTime / div / 2.));
var accel1 = vec0.clone().negate().normalize().multiplyScalar(deltaTime / div * a.parent.GM / vec0.lengthSq());
var velo1 = a.velocity.clone().add(dvelo);
a.velocity.add(accel1);
a.position.add(velo1.multiplyScalar(deltaTime / div));
if(0 < a.angularVelocity.lengthSq()){
var axis = a.angularVelocity.clone().normalize();
// We have to multiply in this order!
a.quaternion.multiplyQuaternions(AxisAngleQuaternion(axis.x, axis.y, axis.z, a.angularVelocity.length() * deltaTime / div), a.quaternion);
}
}
// Only controllable objects can change orbiting body
if(a.controllable){
// Check if we are leaving sphere of influence of current parent.
if(a.parent.parent && a.parent.soi && a.parent.soi * 1.01 < a.position.length()){
a.position.add(parent.position);
a.velocity.add(parent.velocity);
var j = children.indexOf(a);
if(0 <= j)
children.splice(j, 1);
a.parent = parent.parent;
a.parent.children.push(a);
continue; // Continue but not increment i
}
var skip = false;
// Check if we are entering sphere of influence of another sibling.
for(var j = 0; j < children.length; j++){
var aj = children[j];
if(aj === a)
continue;
if(!aj.soi)
continue;
if(aj.position.distanceTo(a.position) < aj.soi * .99){
a.position.sub(aj.position);
a.velocity.sub(aj.velocity);
var k = children.indexOf(a);
if(0 <= k)
children.splice(k, 1);
a.parent = aj;
aj.children.push(a);
skip = true;
break;
}
}
if(skip)
continue; // Continue but not increment i
}
simulateBody(a);
i++;
}
}
for(var d = 0; d < div; d++){
// Allow trying to increase throttle when timewarping in order to show the message
if(accelerate) throttleControl.increment(deltaTime / div);
if(decelerate) throttleControl.decrement(deltaTime / div);
simulateBody(sun);
}
sun.update();
var irotate = AxisAngleQuaternion(-1, 0, 0, Math.PI / 2);
// offset sun position
light.position.copy(sun.model.position);
grids.visible = grid_enable;
// camera.up.copy(new THREE.Vector3(0,0,1)); // This did't work with OrbitControls
cameraControls.update();
var oldPosition = camera.position.clone();
var oldQuaternion = camera.quaternion.clone();
if(sync_rotate && select_obj){
camera.quaternion.copy(
select_obj.quaternion.clone()
.multiply(AxisAngleQuaternion(0, 1, 0, -1*Math.PI / 2)));
camera.position.copy(new THREE.Vector3(0, 0.2, 1).normalize().multiplyScalar(camera.position.length()).applyQuaternion(camera.quaternion));
}
var position = camera.position.clone();
camera.position.set(0,0,0);
renderer.render( background, camera);
camera.position.copy(position);
renderer.render( scene, camera );
if(navballMesh && select_obj && select_obj.controllable){
// First, calculate the quaternion for rotating the system so that
// X axis points north, Y axis points east and Z axis points zenith.
var north = new THREE.Vector3(0, 0, 1).applyQuaternion(select_obj.parent.quaternion);
var tangent = north.cross(select_obj.position).normalize();
var qball = new THREE.Quaternion();
var mat = new THREE.Matrix4();
var normal = select_obj.position.clone().normalize().negate();
mat.makeBasis(tangent.clone().cross(normal), tangent, normal);
qball.setFromRotationMatrix (mat);
navballMesh.quaternion.copy(
AxisAngleQuaternion(0, 1, 0, -1*Math.PI / 2)
.multiply(AxisAngleQuaternion(0, 0, 1, Math.PI))
.multiply(select_obj.quaternion.clone().conjugate())
.multiply(qball)
.multiply(AxisAngleQuaternion(1, 0, 0, Math.PI / 2))
);
navballMesh.position.y = -window.innerHeight / 2 + navballRadius;
var grade;
var factor;
if(new THREE.Vector3(1, 0, 0).applyQuaternion(select_obj.quaternion).dot(select_obj.velocity) < 0){
grade = retrograde;
prograde.visible = false;
factor = -1.;
}
else{
grade = prograde;
retrograde.visible = false;
factor = 1.;
}
grade.visible = true;
grade.position.y = -window.innerHeight / 2 + navballRadius + factor * new THREE.Vector3(0, 1, 0).applyQuaternion(select_obj.quaternion).dot(select_obj.velocity) / select_obj.velocity.length() * navballRadius;
grade.position.x = factor * new THREE.Vector3(0, 0, 1).applyQuaternion(select_obj.quaternion).dot(select_obj.velocity) / select_obj.velocity.length() * navballRadius;
camera.position.set(0,0,0);
camera.quaternion.set(1,0,0,0);
renderer.render( overlay, overlayCamera);
}
// Restore the original state because cameraControls expect these variables unchanged
camera.quaternion.copy(oldQuaternion);
camera.position.copy(oldPosition);
if(select_obj && select_obj.parent){
altitudeControl.setText(select_obj.position.length() * AU - select_obj.parent.radius);
}
else
altitudeControl.setText(0);
}
function onKeyDown( event ) {
var char = String.fromCharCode(event.which || event.keyCode).toLowerCase();
switch ( char ) {
case 'i':
if(select_obj === null)
select_obj = sun.children[0];
else{
// Some objects do not have an orbit
if(select_obj.orbit)
select_obj.orbit.material = select_obj.orbitMaterial;
var objs = select_obj.children;
if(0 < objs.length){
select_obj = objs[0];
}
else{
var selected = false;
var prev = select_obj;
for(var parent = select_obj.parent; parent; parent = parent.parent){
objs = parent.children;
for(var i = 0; i < objs.length; i++){
var o = objs[i];
if(o === prev && i + 1 < objs.length){
select_obj = objs[i+1];
selected = true;
break;
}
}
if(selected)
break;
prev = parent;
}
if(!parent)
select_obj = sun;
}
}
if(select_obj.orbit)
select_obj.orbit.material = selectedOrbitMaterial;
break;
case 'c':
center_select = !center_select;
break;
case 'n': // toggle NLIPS
nlips_enable = !nlips_enable;
break;
case 'g':
grid_enable = !grid_enable;
break;
case 'h':
sync_rotate = !sync_rotate;
break;
case 'k':
units_km = !units_km;
break;
}
if(select_obj && select_obj.controllable) switch( char ){
case 'w': // prograde
buttons.up = true;
// prograde = true;
break;
case 's': // retrograde
buttons.down = true;
// retrograde = true;
break;
case 'q': // normal
buttons.counterclockwise = true;
// normal = true;
break;
case 'e': // normal negative
buttons.clockwise = true;
// antinormal = true;
break;
case 'a': // orbit plane normal
buttons.left = true;
// incline = true;
break;
case 'd': // orbit plane normal negative
buttons.right = true;
// antiincline = true;
break;
case 'z':
throttleControl.setThrottle(1);
break;
case 'x':
throttleControl.setThrottle(0);
break;
}
// Annoying browser incompatibilities
var code = event.which || event.keyCode;
// Also support numpad plus and minus
if(code === 107 || code === 187 && event.shiftKey)
timescaleControl.increment();
if(code === 109 || code === 189)
timescaleControl.decrement();
if(code === 16)
accelerate = true;
if(code === 17)
decelerate = true;
}
function onKeyUp( event ) {
switch ( String.fromCharCode(event.which || event.keyCode).toLowerCase() ) {
case 'w': // prograde
buttons.up = false;
// prograde = false;
break;
case 's':
buttons.down = false;
// retrograde = false;
break;
case 'q': // prograde
buttons.counterclockwise = false;
// normal = false;
break;
case 'e':
buttons.clockwise = false;
// antinormal = false;
break;
case 'a': // orbit plane normal
buttons.left = false;
// incline = false;
break;
case 'd': // orbit plane normal negative
buttons.right = false;
// antiincline = false;
break;
}
// Annoying browser incompatibilities
var code = event.which || event.keyCode;
if(code === 16)
accelerate = false;
if(code === 17)
decelerate = false;
}
init();
animate();
})()
| Further share code with scenarioSelectorControl
| orbiter.js | Further share code with scenarioSelectorControl | <ide><path>rbiter.js
<ide> })
<ide> container.appendChild( messageControl.domElement );
<ide>
<del> scenarioSelectorControl = new (function(){
<del> var buttonTop = 0;
<del> var buttonHeight = 32;
<del> var buttonWidth = 32;
<add> function MenuControl(titleString, iconSrc, config){
<ide> this.domElement = document.createElement('div');
<ide> var element = this.domElement;
<ide> element.style.position = 'absolute';
<ide> element.style.textAlign = 'left';
<del> element.style.top = buttonTop + 'px';
<add> element.style.top = config.buttonTop + 'px';
<ide> element.style.right = 0 + 'px';
<ide> element.style.zIndex = 7;
<del> var icon = document.createElement('img');
<del> icon.src = 'images/menuIcon.png';
<del> icon.style.width = buttonWidth + 'px';
<del> icon.style.height = buttonHeight + 'px';
<del> var visible = false;
<del> element.appendChild(icon);
<add> this.icon = document.createElement('img');
<add> this.icon.src = iconSrc;
<add> this.icon.style.width = config.buttonWidth + 'px';
<add> this.icon.style.height = config.buttonHeight + 'px';
<add> var scope = this;
<add> this.iconMouseOver = false;
<add> this.icon.ondragstart = function(event){
<add> event.preventDefault();
<add> };
<add> this.icon.onclick = function(event){
<add> scope.setVisible(!scope.visible);
<add> };
<add> this.icon.onmouseenter = function(event){
<add> if(!scope.visible)
<add> scope.title.style.display = 'block';
<add> rightTitleSetSize(scope.title, scope.icon);
<add> scope.iconMouseOver = true;
<add> };
<add> this.icon.onmouseleave = function(event){
<add> if(!scope.visible)
<add> scope.title.style.display = 'none';
<add> scope.iconMouseOver = false;
<add> };
<add> element.appendChild(this.icon);
<ide>
<ide> var title = document.createElement('div');
<del> title.innerHTML = 'Scenarios';
<add> title.innerHTML = titleString;
<ide> title.style.display = 'none';
<ide> title.style.position = 'absolute';
<ide> title.style.background = 'rgba(0, 0, 0, 0.5)';
<ide> title.style.zIndex = 20;
<ide> element.appendChild(title);
<add> this.title = title;
<add>
<add> this.visible = false;
<ide>
<ide> var valueElement = document.createElement('div');
<del> // valueElement.style.display = "none";
<del> // valueElement.style.position = "fixed";
<ide> valueElement.style.cssText = "display: none; position: fixed; left: 50%;"
<del> + "width: 300px; top: 50%; background-color: rgba(0,0,0,0.85); border: 5px ridge #ffff7f;"
<del> + "font-size: 25px; text-align: center";
<add> + "width: 300px; top: 50%; background-color: rgba(0,0,0,0.85); border: 5px ridge #7fff7f;"
<add> + "font-size: 15px; text-align: center";
<add> this.valueElement = valueElement;
<add>
<add> var titleElem = document.createElement('div');
<add> titleElem.style.margin = "15px";
<add> titleElem.style.padding = "15px";
<add> titleElem.style.fontSize = '25px';
<add> titleElem.innerHTML = config.innerTitle || titleString;
<add> this.valueElement.appendChild(titleElem);
<add>
<add> this.domElement.appendChild(this.valueElement);
<add> };
<add>
<add> MenuControl.prototype.setVisible = function(v){
<add> this.visible = v;
<add> if(this.visible){
<add> this.valueElement.style.display = 'block';
<add> var rect = this.valueElement.getBoundingClientRect();
<add> this.valueElement.style.marginLeft = -rect.width / 2 + "px";
<add> this.valueElement.style.marginTop = -rect.height / 2 + "px";
<add> }
<add> else{
<add> this.valueElement.style.display = 'none';
<add> if(!this.iconMouseOver)
<add> this.title.style.display = 'none';
<add> }
<add> };
<add>
<add> scenarioSelectorControl = new (function(){
<add> var config = {
<add> buttonTop: 0,
<add> buttonHeight: 32,
<add> buttonWidth: 32,
<add> innerTitle: "Scenario Selector",
<add> };
<add> var scope = this;
<add> MenuControl.call(this, 'Scenarios', 'images/menuIcon.png', config);
<add>
<add> this.valueElement.style.border = "5px ridge #ffff7f";
<ide> var scenarios = [
<ide> {title: "Earth orbit", parent: earth, semimajor_axis: 10000 / AU},
<ide> {title: "Moon orbit", parent: moon, semimajor_axis: 3000 / AU},
<ide> {title: "Venus orbit", parent: venus, semimajor_axis: 10000 / AU, ascending_node: Math.PI},
<ide> {title: "Jupiter orbit", parent: jupiter, semimajor_axis: 100000 / AU},
<ide> ];
<del> var elem = document.createElement('div');
<del> elem.style.margin = "15px";
<del> elem.style.padding = "15px";
<del> elem.innerHTML = "Scenario Selector";
<del> valueElement.appendChild(elem);
<ide> for(var i = 0; i < scenarios.length; i++){
<ide> var elem = document.createElement('div');
<ide> elem.style.margin = "15px";
<ide> rocket.angularVelocity = new THREE.Vector3();
<ide> throttleControl.setThrottle(0);
<ide> rocket.setOrbitingVelocity(scenario.semimajor_axis, rotation);
<del> title.style.display = 'none';
<del> visible = false;
<del> valueElement.style.display = 'none';
<add> messageControl.setText('Scenario ' + scenario.title + ' Loaded!');
<add> scope.title.style.display = 'none';
<add> scope.visible = false;
<add> scope.valueElement.style.display = 'none';
<ide> }
<ide> })(scenarios[i]);
<del> valueElement.appendChild(elem);
<del> }
<del> this.domElement.appendChild(valueElement);
<del>
<del> icon.ondragstart = function(event){
<del> event.preventDefault();
<del> };
<del> icon.onclick = function(event){
<del> visible = !visible;
<del> if(visible){
<del> valueElement.style.display = 'block';
<del> var rect = valueElement.getBoundingClientRect();
<del> valueElement.style.marginLeft = -rect.width / 2 + "px";
<del> valueElement.style.marginTop = -rect.height / 2 + "px";
<del> }
<del> else{
<del> valueElement.style.display = 'none';
<del> }
<del> };
<del> icon.onmouseenter = function(event){
<del> if(!visible)
<del> title.style.display = 'block';
<del> rightTitleSetSize(title, icon);
<del> };
<del> icon.onmouseleave = function(event){
<del> if(!visible)
<del> title.style.display = 'none';
<del> };
<add> this.valueElement.appendChild(elem);
<add> }
<add>
<add> this.setVisible = function(v){
<add> MenuControl.prototype.setVisible.call(this, v);
<add> if(this.visible){
<add> [saveControl, loadControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
<add> }
<add> }
<ide> });
<ide> container.appendChild( scenarioSelectorControl.domElement );
<del>
<del> function MenuControl(titleString, iconSrc, config){
<del> this.domElement = document.createElement('div');
<del> var element = this.domElement;
<del> element.style.position = 'absolute';
<del> element.style.textAlign = 'left';
<del> element.style.top = config.buttonTop + 'px';
<del> element.style.right = 0 + 'px';
<del> element.style.zIndex = 7;
<del> this.icon = document.createElement('img');
<del> this.icon.src = iconSrc;
<del> this.icon.style.width = config.buttonWidth + 'px';
<del> this.icon.style.height = config.buttonHeight + 'px';
<del> var scope = this;
<del> this.icon.ondragstart = function(event){
<del> event.preventDefault();
<del> };
<del> this.icon.onclick = function(event){
<del> scope.setVisible(!scope.visible);
<del> };
<del> this.icon.onmouseenter = function(event){
<del> if(!scope.visible)
<del> scope.title.style.display = 'block';
<del> rightTitleSetSize(scope.title, scope.icon);
<del> };
<del> this.icon.onmouseleave = function(event){
<del> if(!scope.visible)
<del> scope.title.style.display = 'none';
<del> };
<del> element.appendChild(this.icon);
<del>
<del> var title = document.createElement('div');
<del> title.innerHTML = titleString;
<del> title.style.display = 'none';
<del> title.style.position = 'absolute';
<del> title.style.background = 'rgba(0, 0, 0, 0.5)';
<del> title.style.zIndex = 20;
<del> element.appendChild(title);
<del> this.title = title;
<del>
<del> this.visible = false;
<del>
<del> var valueElement = document.createElement('div');
<del> valueElement.style.cssText = "display: none; position: fixed; left: 50%;"
<del> + "width: 300px; top: 50%; background-color: rgba(0,0,0,0.85); border: 5px ridge #7fff7f;"
<del> + "font-size: 15px; text-align: center";
<del> this.valueElement = valueElement;
<del>
<del> var titleElem = document.createElement('div');
<del> titleElem.style.margin = "15px";
<del> titleElem.style.padding = "15px";
<del> titleElem.style.fontSize = '25px';
<del> titleElem.innerHTML = titleString;
<del> this.valueElement.appendChild(titleElem);
<del>
<del> this.domElement.appendChild(this.valueElement);
<del> }
<ide>
<ide> saveControl = new (function(){
<ide> var config = {
<ide> this.valueElement.appendChild(saveContainer);
<ide>
<ide> this.setVisible = function(v){
<del> this.visible = v;
<add> MenuControl.prototype.setVisible.call(this, v);
<ide> if(this.visible){
<del> loadControl.setVisible(false); // Mutually exclusive
<del> this.valueElement.style.display = 'block';
<add> [scenarioSelectorControl, loadControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
<ide> updateSaveDataList();
<del> var rect = this.valueElement.getBoundingClientRect();
<del> this.valueElement.style.marginLeft = -rect.width / 2 + "px";
<del> this.valueElement.style.marginTop = -rect.height / 2 + "px";
<del> }
<del> else{
<del> this.valueElement.style.display = 'none';
<ide> }
<ide> }
<ide> });
<ide> this.valueElement.appendChild(saveContainer);
<ide>
<ide> this.setVisible = function(v){
<del> scope.visible = v;
<add> MenuControl.prototype.setVisible.call(this, v);
<ide> if(scope.visible){
<del> saveControl.setVisible(false); // Mutually exclusive
<del> scope.valueElement.style.display = 'block';
<add> [scenarioSelectorControl, saveControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
<ide> updateSaveDataList();
<del> var rect = scope.valueElement.getBoundingClientRect();
<del> scope.valueElement.style.marginLeft = -rect.width / 2 + "px";
<del> scope.valueElement.style.marginTop = -rect.height / 2 + "px";
<del> }
<del> else{
<del> scope.valueElement.style.display = 'none';
<ide> }
<ide> }
<ide> }); |
|
Java | apache-2.0 | 05a321a5e27a532d5c9577055c663eb017e77ff4 | 0 | invider/trux,invider/trux,invider/trux | package com.decaflabs.trux;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.decaflabs.trux.platform.Platform;
/**
* Represents the planet surface with all objects
*/
public class Geo {
private static final int LINE_WIDTH = 120;
private double length;
private Set<Platform> platforms = new HashSet<Platform>();
public Geo(double length) {
this.length = length;
}
protected double randomTag() {
return Math.random() * this.length;
}
protected void spawn(Platform platform) {
this.platforms.add(platform);
}
protected void kill(Platform platform) {
this.platforms.remove(platform);
}
/**
* select all platforms within range x1..x2
*/
protected List<Platform> select(double x1, double x2) {
List<Platform> res = new LinkedList<Platform>();
for(Platform p: this.platforms) {
if (p.getX() >= x1 && p.getX() < x2) res.add(p);
}
return res;
}
/**
* up
* @param delta
*/
public void mutate(double delta) {
for (Platform p: this.platforms) {
p.mutate(delta);
}
// planet borders correction
for (Platform p: this.platforms) {
if (p.getX() > this.length) p.setX(0);
else if (p.getX() < 0) p.setX(this.length);
}
}
/**
* get carriage return string to erase previous Geo print
*/
public String erase() {
return "\r";
}
/**
* get Geo string representation
*/
public String toString() {
StringBuilder buf = new StringBuilder("");
double step = this.length / this.LINE_WIDTH;
double x = 0;
while (x < this.length) {
List<Platform> platformList = this.select(x, x + step);
if (platformList.size() > 0) {
// represent as a team number of the first element
int team = platformList.get(0).getTeam();
if (team == 0) buf.append('X');
else buf.append("" + team);
} else {
buf.append('_');
}
x += step;
}
return buf.toString();
}
}
| src/main/java/com/decaflabs/trux/Geo.java | package com.decaflabs.trux;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.decaflabs.trux.platform.Platform;
/**
* Represents the planet surface with all objects
*/
public class Geo {
private static final int LINE_WIDTH = 80;
private double length;
private Set<Platform> platforms = new HashSet<Platform>();
public Geo(double length) {
this.length = length;
}
protected double randomTag() {
return Math.random() * this.length;
}
protected void spawn(Platform platform) {
this.platforms.add(platform);
}
protected void kill(Platform platform) {
this.platforms.remove(platform);
}
/**
* select all platforms within range x1..x2
*/
protected List<Platform> select(double x1, double x2) {
List<Platform> res = new LinkedList<Platform>();
for(Platform p: this.platforms) {
if (p.getX() >= x1 && p.getX() < x2) res.add(p);
}
return res;
}
/**
* up
* @param delta
*/
public void mutate(double delta) {
for (Platform p: this.platforms) {
p.mutate(delta);
}
// planet borders correction
for (Platform p: this.platforms) {
if (p.getX() > this.length) p.setX(0);
else if (p.getX() < 0) p.setX(this.length);
}
}
public String erase() {
StringBuilder buf = new StringBuilder("");
for (int i = 0; i < this.LINE_WIDTH; i++) buf.append('\b');
return buf.toString();
}
public String toString() {
StringBuilder buf = new StringBuilder("");
double step = this.length / this.LINE_WIDTH;
double x = 0;
while (x < this.length) {
List<Platform> platformList = this.select(x, x + step);
if (platformList.size() > 0) {
// represent as a team number of the first element
int team = platformList.get(0).getTeam();
if (team == 0) buf.append('X');
else buf.append("" + team);
} else {
buf.append('_');
}
x += step;
}
return buf.toString();
}
}
| [*] improved Geo output
| src/main/java/com/decaflabs/trux/Geo.java | [*] improved Geo output | <ide><path>rc/main/java/com/decaflabs/trux/Geo.java
<ide> */
<ide> public class Geo {
<ide>
<del> private static final int LINE_WIDTH = 80;
<add> private static final int LINE_WIDTH = 120;
<ide>
<ide> private double length;
<ide>
<ide> }
<ide> }
<ide>
<add> /**
<add> * get carriage return string to erase previous Geo print
<add> */
<ide> public String erase() {
<del> StringBuilder buf = new StringBuilder("");
<del> for (int i = 0; i < this.LINE_WIDTH; i++) buf.append('\b');
<del> return buf.toString();
<add> return "\r";
<ide> }
<ide>
<add> /**
<add> * get Geo string representation
<add> */
<ide> public String toString() {
<ide> StringBuilder buf = new StringBuilder("");
<ide> double step = this.length / this.LINE_WIDTH; |
|
Java | apache-2.0 | 4fada9786fec8a5c5292a4d0f0a94fd3138673ff | 0 | shajyhia/score-language,CloudSlang/cloud-slang,narry/cloud-slang,CloudSlang/cloud-slang,jrosadohp/cloud-slang,jrosadohp/cloud-slang,CloudSlang/cloud-slang,CloudSlang/cloud-slang,natabeck/cloud-slang,narry/cloud-slang,shajyhia/score-language,natabeck/cloud-slang | /*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package org.openscore.lang.tools.verifier;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import org.openscore.lang.compiler.SlangCompiler;
import org.openscore.lang.compiler.modeller.model.Executable;
import org.openscore.lang.compiler.modeller.model.SlangFileType;
import org.openscore.lang.compiler.scorecompiler.ScoreCompiler;
import org.openscore.lang.entities.CompilationArtifact;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.openscore.lang.compiler.SlangSource.fromFile;
/*
* Created by stoneo on 2/9/2015.
*/
/**
* Verifies all files with extensions: .sl, .sl.yaml or .sl.yml in a given directory are valid
*/
public class VerifierHelper {
@Autowired
private SlangCompiler slangCompiler;
@Autowired
private ScoreCompiler scoreCompiler;
private final static Logger log = Logger.getLogger(SlangFilesVerifier.class);
private String[] SLANG_FILE_EXTENSIONS = {"sl", "sl.yaml", "sl.yml"};
/**
* Transform all Slang files in given directory to Slang models, and store them
* @param directoryPath given directory containing all Slang files
*/
public void verifyAllSlangFilesInDirAreValid(String directoryPath){
Map<String, Executable> slangModels = transformSlangFilesInDirToModels(directoryPath);
compileAllSlangModels(slangModels);
}
private Map<String, Executable> transformSlangFilesInDirToModels(String directoryPath) {
Validate.notNull(directoryPath, "You mut specify a path");
Map<String, Executable> slangModels = new HashMap<>();
Collection<File> slangFiles = FileUtils.listFiles(new File(directoryPath), SLANG_FILE_EXTENSIONS, true);
log.info("Start compiling all slang files under: " + directoryPath);
log.info(slangFiles.size() + " .sl files were found");
for(File slangFile: slangFiles){
Validate.isTrue(slangFile.isFile(), "file path \'" + slangFile.getAbsolutePath() + "\' must lead to a file");
Executable sourceModel;
try {
sourceModel = slangCompiler.preCompile(fromFile(slangFile));
} catch (Exception e) {
log.error("Failed creating Slang ,models for directory: " + directoryPath + ". Exception is : " + e.getMessage());
throw e;
}
verifyStaticCode(slangFile, sourceModel);
slangModels.put(getUniqueName(sourceModel), sourceModel);
}
if(slangFiles.size() != slangModels.size()){
throw new RuntimeException("Found: " + slangFiles.size() + " .sl files in path: " + directoryPath + ". Managed to create slang models for only: " + slangModels.size());
}
return slangModels;
}
private void compileAllSlangModels(Map<String, Executable> slangModels) {
Collection<Executable> models = slangModels.values();
Map<String, CompilationArtifact> compiledArtifacts = new HashMap<>();
for(Executable slangModel : models) {
try {
Set<Executable> dependenciesModels = getModelDependenciesRecursively(slangModels, slangModel);
CompilationArtifact compiledSource = compiledArtifacts.get(slangModel.getName());
if (compiledSource == null) {
compiledSource = scoreCompiler.compile(slangModel, dependenciesModels);
log.info("Compiled: " + slangModel.getName() + " successfully");
compiledArtifacts.put(slangModel.getName(), compiledSource);
}
} catch (Exception e) {
log.error("Failed compiling Slang source: " + slangModel.getName() + ". Exception is : " + e.getMessage());
throw e;
}
}
if(compiledArtifacts.size() != slangModels.size()){
throw new RuntimeException("Out of: " + slangModels.size() + " slang models, we managed to compile only: " + slangModels.size());
}
String successMessage = "Successfully finished Compilation of: " + compiledArtifacts.size() + " Slang files";
log.info(successMessage);
System.out.println(successMessage);
}
private Set<Executable> getModelDependenciesRecursively(Map<String, Executable> slangModels, Executable slangModel) {
Map<String, SlangFileType> sourceDependencies = slangModel.getDependencies();
Set<Executable> dependenciesModels = new HashSet<>();
for (String dependencyName : sourceDependencies.keySet()) {
Executable dependency = slangModels.get(dependencyName);
if(dependency == null){
throw new RuntimeException("Failed compiling slang source: " + slangModel.getName() + ". Missing dependency: " + dependencyName);
}
dependenciesModels.add(dependency);
dependenciesModels.addAll(getModelDependenciesRecursively(slangModels, dependency));
}
return dependenciesModels;
}
private void verifyStaticCode(File slangFile, Executable executable){
// todo: implement
}
private String getUniqueName(Executable sourceModel) {
return sourceModel.getNamespace() + "." + sourceModel.getName();
}
}
| score-lang-content-verifier/src/main/java/org/openscore/lang/tools/verifier/VerifierHelper.java | /*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package org.openscore.lang.tools.verifier;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import org.openscore.lang.compiler.SlangCompiler;
import org.openscore.lang.compiler.modeller.model.Executable;
import org.openscore.lang.compiler.modeller.model.SlangFileType;
import org.openscore.lang.compiler.scorecompiler.ScoreCompiler;
import org.openscore.lang.entities.CompilationArtifact;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.openscore.lang.compiler.SlangSource.fromFile;
/*
* Created by stoneo on 2/9/2015.
*/
/**
* Verifies all files with extensions: .sl, .sl.yaml or .sl.yml in a given directory are valid
*/
public class VerifierHelper {
@Autowired
private SlangCompiler slangCompiler;
@Autowired
private ScoreCompiler scoreCompiler;
private final static Logger log = Logger.getLogger(SlangFilesVerifier.class);
private String[] SLANG_FILE_EXTENSIONS = {"sl", "sl.yaml", "sl.yml"};
/**
* Transform all Slang files in given directory to Slang models, and store them
* @param directoryPath given directory containing all Slang files
*/
public void verifyAllSlangFilesInDirAreValid(String directoryPath){
Map<String, Executable> slangModels = transformSlangFilesInDirToModels(directoryPath);
compileAllSlangModels(slangModels);
}
private Map<String, Executable> transformSlangFilesInDirToModels(String directoryPath) {
Validate.notNull(directoryPath, "You mut specify a path");
Map<String, Executable> slangModels = new HashMap<>();
Collection<File> slangFiles = FileUtils.listFiles(new File(directoryPath), SLANG_FILE_EXTENSIONS, true);
log.info("Start compiling all slang files under: " + directoryPath);
log.info(slangFiles.size() + " .sl files were found");
for(File slangFile: slangFiles){
Validate.isTrue(slangFile.isFile(), "file path \'" + slangFile.getAbsolutePath() + "\' must lead to a file");
Executable sourceModel;
try {
sourceModel = slangCompiler.preCompile(fromFile(slangFile));
} catch (Exception e) {
log.error("Failed creating Slang ,models for directory: " + directoryPath + ". Exception is : " + e.getMessage());
throw e;
}
verifyStaticCode(slangFile, sourceModel);
slangModels.put(getUniqueName(sourceModel), sourceModel);
}
if(slangFiles.size() != slangModels.size()){
throw new RuntimeException("Found: " + slangFiles.size() + " .sl files in path: " + directoryPath + ". Managed to create slang models for only: " + slangModels.size());
}
return slangModels;
}
private void compileAllSlangModels(Map<String, Executable> slangModels) {
Collection<Executable> models = slangModels.values();
Map<String, CompilationArtifact> compiledArtifacts = new HashMap<>();
for(Executable slangModel : models) {
try {
Set<Executable> dependenciesModels = getModelDependenciesRecursively(slangModels, slangModel);
CompilationArtifact compiledSource = compiledArtifacts.get(slangModel.getName());
if (compiledSource == null) {
compiledSource = scoreCompiler.compile(slangModel, dependenciesModels);
log.info("Compiled: " + slangModel.getName() + " successfully");
compiledArtifacts.put(slangModel.getName(), compiledSource);
} else {
log.error("Failed to compile: " + slangModel.getName());
}
} catch (Exception e) {
log.error("Failed compiling Slang source: " + slangModel.getName() + ". Exception is : " + e.getMessage());
throw e;
}
}
if(compiledArtifacts.size() != slangModels.size()){
throw new RuntimeException("Out of: " + slangModels.size() + " slang models, we managed to compile only: " + slangModels.size());
}
String successMessage = "Successfully finished Compilation of: " + compiledArtifacts.size() + " Slang files";
log.info(successMessage);
System.out.println(successMessage);
}
private Set<Executable> getModelDependenciesRecursively(Map<String, Executable> slangModels, Executable slangModel) {
Map<String, SlangFileType> sourceDependencies = slangModel.getDependencies();
Set<Executable> dependenciesModels = new HashSet<>();
for (String dependencyName : sourceDependencies.keySet()) {
Executable dependency = slangModels.get(dependencyName);
if(dependency == null){
throw new RuntimeException("Failed compiling slang source: " + slangModel.getName() + ". Missing dependency: " + dependencyName);
}
dependenciesModels.add(dependency);
dependenciesModels.addAll(getModelDependenciesRecursively(slangModels, dependency));
}
return dependenciesModels;
}
private void verifyStaticCode(File slangFile, Executable executable){
// todo: implement
}
private String getUniqueName(Executable sourceModel) {
return sourceModel.getNamespace() + "." + sourceModel.getName();
}
}
| Fix a bug - remove unneeded else check
Signed-off-by: Orit Stone <[email protected]>
| score-lang-content-verifier/src/main/java/org/openscore/lang/tools/verifier/VerifierHelper.java | Fix a bug - remove unneeded else check Signed-off-by: Orit Stone <[email protected]> | <ide><path>core-lang-content-verifier/src/main/java/org/openscore/lang/tools/verifier/VerifierHelper.java
<ide> compiledSource = scoreCompiler.compile(slangModel, dependenciesModels);
<ide> log.info("Compiled: " + slangModel.getName() + " successfully");
<ide> compiledArtifacts.put(slangModel.getName(), compiledSource);
<del> } else {
<del> log.error("Failed to compile: " + slangModel.getName());
<ide> }
<ide> } catch (Exception e) {
<ide> log.error("Failed compiling Slang source: " + slangModel.getName() + ". Exception is : " + e.getMessage()); |
|
Java | mit | 48e5326616f88821e928f8eead2c89561305578c | 0 | oleg-nenashev/remoting,jenkinsci/remoting,jenkinsci/remoting,oleg-nenashev/remoting | /*
* The MIT License
*
* Copyright (c) 2010, InfraDNA, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.remoting;
import java.io.OutputStream;
import java.util.logging.Logger;
import static java.util.logging.Level.*;
/**
* Keeps track of the number of bytes that the sender can send without overwhelming the receiver of the pipe.
*
* <p>
* {@link OutputStream} is a blocking operation in Java, so when we send byte[] to the remote to write to
* {@link OutputStream}, it needs to be done in a separate thread (or else we'll fail to attend to the channel
* in timely fashion.) This in turn means the byte[] being sent needs to go to a queue between a
* channel reader thread and I/O processing thread, and thus in turn means we need some kind of throttling
* mechanism, or else the queue can grow too much.
*
* <p>
* This implementation solves the problem by using TCP/IP like window size tracking. The sender allocates
* a fixed length window size. Every time the sender sends something we reduce this value. When the receiver
* writes data to {@link OutputStream}, it'll send back the "ack" command, which adds to this value, allowing
* the sender to send more data.
*
* @author Kohsuke Kawaguchi
*/
abstract class PipeWindow {
abstract void increase(int delta);
abstract int peek();
/**
* Blocks until some space becomes available.
*/
abstract int get() throws InterruptedException;
abstract void decrease(int delta);
/**
* Fake implementation used when the receiver side doesn't support throttling.
*/
static final PipeWindow FAKE = new PipeWindow() {
void increase(int delta) {
}
int peek() {
return Integer.MAX_VALUE;
}
int get() throws InterruptedException {
return Integer.MAX_VALUE;
}
void decrease(int delta) {
}
};
static final class Key {
public final int oid;
Key(int oid) {
this.oid = oid;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
return oid == ((Key) o).oid;
}
@Override
public int hashCode() {
return oid;
}
}
static class Real extends PipeWindow {
private int available;
private long written;
private long acked;
private final int oid;
/**
* The only strong reference to the key, which in turn
* keeps this object accessible in {@link Channel#pipeWindows}.
*/
private final Key key;
Real(Key key, int initialSize) {
this.key = key;
this.oid = key.oid;
this.available = initialSize;
}
public synchronized void increase(int delta) {
if (LOGGER.isLoggable(FINER))
LOGGER.finer(String.format("increase(%d,%d)->%d",oid,delta,delta+available));
available += delta;
acked += delta;
notifyAll();
}
public synchronized int peek() {
return available;
}
/**
* Blocks until some space becomes available.
*
* <p>
* If the window size is empty, induce some delay outside the synchronized block,
* to avoid fragmenting the window size. That is, if a bunch of small ACKs come in a sequence,
* bundle them up into a bigger size before making a call.
*/
public int get() throws InterruptedException {
synchronized (this) {
if (available>0)
return available;
while (available==0) {
wait();
}
}
Thread.sleep(10);
synchronized (this) {
return available;
}
}
public synchronized void decrease(int delta) {
if (LOGGER.isLoggable(FINER))
LOGGER.finer(String.format("decrease(%d,%d)->%d",oid,delta,available-delta));
available -= delta;
written+= delta;
if (available<0)
throw new AssertionError();
}
}
private static final Logger LOGGER = Logger.getLogger(PipeWindow.class.getName());
}
| src/main/java/hudson/remoting/PipeWindow.java | /*
* The MIT License
*
* Copyright (c) 2010, InfraDNA, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.remoting;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.logging.Level.*;
/**
* Keeps track of the number of bytes that the sender can send without overwhelming the receiver of the pipe.
*
* <p>
* {@link OutputStream} is a blocking operation in Java, so when we send byte[] to the remote to write to
* {@link OutputStream}, it needs to be done in a separate thread (or else we'll fail to attend to the channel
* in timely fashion.) This in turn means the byte[] being sent needs to go to a queue between a
* channel reader thread and I/O processing thread, and thus in turn means we need some kind of throttling
* mechanism, or else the queue can grow too much.
*
* <p>
* This implementation solves the problem by using TCP/IP like window size tracking. The sender allocates
* a fixed length window size. Every time the sender sends something we reduce this value. When the receiver
* writes data to {@link OutputStream}, it'll send back the "ack" command, which adds to this value, allowing
* the sender to send more data.
*
* @author Kohsuke Kawaguchi
*/
abstract class PipeWindow {
abstract void increase(int delta);
abstract int peek();
/**
* Blocks until some space becomes available.
*/
abstract int get() throws InterruptedException;
abstract void decrease(int delta);
/**
* Fake implementation used when the receiver side doesn't support throttling.
*/
static final PipeWindow FAKE = new PipeWindow() {
void increase(int delta) {
}
int peek() {
return Integer.MAX_VALUE;
}
int get() throws InterruptedException {
return Integer.MAX_VALUE;
}
void decrease(int delta) {
}
};
static final class Key {
public final int oid;
Key(int oid) {
this.oid = oid;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
return oid == ((Key) o).oid;
}
@Override
public int hashCode() {
return oid;
}
}
static class Real extends PipeWindow {
private int available;
private long written;
private long acked;
private final int oid;
/**
* The only strong reference to the key, which in turn
* keeps this object accessible in {@link Channel#pipeWindows}.
*/
private final Key key;
Real(Key key, int initialSize) {
this.key = key;
this.oid = key.oid;
this.available = initialSize;
}
public synchronized void increase(int delta) {
if (LOGGER.isLoggable(INFO))
LOGGER.info(String.format("increase(%d,%d)->%d",oid,delta,delta+available));
available += delta;
acked += delta;
notifyAll();
}
public synchronized int peek() {
return available;
}
/**
* Blocks until some space becomes available.
*
* <p>
* If the window size is empty, induce some delay outside the synchronized block,
* to avoid fragmenting the window size. That is, if a bunch of small ACKs come in a sequence,
* bundle them up into a bigger size before making a call.
*/
public int get() throws InterruptedException {
synchronized (this) {
if (available>0)
return available;
while (available==0) {
wait();
}
}
Thread.sleep(10);
synchronized (this) {
return available;
}
}
public synchronized void decrease(int delta) {
if (LOGGER.isLoggable(INFO))
LOGGER.info(String.format("decrease(%d,%d)->%d",oid,delta,available-delta));
available -= delta;
written+= delta;
if (available<0)
throw new AssertionError();
}
}
private static final Logger LOGGER = Logger.getLogger(PipeWindow.class.getName());
}
| [HUDSON-7572] debug logging code crept in. Meant to be FINER, not INFO.
git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@35531 71c3de6d-444a-0410-be80-ed276b4c234a
| src/main/java/hudson/remoting/PipeWindow.java | [HUDSON-7572] debug logging code crept in. Meant to be FINER, not INFO. | <ide><path>rc/main/java/hudson/remoting/PipeWindow.java
<ide> package hudson.remoting;
<ide>
<ide> import java.io.OutputStream;
<del>import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide>
<ide> import static java.util.logging.Level.*;
<ide> }
<ide>
<ide> public synchronized void increase(int delta) {
<del> if (LOGGER.isLoggable(INFO))
<del> LOGGER.info(String.format("increase(%d,%d)->%d",oid,delta,delta+available));
<add> if (LOGGER.isLoggable(FINER))
<add> LOGGER.finer(String.format("increase(%d,%d)->%d",oid,delta,delta+available));
<ide> available += delta;
<ide> acked += delta;
<ide> notifyAll();
<ide> }
<ide>
<ide> public synchronized void decrease(int delta) {
<del> if (LOGGER.isLoggable(INFO))
<del> LOGGER.info(String.format("decrease(%d,%d)->%d",oid,delta,available-delta));
<add> if (LOGGER.isLoggable(FINER))
<add> LOGGER.finer(String.format("decrease(%d,%d)->%d",oid,delta,available-delta));
<ide> available -= delta;
<ide> written+= delta;
<ide> if (available<0) |
|
Java | mit | d60c8362bda3770f848721d41f766a7547c533b4 | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | ///////////////////////////////////////////////////////////////////////////////
//FILE: ReportingUtils.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//
// AUTHOR: Arthur Edelstein, June 2009
//
// COPYRIGHT: University of California, San Francisco, 2009
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.utils;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Calendar;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import mmcorej.CMMCore;
import org.micromanager.MMStudio;
/**
*
* @author arthur
*/
public class ReportingUtils {
private static CMMCore core_ = null;
private static JFrame owningFrame_;
private static boolean show_ = true;
// Intended for setting to the main frame.
public static void SetContainingFrame(JFrame f) {
owningFrame_ = f;
}
public static void setCore(CMMCore core) {
core_ = core;
}
public static void showErrorOn(boolean show) {
show_ = show;
}
public static void logMessage(String msg) {
if (core_ == null) {
System.out.println(msg);
} else {
core_.logMessage(msg);
}
}
public static void logDebugMessage(String msg) {
if (core_ == null) {
System.out.println(msg);
} else {
core_.logMessage(msg, true);
}
}
public static void showMessage(final String msg) {
JOptionPane.showMessageDialog(null, msg);
}
public static void showMessage(final String msg, Component parent) {
JOptionPane.showMessageDialog(parent, msg);
}
public static void logError(Throwable e, String msg) {
if (e != null) {
String stackTrace = getStackTraceAsString(e);
logMessage(msg + "\n" + e.toString() + " in "
+ Thread.currentThread().toString() + "\n" + stackTrace + "\n");
} else {
logMessage("Error: " + msg);
}
}
public static void logError(Throwable e) {
logError(e, "");
}
public static void logError(String msg) {
logError(null, msg);
}
public static void showError(Throwable e, String msg, Component parent) {
logError(e, msg);
if (!show_)
return;
String fullMsg;
if (e != null && e.getMessage() != null && msg.length() > 0) {
fullMsg = "Error: " + msg + "\n" + e.getMessage();
} else if (e != null && e.getMessage() != null) {
fullMsg = e.getMessage();
} else if (msg.length() > 0) {
fullMsg = "Error: " + msg;
} else if (e != null) {
fullMsg = "Error: " + e.getStackTrace()[0];
} else {
fullMsg = "Unknown error (please check CoreLog.txt file for more information)";
}
ReportingUtils.showErrorMessage(fullMsg, parent);
}
private static String formatAlertMessage(String[] lines) {
com.google.common.escape.Escaper escaper =
com.google.common.html.HtmlEscapers.htmlEscaper();
StringBuilder sb = new StringBuilder();
sb.append("<html>");
for (String line : lines) {
sb.append("<div width='640'>");
sb.append(escaper.escape(line));
sb.append("</div>");
}
sb.append("</html>");
return sb.toString();
}
private static void showErrorMessage(final String fullMsg, final Component parent) {
int maxNrLines = 10;
String lines[] = fullMsg.split("\n");
if (lines.length < maxNrLines) {
String wrappedMsg = formatAlertMessage(lines);
JOptionPane.showMessageDialog(parent, wrappedMsg,
"Micro-Manager Error", JOptionPane.ERROR_MESSAGE);
} else {
JTextArea area = new JTextArea(fullMsg);
area.setRows(maxNrLines);
area.setColumns(50);
area.setLineWrap(true);
JScrollPane pane = new JScrollPane(area);
JOptionPane.showMessageDialog(parent, pane,
"Micro-Manager Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void showError(Throwable e) {
showError(e, "", MMStudio.getFrame());
}
public static void showError(String msg) {
showError(null, msg, MMStudio.getFrame());
}
public static void showError(Throwable e, String msg) {
showError(e, msg, MMStudio.getFrame());
}
public static void showError(Throwable e, Component parent) {
showError(e, "", parent);
}
public static void showError(String msg, Component parent) {
showError(null, msg, parent);
}
private static String getStackTraceAsString(Throwable aThrowable) {
String result = "";
for (StackTraceElement line : aThrowable.getStackTrace()) {
result += " at " + line.toString() + "\n";
}
Throwable cause = aThrowable.getCause();
if (cause != null) {
return result + "Caused by: " + cause.toString() + "\n" + getStackTraceAsString(cause);
} else {
return result;
}
}
/**
* As above, but doesn't require a Throwable; a convenience function for
* logging when you want to know where you were called from.
*/
public static String getStackTraceAsString() {
String result = "";
for (StackTraceElement line : java.lang.Thread.currentThread().getStackTrace()) {
result += " at " + line.toString() + "\n";
}
return result;
}
/**
* As above, but only the caller is returned, not the entire trace.
*/
public static String getCaller() {
// First is getStackTrace, second is us, third is whoever called us,
// fourth is whoever called *them*.
return java.lang.Thread.currentThread().getStackTrace()[3].toString();
}
public static void showError(ActionEvent e) {
throw new UnsupportedOperationException("Not yet implemented");
}
public static void displayNonBlockingMessage(final String message) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ReportingUtils.displayNonBlockingMessage(message);
}
});
return;
}
if (null != owningFrame_) {
Calendar c = Calendar.getInstance();
final JOptionPane optionPane = new JOptionPane(c.getTime().toString() + " " + message, JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
/* the false parameter is for not modal */
final JDialog dialog = new JDialog(owningFrame_, "μManager Warning: ", false);
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (dialog.isVisible() && (e.getSource() == optionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
dialog.setVisible(false);
}
}
});
dialog.setContentPane(optionPane);
/* adapting the frame size to its content */
dialog.pack();
dialog.setLocationRelativeTo(owningFrame_);
dialog.setVisible(true);
}
}
}
| mmstudio/src/org/micromanager/utils/ReportingUtils.java | ///////////////////////////////////////////////////////////////////////////////
//FILE: ReportingUtils.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//
// AUTHOR: Arthur Edelstein, June 2009
//
// COPYRIGHT: University of California, San Francisco, 2009
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.utils;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Calendar;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import mmcorej.CMMCore;
import org.micromanager.MMStudio;
/**
*
* @author arthur
*/
public class ReportingUtils {
private static CMMCore core_ = null;
private static JFrame owningFrame_;
private static boolean show_ = true;
// Intended for setting to the main frame.
public static void SetContainingFrame(JFrame f) {
owningFrame_ = f;
}
public static void setCore(CMMCore core) {
core_ = core;
}
public static void showErrorOn(boolean show) {
show_ = show;
}
public static void logMessage(String msg) {
if (core_ == null) {
System.out.println(msg);
} else {
core_.logMessage(msg);
}
}
public static void showMessage(final String msg) {
JOptionPane.showMessageDialog(null, msg);
}
public static void showMessage(final String msg, Component parent) {
JOptionPane.showMessageDialog(parent, msg);
}
public static void logError(Throwable e, String msg) {
if (e != null) {
String stackTrace = getStackTraceAsString(e);
logMessage(msg + "\n" + e.toString() + " in "
+ Thread.currentThread().toString() + "\n" + stackTrace + "\n");
} else {
logMessage("Error: " + msg);
}
}
public static void logError(Throwable e) {
logError(e, "");
}
public static void logError(String msg) {
logError(null, msg);
}
public static void showError(Throwable e, String msg, Component parent) {
logError(e, msg);
if (!show_)
return;
String fullMsg;
if (e != null && e.getMessage() != null && msg.length() > 0) {
fullMsg = "Error: " + msg + "\n" + e.getMessage();
} else if (e != null && e.getMessage() != null) {
fullMsg = e.getMessage();
} else if (msg.length() > 0) {
fullMsg = "Error: " + msg;
} else if (e != null) {
fullMsg = "Error: " + e.getStackTrace()[0];
} else {
fullMsg = "Unknown error (please check CoreLog.txt file for more information)";
}
ReportingUtils.showErrorMessage(fullMsg, parent);
}
private static String formatAlertMessage(String[] lines) {
com.google.common.escape.Escaper escaper =
com.google.common.html.HtmlEscapers.htmlEscaper();
StringBuilder sb = new StringBuilder();
sb.append("<html>");
for (String line : lines) {
sb.append("<div width='640'>");
sb.append(escaper.escape(line));
sb.append("</div>");
}
sb.append("</html>");
return sb.toString();
}
private static void showErrorMessage(final String fullMsg, final Component parent) {
int maxNrLines = 10;
String lines[] = fullMsg.split("\n");
if (lines.length < maxNrLines) {
String wrappedMsg = formatAlertMessage(lines);
JOptionPane.showMessageDialog(parent, wrappedMsg,
"Micro-Manager Error", JOptionPane.ERROR_MESSAGE);
} else {
JTextArea area = new JTextArea(fullMsg);
area.setRows(maxNrLines);
area.setColumns(50);
area.setLineWrap(true);
JScrollPane pane = new JScrollPane(area);
JOptionPane.showMessageDialog(parent, pane,
"Micro-Manager Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void showError(Throwable e) {
showError(e, "", MMStudio.getFrame());
}
public static void showError(String msg) {
showError(null, msg, MMStudio.getFrame());
}
public static void showError(Throwable e, String msg) {
showError(e, msg, MMStudio.getFrame());
}
public static void showError(Throwable e, Component parent) {
showError(e, "", parent);
}
public static void showError(String msg, Component parent) {
showError(null, msg, parent);
}
private static String getStackTraceAsString(Throwable aThrowable) {
String result = "";
for (StackTraceElement line : aThrowable.getStackTrace()) {
result += " at " + line.toString() + "\n";
}
Throwable cause = aThrowable.getCause();
if (cause != null) {
return result + "Caused by: " + cause.toString() + "\n" + getStackTraceAsString(cause);
} else {
return result;
}
}
/**
* As above, but doesn't require a Throwable; a convenience function for
* logging when you want to know where you were called from.
*/
public static String getStackTraceAsString() {
String result = "";
for (StackTraceElement line : java.lang.Thread.currentThread().getStackTrace()) {
result += " at " + line.toString() + "\n";
}
return result;
}
/**
* As above, but only the caller is returned, not the entire trace.
*/
public static String getCaller() {
// First is getStackTrace, second is us, third is whoever called us,
// fourth is whoever called *them*.
return java.lang.Thread.currentThread().getStackTrace()[3].toString();
}
public static void showError(ActionEvent e) {
throw new UnsupportedOperationException("Not yet implemented");
}
public static void displayNonBlockingMessage(final String message) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ReportingUtils.displayNonBlockingMessage(message);
}
});
return;
}
if (null != owningFrame_) {
Calendar c = Calendar.getInstance();
final JOptionPane optionPane = new JOptionPane(c.getTime().toString() + " " + message, JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
/* the false parameter is for not modal */
final JDialog dialog = new JDialog(owningFrame_, "μManager Warning: ", false);
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (dialog.isVisible() && (e.getSource() == optionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
dialog.setVisible(false);
}
}
});
dialog.setContentPane(optionPane);
/* adapting the frame size to its content */
dialog.pack();
dialog.setLocationRelativeTo(owningFrame_);
dialog.setVisible(true);
}
}
}
| ReportingUtils: Add logDebugMessage() (suggested by Jon Daniels)
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@14833 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| mmstudio/src/org/micromanager/utils/ReportingUtils.java | ReportingUtils: Add logDebugMessage() (suggested by Jon Daniels) | <ide><path>mstudio/src/org/micromanager/utils/ReportingUtils.java
<ide> System.out.println(msg);
<ide> } else {
<ide> core_.logMessage(msg);
<add> }
<add> }
<add>
<add> public static void logDebugMessage(String msg) {
<add> if (core_ == null) {
<add> System.out.println(msg);
<add> } else {
<add> core_.logMessage(msg, true);
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | 3d11522b08a1fa72e734dde4210c98d75f81d648 | 0 | orbitdb/orbit-db,orbitdb/orbit-db,haadcode/orbit-db,haadcode/orbit-db | 'use strict'
const assert = require('assert')
const mapSeries = require('p-each-series')
const rmrf = require('rimraf')
const OrbitDB = require('../src/OrbitDB')
// Include test utilities
const {
config,
startIpfs,
stopIpfs,
testAPIs,
connectPeers,
waitForPeers,
} = require('./utils')
const dbPath1 = './orbitdb/tests/replicate-and-load/1'
const dbPath2 = './orbitdb/tests/replicate-and-load/2'
const ipfsPath1 = './orbitdb/tests/replicate-and-load/1/ipfs'
const ipfsPath2 = './orbitdb/tests/replicate-and-load/2/ipfs'
Object.keys(testAPIs).forEach(API => {
describe(`orbit-db - Replicate and Load (${API})`, function() {
this.timeout(config.timeout * 2)
let ipfsd1, ipfsd2, ipfs1, ipfs2
let orbitdb1, orbitdb2, db1, db2
before(async () => {
config.daemon1.repo = ipfsPath1
config.daemon2.repo = ipfsPath2
rmrf.sync(config.daemon1.repo)
rmrf.sync(config.daemon2.repo)
rmrf.sync(dbPath1)
rmrf.sync(dbPath2)
ipfsd1 = await startIpfs(API, config.daemon1)
ipfsd2 = await startIpfs(API, config.daemon2)
ipfs1 = ipfsd1.api
ipfs2 = ipfsd2.api
orbitdb1 = await OrbitDB.createInstance(ipfs1, { directory: dbPath1 })
orbitdb2 = await OrbitDB.createInstance(ipfs2, { directory: dbPath2 })
// Connect the peers manually to speed up test times
await connectPeers(ipfs1, ipfs2)
})
after(async () => {
if(orbitdb1)
await orbitdb1.stop()
if(orbitdb2)
await orbitdb2.stop()
if (ipfsd1)
await stopIpfs(ipfsd1)
if (ipfsd2)
await stopIpfs(ipfsd2)
})
describe('two peers', function() {
// Opens two databases db1 and db2 and gives write-access to both of the peers
const openDatabases1 = async (options) => {
// Set write access for both clients
options.write = [
orbitdb1.identity.publicKey,
orbitdb2.identity.publicKey
],
options = Object.assign({}, options, { path: dbPath1 })
db1 = await orbitdb1.eventlog('replicate-and-load-tests', options)
// Set 'localOnly' flag on and it'll error if the database doesn't exist locally
options = Object.assign({}, options, { path: dbPath2 })
db2 = await orbitdb2.eventlog(db1.address.toString(), options)
}
const openDatabases = async (options) => {
// Set write access for both clients
options.write = [
orbitdb1.identity.publicKey,
orbitdb2.identity.publicKey
],
options = Object.assign({}, options, { path: dbPath1, create: true })
db1 = await orbitdb1.eventlog('tests', options)
// Set 'localOnly' flag on and it'll error if the database doesn't exist locally
options = Object.assign({}, options, { path: dbPath2 })
db2 = await orbitdb2.eventlog(db1.address.toString(), options)
}
beforeEach(async () => {
await openDatabases({ sync: true })
assert.equal(db1.address.toString(), db2.address.toString())
console.log("Waiting for peers...")
await waitForPeers(ipfs1, [orbitdb2.id], db1.address.toString())
await waitForPeers(ipfs2, [orbitdb1.id], db1.address.toString())
console.log("Found peers")
})
afterEach(async () => {
await db1.drop()
await db2.drop()
})
it('replicates database of 100 entries and loads it from the disk', async () => {
const entryCount = 100
const entryArr = []
let timer
for (let i = 0; i < entryCount; i ++)
entryArr.push(i)
console.log("Writing to database...")
await mapSeries(entryArr, (i) => db1.add('hello' + i))
console.log("Done")
return new Promise((resolve, reject) => {
timer = setInterval(async () => {
if (db2._oplog.length === entryCount) {
clearInterval(timer)
const items = db2.iterator({ limit: -1 }).collect()
assert.equal(items.length, entryCount)
assert.equal(items[0].payload.value, 'hello0')
assert.equal(items[items.length - 1].payload.value, 'hello99')
db2 = null
try {
// Set write access for both clients
let options = {
accessController: {
write: [
orbitdb1.identity.id,
orbitdb2.identity.id
]
}
}
// Get the previous address to make sure nothing mutates it
const addr = db1.address.toString()
// Open the database again (this time from the disk)
options = Object.assign({}, options, { path: dbPath1, create: false })
db1 = await orbitdb1.eventlog(addr, options)
// Set 'localOnly' flag on and it'll error if the database doesn't exist locally
options = Object.assign({}, options, { path: dbPath2, localOnly: true })
db2 = await orbitdb2.eventlog(addr, options)
await db1.load()
await db2.load()
// Make sure we have all the entries in the databases
const result1 = db1.iterator({ limit: -1 }).collect()
const result2 = db2.iterator({ limit: -1 }).collect()
assert.equal(result1.length, entryCount)
assert.equal(result2.length, entryCount)
} catch (e) {
reject(e)
}
resolve()
}
}, 100)
})
})
})
})
})
| test/replicate-and-load.test.js | 'use strict'
const assert = require('assert')
const mapSeries = require('p-each-series')
const rmrf = require('rimraf')
const OrbitDB = require('../src/OrbitDB')
// Include test utilities
const {
config,
startIpfs,
stopIpfs,
testAPIs,
connectPeers,
waitForPeers,
} = require('./utils')
const dbPath1 = './orbitdb/tests/replicate-and-load/1'
const dbPath2 = './orbitdb/tests/replicate-and-load/2'
const ipfsPath1 = './orbitdb/tests/replicate-and-load/1/ipfs'
const ipfsPath2 = './orbitdb/tests/replicate-and-load/2/ipfs'
Object.keys(testAPIs).forEach(API => {
describe(`orbit-db - Replicate and Load (${API})`, function() {
this.timeout(config.timeout)
let ipfsd1, ipfsd2, ipfs1, ipfs2
let orbitdb1, orbitdb2, db1, db2
before(async () => {
config.daemon1.repo = ipfsPath1
config.daemon2.repo = ipfsPath2
rmrf.sync(config.daemon1.repo)
rmrf.sync(config.daemon2.repo)
rmrf.sync(dbPath1)
rmrf.sync(dbPath2)
ipfsd1 = await startIpfs(API, config.daemon1)
ipfsd2 = await startIpfs(API, config.daemon2)
ipfs1 = ipfsd1.api
ipfs2 = ipfsd2.api
orbitdb1 = await OrbitDB.createInstance(ipfs1, { directory: dbPath1 })
orbitdb2 = await OrbitDB.createInstance(ipfs2, { directory: dbPath2 })
// Connect the peers manually to speed up test times
await connectPeers(ipfs1, ipfs2)
})
after(async () => {
if(orbitdb1)
await orbitdb1.stop()
if(orbitdb2)
await orbitdb2.stop()
if (ipfsd1)
await stopIpfs(ipfsd1)
if (ipfsd2)
await stopIpfs(ipfsd2)
})
describe('two peers', function() {
// Opens two databases db1 and db2 and gives write-access to both of the peers
const openDatabases1 = async (options) => {
// Set write access for both clients
options.write = [
orbitdb1.identity.publicKey,
orbitdb2.identity.publicKey
],
options = Object.assign({}, options, { path: dbPath1 })
db1 = await orbitdb1.eventlog('replicate-and-load-tests', options)
// Set 'localOnly' flag on and it'll error if the database doesn't exist locally
options = Object.assign({}, options, { path: dbPath2 })
db2 = await orbitdb2.eventlog(db1.address.toString(), options)
}
const openDatabases = async (options) => {
// Set write access for both clients
options.write = [
orbitdb1.identity.publicKey,
orbitdb2.identity.publicKey
],
options = Object.assign({}, options, { path: dbPath1, create: true })
db1 = await orbitdb1.eventlog('tests', options)
// Set 'localOnly' flag on and it'll error if the database doesn't exist locally
options = Object.assign({}, options, { path: dbPath2 })
db2 = await orbitdb2.eventlog(db1.address.toString(), options)
}
beforeEach(async () => {
await openDatabases({ sync: true })
assert.equal(db1.address.toString(), db2.address.toString())
console.log("Waiting for peers...")
await waitForPeers(ipfs1, [orbitdb2.id], db1.address.toString())
await waitForPeers(ipfs2, [orbitdb1.id], db1.address.toString())
console.log("Found peers")
})
afterEach(async () => {
await db1.drop()
await db2.drop()
})
it('replicates database of 100 entries and loads it from the disk', async () => {
const entryCount = 100
const entryArr = []
let timer
for (let i = 0; i < entryCount; i ++)
entryArr.push(i)
await mapSeries(entryArr, (i) => db1.add('hello' + i))
return new Promise((resolve, reject) => {
timer = setInterval(async () => {
const items = db2.iterator({ limit: -1 }).collect()
if (items.length === entryCount) {
clearInterval(timer)
assert.equal(items.length, entryCount)
assert.equal(items[0].payload.value, 'hello0')
assert.equal(items[items.length - 1].payload.value, 'hello99')
db2 = null
try {
// Set write access for both clients
let options = {
accessController: {
write: [
orbitdb1.identity.id,
orbitdb2.identity.id
]
}
}
// Get the previous address to make sure nothing mutates it
const addr = db1.address.toString()
// Open the database again (this time from the disk)
options = Object.assign({}, options, { path: dbPath1, create: false })
db1 = await orbitdb1.eventlog(addr, options)
// Set 'localOnly' flag on and it'll error if the database doesn't exist locally
options = Object.assign({}, options, { path: dbPath2, localOnly: true })
db2 = await orbitdb2.eventlog(addr, options)
await db1.load()
await db2.load()
// Make sure we have all the entries in the databases
const result1 = db1.iterator({ limit: -1 }).collect()
const result2 = db2.iterator({ limit: -1 }).collect()
assert.equal(result1.length, entryCount)
assert.equal(result2.length, entryCount)
} catch (e) {
reject(e)
}
resolve()
}
}, 100)
})
})
})
})
})
| Increase replication test timeout
| test/replicate-and-load.test.js | Increase replication test timeout | <ide><path>est/replicate-and-load.test.js
<ide>
<ide> Object.keys(testAPIs).forEach(API => {
<ide> describe(`orbit-db - Replicate and Load (${API})`, function() {
<del> this.timeout(config.timeout)
<add> this.timeout(config.timeout * 2)
<ide>
<ide> let ipfsd1, ipfsd2, ipfs1, ipfs2
<ide> let orbitdb1, orbitdb2, db1, db2
<ide> for (let i = 0; i < entryCount; i ++)
<ide> entryArr.push(i)
<ide>
<add> console.log("Writing to database...")
<ide> await mapSeries(entryArr, (i) => db1.add('hello' + i))
<add> console.log("Done")
<ide>
<ide> return new Promise((resolve, reject) => {
<ide> timer = setInterval(async () => {
<del> const items = db2.iterator({ limit: -1 }).collect()
<del> if (items.length === entryCount) {
<add> if (db2._oplog.length === entryCount) {
<ide> clearInterval(timer)
<add>
<add> const items = db2.iterator({ limit: -1 }).collect()
<ide> assert.equal(items.length, entryCount)
<ide> assert.equal(items[0].payload.value, 'hello0')
<ide> assert.equal(items[items.length - 1].payload.value, 'hello99') |
|
JavaScript | apache-2.0 | 0153ec021ae29b2ae6a9811cf5258ddc682967d9 | 0 | atomjump/medimage,atomjump/medimage | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//Source code Copyright (c) 2018 AtomJump Ltd. (New Zealand)
var deleteThisFile = {}; //Global object for image taken, to be deleted
var centralPairingUrl = "https://atomjump.com/med-genid.php"; //Redirects to an https connection. In future try setting to http://atomjump.org/med-genid.php
var glbThis = {}; //Used as a global error handler
var retryIfNeeded = []; //A global pushable list with the repeat attempts
var checkComplete = []; //A global pushable list with the repeat checks to see if image is on PC
var retryNum = 0;
//See: https://stackoverflow.com/questions/14787705/phonegap-cordova-filetransfer-abort-not-working-as-expected
// basic implementation of hash map of FileTransfer objects
// so that given a key, an abort function can find the right FileTransfer to abort
function SimpleHashMap()
{
this.items = {};
this.setItem = function(key, value) { this.items[key] = value; }
this.getItem = function(key)
{
if (this.hasItem(key)) { return this.items[key]; }
return undefined;
}
this.hasItem = function(key) { return this.items.hasOwnProperty(key); }
this.removeItem = function(key)
{
if (this.hasItem(key)) { delete this.items[key]; }
}
}
var fileTransferMap = new SimpleHashMap();
var app = {
// Application Constructor
initialize: function() {
glbThis = this;
this.bindEvents();
//Set display name
this.displayServerName();
//Initialise the id field
this.displayIdInput();
//Check if there are any residual photos that need to be sent again
glbThis.loopLocalPhotos();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
if(parentElement) {
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
} else {
console.log('Failed Received Event: ' + id);
}
},
processPicture: function(imageURIin)
{
var _this = this;
glbThis = this;
//Called from takePicture(), after the image file URI has been shifted into a persistent file
//Reconnect once
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
var thisImageURI = imageURIin;
var idEntered = document.getElementById("id-entered").value;
_this.findServer(function(err) {
if(err) {
glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds.");
//Search again in 10 seconds:
var passedImageURI = thisImageURI;
var idEnteredB = idEntered;
setTimeout(function() {
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
glbThis.uploadPhoto(passedImageURI, idEnteredB, newFilename);
}, 10000);
} else {
//Now we are connected - so we can get the filename
_this.determineFilename(thisImageURI, idEntered, function(err, newFilename, imageURI) {
if(err) {
//There was a problem getting the filename from the disk file
glbThis.notify("Sorry, we cannot process the filename of the photo " + idEntered + ". If this happens consistently, please report the problem to medimage.co.nz");
} else {
//Store in case the app quits unexpectably
_this.recordLocalPhoto( imageURI, idEntered, newFilename);
//Now we are connected, upload the photo again
glbThis.uploadPhoto(imageURI, idEntered, newFilename);
}
});
}
});
},
takePicture: function() {
var _this = this;
glbThis = this;
navigator.camera.getPicture( function( imageURI ) {
//Move picture into persistent storage
//Grab the file name of the photo in the temporary directory
var currentName = imageURI.replace(/^.*[\\\/]/, '');
//Create a new name for the photo
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
window.resolveLocalFileSystemURI( imageURI, function(fileEntry) {
var myFile = fileEntry;
try {
//Try moving the file to permanent storage
window.resolveLocalFileSystemURL( cordova.file.dataDirectory,
function(directory) {
try {
myFile.moveTo(directory, newFileName, function(success){
//Moved it to permanent storage successfully
//success.fullPath contains the path to the photo in permanent storage
if(success.nativeURL) {
glbThis.processPicture(success.nativeURL);
} else {
glbThis.notify("Sorry we could not find the moved photo on the phone. Please let medimage.co.nz know that a moveFile() has not worked correctly.");
}
}, function(err){
//an error occured moving file - send anyway, even if it is in the temporary folder
glbThis.processPicture(imageURI);
});
} catch(err) {
//A problem moving the file but send the temp file anyway
glbThis.processPicture(imageURI);
}
}, function(err) {
//an error occured moving file - send anyway, even if it is in the temporary folder
glbThis.processPicture(imageURI);
});
} catch(err) {
//A proble occured determining if the persistent folder existed
glbThis.processPicture(imageURI);
}
},
function(err) {
//Could not resolve local file
glbThis.notify("Sorry we could not find the photo on the phone.");
});
},
function( message ) {
//An error or cancellation
glbThis.notify( message );
},
{
quality: 100,
destinationType: Camera.DestinationType.FILE_URI
});
},
recordLocalPhoto: function(imageURI, idEntered, fileName) {
//Save into our localPhotos array, in case the app quits
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
var newPhoto = {
"imageURI" : imageURI,
"idEntered" : idEntered,
"fileName" : fileName,
"status" : "send"
}; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel'
localPhotos.push(newPhoto);
glbThis.setArrayLocalStorage("localPhotos", localPhotos);
return true;
},
arrayRemoveNulls: function(arr) {
var newArray = [];
for(var cnt = 0; cnt < arr.length; cnt++) {
if(arr[cnt] && arr[cnt] != null) {
newArray.push(arr[cnt]);
}
}
return newArray;
},
removeLocalPhoto: function(imageURI) {
//Loop through the current array and remove
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
for(var cnt = 0; cnt< localPhotos.length; cnt++) {
if(localPhotos[cnt].imageURI === imageURI) {
localPhotos[cnt] = null; //Need the delete first to get rid of subobjects
localPhotos = glbThis.arrayRemoveNulls(localPhotos);
//Set back the storage of the array
glbThis.setArrayLocalStorage("localPhotos", localPhotos);
return;
}
}
},
changeLocalPhotoStatus: function(imageURI, newStatus, fullData) {
//Input:
//imageURI - unique image address on phone filesystem
//newStatus can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel'
//If onserver, the optional parameter 'fullGet', is the URL to call to check if the file is back on the server
//Note: during the cancel, each removeLocalPhoto could occur at any time (async) depending on the filesystem speed,
//so the removeLocalPhoto does a sync load, delete from array, and write back.
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
for(var cnt = 0; cnt< localPhotos.length; cnt++) {
if(localPhotos[cnt].imageURI === imageURI) {
if(newStatus === "cancel") {
//Delete the photo
window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
//Remove the file from the phone
fileEntry.remove();
//Remove entry from the array
glbThis.removeLocalPhoto(imageURI);
}, function(evt) {
//Some form of error case. We likely couldn't find the file, but we still want to remove the entry from the array
//in this case
var errorCode = null;
if(evt.code) {
errorCode = evt.code;
}
if(evt.target && evt.target.error.code) {
errorCode = evt.target.error.code;
}
if(errorCode === 1) {
//The photo is not there. Remove anyway
//Remove entry from the array
glbThis.removeLocalPhoto(imageURI);
} else {
glbThis.notify("Sorry, there was a problem removing the photo on the phone. Error code: " + evt.target.error.code);
//Remove entry from the array
glbThis.removeLocalPhoto(imageURI);
}
});
} else {
localPhotos[cnt].status = newStatus;
if((newStatus == "onserver")&&(fullData)) {
localPhotos[cnt].fullData = fullData;
}
//Set back the storage of the array
glbThis.setArrayLocalStorage("localPhotos", localPhotos);
}
}
}
//Note: don't put any post proccessing down here. The resolveLocalFileSystem is async.
},
loopLocalPhotos: function() {
//Get a photo, one at a time, in the array format:
/* {
"imageURI" : imageURI,
"idEntered" : idEntered,
"fileName" : fileName,
"fullData" : fullDataObject - optional
"status" : "send"
}; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel'
and attempt to upload them.
*/
var photoDetails = null;
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
for(var cnt = 0; cnt< localPhotos.length; cnt++) {
var newPhoto = localPhotos[cnt];
if(newPhoto) {
if(newPhoto.status == 'onserver') {
//OK - so it was successfully put onto the server. Recheck to see if it needs to be uploaded again
if(newPhoto.fullData) {
try {
var fullData = newPhoto.fullData;
if(fullData.details && fullData.details.imageURI) {
fullData.loopCnt = 11;
fullData.slowLoopCnt = null; //Start again with a quick loop
checkComplete.push(fullData);
var thisImageURI = fullData.details.imageURI;
glbThis.check(thisImageURI); //This will only upload again if it finds it hasn't been transferred off the
} else {
//This is a case where full details are not available. Do nothing.
glbThis.changeLocalPhotoStatus(newPhoto.imageURI, "cancel");
}
} catch(err) {
//There was a problem parsing the data.
glbThis.changeLocalPhotoStatus(newPhoto.imageURI, "cancel");
}
} else {
//No fullData was added - resend anyway
glbThis.changeLocalPhotoStatus(newPhoto.imageURI, "cancel");
}
} else {
//Needs to be resent
glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName);
}
}
}
return;
},
get: function(url, cb) {
var alreadyReturned = false;
var request = new XMLHttpRequest();
request.open("GET", url, true);
var getTimeout = setTimeout(function() {
if(alreadyReturned == false) { //Don't double up with onerror
alreadyReturned = true;
cb(url, null, "timeout"); // Assume it hasn't gone through - we have a 404 error checking the server
}
}, 5000);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
clearTimeout(getTimeout);
cb(url, request.responseText); // -> request.responseText <- is a result
} else {
cb(url, null);
}
}
}
request.onerror = function() {
if (request.status != 200) {
if(alreadyReturned == false) { //Don't double up with timeout
clearTimeout(getTimeout);
alreadyReturned = true;
cb(url, null);
}
}
}
request.send();
},
scanlan: function(port, cb) {
var _this = this;
if(_this.lan) {
var lan = _this.lan;
totalScanned = 0;
for(var cnt=0; cnt< 255; cnt++){
var machine = cnt.toString();
var url = 'http://' + lan + machine + ':' + port;
this.get(url, function(goodurl, resp, timeout) {
if(resp) {
//This is a good server
totalScanned ++;
//Save the first TODO: if more than one, open another screen here
localStorage.setItem("currentWifiServer", goodurl);
clearInterval(scanning);
cb(goodurl, null);
} else {
totalScanned ++;
_this.notify("Scanning Wifi. Responses:" + totalScanned);
}
});
}
var pausing = false;
//timeout check every 6 secs
var scanning = setInterval(function() {
if(totalScanned < 255) {
//Let a user decide to continue
if(pausing == false) {
pausing = true; //Pausing prevents it from opening up more windows
if(confirm("Timeout finding your Wifi server. Note: you have scanned for http://" + lan + "[range of 0-255]:" + port + ", and received " + totalScanned + " responses. Do you wish to keep scanning?")) {
//Yes, do nothing and wait.
pausing = false; //Can start asking again
} else {
//Exit out of here
clearInterval(scanning);
cb(null, "Timeout finding your Wifi server.</br></br><a href='javascript:' onclick=\"app.enterServerManually('We scanned for http://" + lan + "[range of 0-255]:" + port + ", and received " + totalScanned + " responses, but no servers. You can enter this manually below:');\">More Details</a>");
}
}
} else { //Total scanned is complete
//Have scanned the full range, error out of here.
clearInterval(scanning);
cb(null, "We couldn't see your Wifi server.</br></br><a href='javascript:' onclick=\"app.enterServerManually('We scanned for http://" + lan + "[range of 0-255]:" + port + ", and received " + totalScanned + " responses, but no servers. You can enter this manually below:');\">More Details</a>");
}
}, 8000);
} else {
//No lan detected
cb(null,"Local Wifi not detected.<br/><br/><a href='javascript:' onclick=\"app.enterServerManually('Sorry, we could not detect the LAN. You can enter the server address manually below:');\">More Details</a>");
}
},
notify: function(msg) {
//Set the user message
document.getElementById("notify").innerHTML = msg;
},
cancelNotify: function(msg) {
//Set the user message
document.getElementById("cancel-trans").innerHTML = msg;
},
cancelUpload: function(cancelURI) {
var ft = fileTransferMap.getItem(cancelURI);
if (ft)
{
ft.abort(glbThis.win, glbThis.fail);
//remove the photo
glbThis.changeLocalPhotoStatus(cancelURI, "cancel");
}
},
determineFilename: function(imageURIin, idEntered, cb) {
//Determines the filename to use based on the imageURI of the photo,
//and the id entered into the text field.
//Calls back with: cb(err, newFilename, imageURI)
// where err is null for no error, or text of the error,
// and the newFilename as a text string which includes the .jpg at the end
// imageURI is the local filesystem resolved URI
//It will use the current date / time from the phone, thought this format varies slightly
//phone to phone.
//Have connected OK to a server
var idEnteredB = idEntered;
window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) {
deleteThisFile = fileEntry; //Store globally
var imageURI = fileEntry.toURL();
var tempName = idEnteredB;
if((tempName == '')||(tempName == null)) {
tempName = 'image';
}
var initialHash = localStorage.getItem("initialHash");
if((initialHash)&&(initialHash != null)) {
if(initialHash == 'true') {
//Prepend the initial hash
tempName = "#" + tempName;
}
} else {
//Not set, so prepend the initial hash by default
tempName = "#" + tempName;
}
var defaultDir = localStorage.getItem("defaultDir");
if((defaultDir)&&(defaultDir != null)) {
//A hash code signifies a directory to write to
tempName = "#" + defaultDir + " " + tempName;
}
var myoutFile = tempName.replace(/ /g,'-');
var idEnteredC = idEnteredB; //Get a 2nd tier of variable
navigator.globalization.dateToString(
new Date(),
function (date) {
var mydt = date.value.replace(/:/g,'-');
mydt = mydt.replace(/ /g,'-');
mydt = mydt.replace(/\//g,'-');
var aDate = new Date();
var seconds = aDate.getSeconds();
mydt = mydt + "-" + seconds;
mydt = mydt.replace(/,/g,''); //remove any commas from iphone
mydt = mydt.replace(/\./g,'-'); //remove any fullstops
var myNewFileName = myoutFile + '-' + mydt + '.jpg';
cb(null, myNewFileName, imageURI);
},
function () {
navigator.notification.alert('Sorry, there was an error getting the current date\n');
cb("Sorry, there was an error getting the current date");
},
{ formatLength:'medium', selector:'date and time'}
); //End of function in globalization date to string
}, function(evt) {
//An error accessing the file
//and potentially delete phone version
glbThis.changeLocalPhotoStatus(myImageURIin, 'cancel');
cb("Sorry, we could not access the photo file");
}); //End of resolveLocalFileSystemURI
},
uploadPhoto: function(imageURIin, idEntered, newFilename) {
var _this = this;
var usingServer = localStorage.getItem("usingServer");
var idEnteredB = idEntered;
if((!usingServer)||(usingServer == null)) {
//No remove server already connected to, find the server now. And then call upload again
_this.findServer(function(err) {
if(err) {
window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again
glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds.");
//Search again in 10 seconds:
var scope = this;
scope.imageURIin = imageURIin;
scope.idEnteredB = idEnteredB;
scope.newFilename = newFilename;
setTimeout(function() {
glbThis.uploadPhoto(scope.imageURIin, scope.idEnteredB, scope.newFilename)
}, 10000);
} else {
//Now we are connected, upload the photo again
glbThis.uploadPhoto(imageURIin, idEnteredB, newFilename);
}
});
return;
} else {
//Have connected OK to a server
var myImageURIin = imageURIin;
var imageURI = imageURIin;
var options = new FileUploadOptions();
options.fileKey="file1";
options.mimeType="image/jpeg";
var params = new Object();
params.title = idEntered;
if((params.title == '')||(params.title == null)) {
if((idEnteredB == '')||(idEnteredB == null)) {
params.title = 'image';
} else {
params.title = idEnteredB;
}
}
options.fileName = newFilename;
options.params = params;
options.chunkedMode = false; //chunkedMode = false does work, but still having some issues. =true may only work on newer systems?
options.headers = {
Connection: "close"
}
options.idEntered = idEnteredB;
var ft = new FileTransfer();
_this.notify("Uploading " + params.title);
_this.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#f7afbb;\" size=\"30px\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + imageURI + "');\"></ons-icon><br/>Cancel");
ft.onprogress = _this.progress;
var serverReq = usingServer + '/api/photo';
var repeatIfNeeded = {
"imageURI" : imageURI,
"serverReq" : serverReq,
"options" :options,
"failureCount": 0,
"nextAttemptSec": 15
};
retryIfNeeded.push(repeatIfNeeded);
fileTransferMap.setItem(imageURI, ft); //Make sure we can abort this photo later
//Keep the screen awake as we upload
window.plugins.insomnia.keepAwake();
var myImageURI = repeatIfNeeded.imageURI;
ft.upload(imageURI, serverReq, function(result) {
glbThis.win(result, myImageURI);
}, function(result) {
glbThis.fail(result, myImageURI);
}, options);
} //End of connected to a server OK
},
progress: function(progressEvent) {
var statusDom = document.querySelector('#status');
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
statusDom.innerHTML = perc + "% uploaded...";
} else {
if(statusDom.innerHTML == "") {
statusDom.innerHTML = "Uploading";
} else {
statusDom.innerHTML += ".";
}
}
},
retry: function(existingText) {
window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again
var repeatIfNeeded = retryIfNeeded.pop();
if(repeatIfNeeded) {
//Resend within a minute here
var t = new Date();
t.setSeconds(t.getSeconds() + repeatIfNeeded.nextAttemptSec);
var timein = (repeatIfNeeded.nextAttemptSec*1000); //In microseconds
repeatIfNeeded.nextAttemptSec *= 3; //Increase the delay between attempts each time to save battery
if(repeatIfNeeded.nextAttemptSec > 21600) repeatIfNeeded.nextAttemptSec = 21600; //If longer than 6 hours gap, make 6 hours (that is 60x60x6)
var hrMin = t.getHours() + ":" + t.getMinutes();
glbThis.notify(existingText + " Retrying " + repeatIfNeeded.options.params.title + " at " + hrMin);
repeatIfNeeded.failureCount += 1; //Increase this
if(repeatIfNeeded.failureCount > 2) {
//Have tried too many attempts - try to reconnect completely (i.e. go
//from wifi to network and vica versa
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
glbThis.uploadPhoto(repeatIfNeeded.imageURI, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.fileName);
//Clear any existing timeouts
if(repeatIfNeeded.retryTimeout) {
clearTimeout(repeatIfNeeded.retryTimeout);
}
//Clear the current transfer too
repeatIfNeeded.ft.abort();
return;
} else {
//OK in the first few attempts - keep the current connection and try again
//Wait 10 seconds+ here before trying the next upload
repeatIfNeeded.retryTimeout = setTimeout(function() {
repeatIfNeeded.ft = new FileTransfer();
repeatIfNeeded.ft.onprogress = glbThis.progress;
glbThis.notify("Trying to upload " + repeatIfNeeded.options.params.title);
glbThis.cancelNotify("<ons-icon size=\"30px\" style=\"vertical-align: middle; color:#f7afbb;\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + repeatIfNeeded.imageURI + "');\"></ons-icon><br/>Cancel");
retryIfNeeded.push(repeatIfNeeded);
//Keep the screen awake as we upload
window.plugins.insomnia.keepAwake();
var myImageURI = repeatIfNeeded.imageURI;
repeatIfNeeded.ft.upload(repeatIfNeeded.imageURI, repeatIfNeeded.serverReq,
function(result) {
glbThis.win(result, myImageURI);
},function(result) {
glbThis.fail(result, myImageURI);
}, repeatIfNeeded.options);
}, timein); //Wait 10 seconds before trying again
}
}
},
removeCheckComplete: function(imageURI) {
//Loop through the current array and remove the entries
for(var cnt = 0; cnt< checkComplete.length; cnt++) {
if(checkComplete[cnt].details && checkComplete[cnt].details.imageURI && checkComplete[cnt].details.imageURI === imageURI) {
checkComplete[cnt] = null; //Need the delete first to get rid of subobjects
}
}
//Remove the null array entries
checkComplete = glbThis.arrayRemoveNulls(checkComplete);
return;
},
removeRetryIfNeeded: function(imageURI) {
//Loop through the current array and remove the entries
for(var cnt = 0; cnt< retryIfNeeded.length; cnt++) {
if(retryIfNeeded[cnt].imageURI === imageURI) {
retryIfNeeded[cnt] = null; //Need the delete first to get rid of subobjects
}
}
//Remove the null array entries
retryIfNeeded = glbThis.arrayRemoveNulls(retryIfNeeded);
return;
},
check: function(imageURI){
//Checks to see if the next photo on the server (in the checkComplete stack) has been sent on to the PC successfully. If not it will keep pinging until is has been dealt with, or it times out.
var startSlowLoop = false;
var nowChecking = null;
for(var cnt = 0; cnt < checkComplete.length; cnt++) {
if(checkComplete[cnt].details.imageURI === imageURI) {
nowChecking = JSON.parse(JSON.stringify(checkComplete[cnt]));
checkComplete[cnt].loopCnt --; //Decrement the original
if(nowChecking.loopCnt <= 0) {
//Now continue to check with this photo, but only once every 30 seconds, 100 times (i.e. about 45 minutes).
if(!nowChecking.slowLoopCnt) {
//Need to set a slow count
checkComplete[cnt].slowLoopCnt = 100;
startSlowLoop = true;
} else {
//Decrement the slow loop
checkComplete[cnt].slowLoopCnt --;
}
}
}
}
if(!nowChecking) {
//This check is complete, already. Strictly speaking we shouldn't get here unless we've been deleted
return;
}
nowChecking.loopCnt --;
if(nowChecking.loopCnt <= 0) {
//Have finished - remove interval and report back
if(startSlowLoop == true) {
//Have now finished the frequent checks. Move into slower checks.
var myTitle = "Image";
if(nowChecking.details && nowChecking.details.options && nowChecking.details.options.params && nowChecking.details.options.params.title && nowChecking.details.options.params.title != "") {
myTitle = nowChecking.details.options.params.title;
}
document.getElementById("notify").innerHTML = "You are experiencing a slightly longer transfer time than normal, likely due to a slow network. Your image " + myTitle + " should be delivered shortly. <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">Forget</a>";
window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep, we could be here for a while.
//The file exists on the server still - try again in 30 seconds
var thisScope = {};
thisScope.imageURI = imageURI;
setTimeout(function() {
glbThis.check(thisScope.imageURI);
}, 30000);
} else {
//Count down inside the slower checks
nowChecking.slowLoopCnt --;
if(nowChecking.slowLoopCnt <= 0) {
//Have finished the long count down, and given up
document.getElementById("notify").innerHTML = "Sorry, the image is on the remote server, but has not been delivered to your local PC. We will try again once your app restarts. <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">Forget</a>";
glbThis.cancelNotify(""); //Remove any cancel icons
} else {
//Otherwise in the long count down
var myNowChecking = nowChecking;
glbThis.get(nowChecking.fullGet, function(url, resp) {
if((resp === "false")||(resp === false)) {
//File no longer exists, success!
glbThis.cancelNotify(""); //Remove any transfer icons
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
glbThis.removeCheckComplete(myNowChecking.details.imageURI);
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1;
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! ';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more;
}
}
} else {
return;
}
//and delete phone version
if(myNowChecking.details) {
glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel');
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.';
}
} else {
//The file exists on the server still - try again in 30 seconds
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
var moreLength = (checkComplete.length + retryIfNeeded.length);
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(!nowChecking.slowLoopCnt) {
nowChecking.slowLoopCnt = 100; //Init
}
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' has not finished transferring. Checking again in 30 seconds. ' + myNowChecking.slowLoopCnt;
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' has not finished transferring. Checking again in 30 seconds.' + more + ' ' + myNowChecking.slowLoopCnt;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more + myNowChecking.slowLoopCnt;
}
}
} else {
return;
}
var thisScope = {};
if(myNowChecking && myNowChecking.details) {
thisScope.imageURI = myNowChecking.details.imageURI;
setTimeout(function() {
glbThis.check(thisScope.imageURI);
}, 30000);
}
}
});
}
}
} else {
//Try a get request to the check
//Get the current file data
glbThis.cancelNotify(""); //Remove any cancel icons
var myNowChecking = nowChecking;
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1; //The -1 is to not include the current in the count
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..' + more;
} else {
document.getElementById("notify").innerHTML = 'Image on server. Transferring to PC..' + more;
}
}
glbThis.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#DDD;\" size=\"20px\" spin icon=\"fa-spinner\"></ons-icon><br/>");
} else {
return;
}
var myNowChecking = nowChecking;
glbThis.get(nowChecking.fullGet, function(url, resp) {
if((resp === "false")||(resp === false)) {
//File no longer exists, success!
glbThis.cancelNotify(""); //Remove any transfer icons
glbThis.removeCheckComplete(myNowChecking.details.imageURI);
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
var moreLength = (checkComplete.length + retryIfNeeded.length);
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more;
}
}
} else {
return;
}
//and delete phone version
if(myNowChecking.details) {
glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel');
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more + ' Note: The image will be resent on a restart to verify.';
}
} else {
//The file exists on the server still - try again in a few moments
var thisScope = {};
if(myNowChecking && myNowChecking.details) {
thisScope.imageURI = myNowChecking.details.imageURI;
setTimeout(function() {
glbThis.check(thisScope.imageURI);
}, 2000);
}
}
});
}
},
win: function(r, imageURI) {
//Have finished transferring the file to the server
window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again
document.querySelector('#status').innerHTML = ""; //Clear progress status
glbThis.cancelNotify(""); //Remove any cancel icons
//Check if this was a transfer to the remote server
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
if((r.responseCode == 200)||(r.response.indexOf("200") != -1)) {
var remoteServer = localStorage.getItem("serverRemote");
if(remoteServer == 'false') {
//i.e. Wifi case
glbThis.cancelNotify(""); //Remove any transfer icons
//and delete phone version of file
var repeatIfNeeded = null;
for(var cnt=0; cnt< retryIfNeeded.length; cnt++) {
if(retryIfNeeded[cnt].imageURI === imageURI) {
repeatIfNeeded = JSON.parse(JSON.stringify(retryIfNeeded[cnt]));
}
}
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1;
if(moreLength >= 0) {
if(moreLength == 0) {
var more = "";
} else {
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
}
} else {
return;
}
var myTitle = "Image";
if(repeatIfNeeded) {
glbThis.removeRetryIfNeeded(repeatIfNeeded.imageURI);
if(repeatIfNeeded && repeatIfNeeded.options && repeatIfNeeded.options.params && repeatIfNeeded.options.params.title && repeatIfNeeded.options.params.title != "") {
myTitle = repeatIfNeeded.options.params.title;
if(myTitle === "image") myTitle = "Image";
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more;
}
glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'cancel');
} else {
//Trying to check, but no file on stack
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more + ' Note: The image will be resent on a restart to verify.';
}
} else {
//Onto remote server - now do some pings to check we have got to the PC
//and delete phone version of file
var repeatIfNeeded = null;
for(var cnt=0; cnt< retryIfNeeded.length; cnt++) {
if(retryIfNeeded[cnt].imageURI === imageURI) {
repeatIfNeeded = JSON.parse(JSON.stringify(retryIfNeeded[cnt]));
}
}
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1;
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
var myTitle = "Image";
if(repeatIfNeeded && repeatIfNeeded.options && repeatIfNeeded.options.params && repeatIfNeeded.options.params.title && repeatIfNeeded.options.params.title != "") {
myTitle = repeatIfNeeded.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..' + more;
} else {
document.getElementById("notify").innerHTML = 'Image on server. Transferring to PC..' + more;
}
}
glbThis.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#DDD;\" size=\"20px\" spin icon=\"fa-spinner\"></ons-icon><br/>");
} else {
return;
}
if(repeatIfNeeded) {
var thisFile = repeatIfNeeded.options.fileName;
var usingServer = localStorage.getItem("usingServer");
if(usingServer) { //Note, we have had a case of a null server here. In this case
//simply don't do any follow on checks.
var fullGet = usingServer + '/check=' + encodeURIComponent(thisFile);
var nowChecking = {};
nowChecking.loopCnt = 11; //Max timeout = 11*2 = 22 secs but also a timeout of 5 seconds on the request.
nowChecking.fullGet = fullGet;
nowChecking.details = repeatIfNeeded;
checkComplete.push(nowChecking);
//Set an 'onserver' status
glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'onserver', nowChecking);
var self = {};
self.thisImageURI = repeatIfNeeded.imageURI;
setTimeout(function() { //Wait two seconds and then do a check
glbThis.check(self.thisImageURI);
}, 2000);
glbThis.removeRetryIfNeeded(repeatIfNeeded.imageURI);
} else {
//Set an 'onserver' status, and remove this entry
glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'onserver', nowChecking);
glbThis.removeRetryIfNeeded(repeatIfNeeded.imageURI);
}
} else {
//Trying to check, but no file on stack
}
} //End of if(remoteServer == 'false')
//Save the current server settings for future reuse
glbThis.saveServer();
} else {
//Retry sending
glbThis.retry("");
}
},
fail: function(error, imageURI) {
window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep
document.querySelector('#status').innerHTML = ""; //Clear progress status
glbThis.cancelNotify(""); //Remove any cancel icons
switch(error.code)
{
case 1:
glbThis.notify("The photo was uploaded.");
//Remove the photo from the list
glbThis.changeLocalPhotoStatus(imageURI, 'cancel');
break;
case 2:
glbThis.notify("Sorry you have tried to send it to an invalid URL.");
break;
case 3:
glbThis.notify("Waiting for better reception..");
glbThis.retry("Waiting for better reception...</br>");
break;
case 4:
glbThis.notify("Your image transfer was aborted.");
//No need to retry here: glbThis.retry("Sorry, your image transfer was aborted.</br>");
break;
default:
glbThis.notify("An error has occurred: Code = " + error.code);
break;
}
},
forgetAllPhotos: function() {
//Loop through all photos in retryIfNeeded, checkComplete and localPhotos and remove them
//all.
var _this = this;
glbThis = this;
for(var cnta = 0; cnta < retryIfNeeded.length; cnta++) {
if(retryIfNeeded[cnta].imageURI) {
_this.cancelUpload(retryIfNeeded[cnta].imageURI);
_this.removeRetryIfNeeded(retryIfNeeded[cnta].imageURI);
}
}
for(var cntb = 0; cntb < checkComplete.length; cntb++) {
if(checkComplete[cntb].details && checkComplete[cntb].details.imageURI) {
_this.removeCheckComplete(checkComplete[cntb].details.imageURI);
}
}
var localPhotos = _this.getArrayLocalStorage("localPhotos");
for(var cntc = 0; cntc < localPhotos.length; cntc++) {
if(localPhotos[cntc].imageURI) {
_this.changeLocalPhotoStatus(localPhotos[cntc].imageURI, 'cancel');
}
}
glbThis.notify("All photos have been deleted and forgotten.");
glbThis.cancelNotify(""); //Remove any cancel icons
},
askForgetAllPhotos: function() {
//Ask if we want to remove all the photos on the system
//Get a live current photo count
var moreLength = checkComplete.length + retryIfNeeded.length;
if(moreLength == 1) {
var moreStr = "is " + moreLength + " photo";
} else {
var moreStr = "are " + moreLength + " photos";
}
navigator.notification.confirm(
'There ' + moreStr + ' in memory. Do you want to forget and delete all of these photos? (Some of them may have been sent already)', // message
function(buttonIndex) {
if(buttonIndex == 1) {
glbThis.forgetAllPhotos();
return;
} else {
return;
}
}, // callback to invoke
'Forget Photos', // title
['Yes','No'] // buttonLabels
);
},
getip: function(cb) {
var _this = glbThis;
//timeout after 3 secs -rerun this.findServer()
var iptime = setTimeout(function() {
var err = "You don't appear to be connected to your wifi. Please connect and try again.";
cb(null, err);
}, 5000);
networkinterface.getWiFiIPAddress(function(ipInfo) {
_this.ip = ipInfo.ip; //note: we could use ipInfo.subnet here but, this could be a 16-bit subnet rather than 24-bit?
var len = ipInfo.ip.lastIndexOf('\.') + 1;
_this.lan = ipInfo.ip.substr(0,len);
clearTimeout(iptime);
cb(null);
},
function(err) {
var retErr = "Sorry, there was a problem getting your IP address.<br/><br/><a href='javascript:' onclick=\"navigator.notification.alert('Error: " + err + "', function() {}, 'More Details');\">More Details</a>";
cb(null, retErr);
});
},
factoryReset: function() {
//We have connected to a server OK
var _this = this;
navigator.notification.confirm(
'Are you sure? All your saved PCs and other settings will be cleared.', // message
function(buttonIndex) {
if(buttonIndex == 1) {
localStorage.clear();
localStorage.removeItem("usingServer"); //Init it
localStorage.removeItem("defaultDir"); //Init it
localStorage.removeItem("currentRemoteServer");
localStorage.removeItem("currentWifiServer");
localStorage.setItem("initialHash", 'true'); //Default to write a folder
document.getElementById("always-create-folder").checked = true;
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = "";
alert("Cleared all saved PCs.");
glbThis.openSettings();
}
}, // callback to invoke
'Clear Settings', // title
['Ok','Cancel'] // buttonLabels
);
return false;
},
checkDefaultDir: function(server) {
//Check if the default server has a default dir eg. input:
// http://123.123.123.123:5566/write/fshoreihtskhfv
//Where the defaultDir would be 'fshoreihtskhfv'
//Returns '{ server: "http://123.123.123.123:5566", dir: "fshoreihtskhfv"'
var requiredStr = "/write/";
var startsAt = server.indexOf(requiredStr);
if(startsAt >= 0) {
//Get the default dir after the /write/ string
var startFrom = startsAt + requiredStr.length;
var defaultDir = server.substr(startFrom);
var properServer = server.substr(0, startsAt);
return { server: properServer, dir: defaultDir };
} else {
return { server: server, dir: "" };
}
},
connect: function(results) {
//Save the server with a name
//Get existing settings array
switch(results.buttonIndex) {
case 1:
//Clicked on 'Ok'
//Start the pairing process
var pairUrl = centralPairingUrl + '?compare=' + results.input1;
glbThis.notify("Pairing..");
glbThis.get(pairUrl, function(url, resp) {
if(resp) {
resp = resp.replace('\n', '')
if(resp == 'nomatch') {
glbThis.notify("Sorry, there was no match for that code.");
return;
} else {
var server = resp;
glbThis.notify("Pairing success.");
//And save this server
localStorage.setItem("currentRemoteServer",server);
localStorage.removeItem("currentWifiServer"); //Clear the wifi
localStorage.removeItem("usingServer"); //Init it
localStorage.removeItem("defaultDir"); //Init it
navigator.notification.confirm(
'Do you want to connect via WiFi, if it is available, also?', // message
function(buttonIndex) {
if(buttonIndex == 1) {
//yes, we also want to connect via wifi
glbThis.checkWifi(function(err) {
if(err) {
//An error finding wifi
glbThis.notify(err);
glbThis.bigButton();
} else {
//Ready to take a picture, rerun with this
//wifi server
glbThis.notify("WiFi paired successfully.");
glbThis.bigButton();
}
});
} else {
glbThis.notify("Pairing success, without WiFi.");
glbThis.bigButton();
}
}, // callback to invoke
'Pairing Success!', // title
['Yes','No'] // buttonLabels
);
return;
}
} else {
//A 404 response
glbThis.notify("Sorry, we could not connect to the pairing server. Please try again.");
}
}); //end of get
return;
break;
case 2:
//Clicked on 'Wifi only'
//Otherwise, first time we are running the app this session
localStorage.removeItem("currentWifiServer"); //Clear the wifi
localStorage.removeItem("currentRemoteServer"); //Clear the wifi
localStorage.removeItem("usingServer"); //Init it
localStorage.removeItem("defaultDir"); //Init it
glbThis.checkWifi(function(err) {
if(err) {
//An error finding server - likely need to enter a pairing code. Warn the user
glbThis.notify(err);
} else {
//Ready to take a picture, rerun
glbThis.notify("Wifi paired successfully.");
glbThis.bigButton();
}
});
return;
break;
default:
//Clicked on 'Cancel'
break;
}
},
bigButton: function() {
//Called when pushing the big button
var _this = this;
var foundRemoteServer = null;
var foundWifiServer = null;
foundRemoteServer = localStorage.getItem("currentRemoteServer");
foundWifiServer = localStorage.getItem("currentWifiServer");
if(((foundRemoteServer == null)||(foundRemoteServer == ""))&&
((foundWifiServer == null)||(foundWifiServer == ""))) {
//Likely need to enter a pairing code. Warn the user
//No current server - first time with this new connection
//We have connected to a server OK
navigator.notification.prompt(
'Please enter the 4 letter pairing code from your PC.', // message
glbThis.connect, // callback to invoke
'New Connection', // title
['Ok','Use Wifi Only','Cancel'], // buttonLabels
'' // defaultText
);
} else {
//Ready to take a picture
_this.takePicture();
}
},
checkWifi: function(cb) {
glbThis.notify("Checking Wifi connection");
this.getip(function(ip, err) {
if(err) {
cb(err);
return;
}
glbThis.notify("Scanning Wifi");
glbThis.scanlan('5566', function(url, err) {
if(err) {
cb(err);
} else {
cb(null);
}
});
});
},
getOptions: function(guid, cb) {
//Input a server dir e.g. uPSE4UWHmJ8XqFUqvf
// where the last part is the guid.
//Get a URL like this: https://atomjump.com/med-settings.php?type=get&guid=uPSE4UWHmJ8XqFUqvf
//to get a .json array of options.
var settingsUrl = "https://atomjump.com/med-settings.php?type=get&guid=" + guid;
glbThis.get(settingsUrl, function(url, resp) {
if(resp != "") {
var options = JSON.stringify(resp); //Or is it without the json parsing?
if(options) {
//Set local storage
//localStorage.removeItem("serverOptions");
localStorage.setItem("serverOptions", options);
cb(null);
} else {
cb("No options");
}
} else {
cb("No options");
}
});
},
clearOptions: function() {
localStorage.removeItem("serverOptions");
},
findServer: function(cb) {
//Check storage for any saved current servers, and set the remote and wifi servers
//along with splitting any subdirectories, ready for use by the the uploader.
//Then actually try to connect - if wifi is an option, use that first
var _this = this;
var alreadyReturned = false;
var found = false;
//Clear off
var foundRemoteServer = null;
var foundWifiServer = null;
var foundRemoteDir = null;
var foundWifiDir = null;
var usingServer = null;
this.clearOptions();
//Early out
usingServer = localStorage.getItem("usingServer");
if((usingServer)&&(usingServer != null)) {
cb(null);
return;
}
foundRemoteServer = localStorage.getItem("currentRemoteServer");
foundWifiServer = localStorage.getItem("currentWifiServer");
if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "")) {
//Already found a remote server
//Generate the directory split, if any. Setting RAM foundServer and defaultDir
var split = this.checkDefaultDir(foundRemoteServer);
foundRemoteServer = split.server;
foundRemoteDir = split.dir;
} else {
foundRemoteServer = null;
foundRemoteDir = null;
}
//Check if we have a Wifi option
if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "")) {
//Already found wifi
//Generate the directory split, if any. Setting RAM foundServer and defaultDir
var split = this.checkDefaultDir(foundWifiServer);
foundWifiServer = split.server;
foundWifiDir = split.dir;
} else {
foundWifiServer = null;
foundWifiDir = null;
}
//Early out:
if((foundWifiServer == null)&&(foundRemoteServer == null)) {
cb('No known server.');
return;
}
//Now try the wifi server as the first option to use if it exists:
if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "null")) {
//Ping the wifi server
glbThis.notify('Trying to connect to the wifi server..');
//Timeout after 5 secs for the following ping
var scanning = setTimeout(function() {
glbThis.notify('Timeout finding your wifi server.</br>Trying remote server..');
//Else can't communicate with the wifi server at this time.
//Try the remote server
if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "null")) {
var scanningB = setTimeout(function() {
//Timed out connecting to the remote server - that was the
//last option.
localStorage.removeItem("usingServer");
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
if(alreadyReturned == false) {
alreadyReturned = true;
cb('No server found');
}
}, 6000);
glbThis.get(foundRemoteServer, function(url, resp) {
if(resp != "") {
//Success, got a connection to the remote server
clearTimeout(scanningB); //Ensure we don't error out
localStorage.setItem("usingServer", foundRemoteServer);
localStorage.setItem("serverRemote", 'true');
localStorage.setItem("defaultDir", foundRemoteDir);
if(alreadyReturned == false) {
alreadyReturned = true;
//Get any global options
glbThis.getOptions(foundRemoteDir);
cb(null);
}
clearTimeout(scanning); //Ensure we don't error out
}
});
} else {
//Only wifi existed
localStorage.removeItem("usingServer");
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
if(alreadyReturned == false) {
alreadyReturned = true;
cb('No server found');
}
}
}, 2000);
//Ping the wifi server
glbThis.get(foundWifiServer, function(url, resp) {
if(resp != "") {
//Success, got a connection to the wifi
clearTimeout(scanning); //Ensure we don't error out
localStorage.setItem("usingServer", foundWifiServer);
localStorage.setItem("defaultDir", foundWifiDir);
localStorage.setItem("serverRemote", 'false');
if(alreadyReturned == false) {
alreadyReturned = true;
cb(null); //Success found server
}
}
});
} else {
//OK - no wifi option - go straight to the remote server
//Try the remote server
glbThis.notify('Trying to connect to the remote server....');
var scanning = setTimeout(function() {
//Timed out connecting to the remote server - that was the
//last option.
localStorage.removeItem("usingServer");
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
if(alreadyReturned == false) {
alreadyReturned = true;
cb('No server found');
}
}, 6000);
_this.get(foundRemoteServer, function(url, resp) {
if(resp != "") {
//Success, got a connection to the remote server
localStorage.setItem("usingServer", foundRemoteServer);
localStorage.setItem("defaultDir", foundRemoteDir);
localStorage.setItem("serverRemote", 'true');
if(alreadyReturned == false) {
alreadyReturned = true;
//Get any global options
glbThis.getOptions(foundRemoteDir);
cb(null);
}
clearTimeout(scanning); //Ensure we don't error out
}
});
}
},
/* Settings Functions */
openSettings: function() {
//Open the settings screen
var html = this.listServers();
document.getElementById("settings").innerHTML = html;
document.getElementById("settings-popup").style.display = "block";
},
closeSettings: function() {
//Close the settings screen
document.getElementById("settings-popup").style.display = "none";
},
listServers: function() {
//List the available servers
var settings = this.getArrayLocalStorage("settings");
if(settings) {
var html = "<ons-list><ons-list-header>Select a PC to use now:</ons-list-header>";
//Convert the array into html
for(var cnt=0; cnt< settings.length; cnt++) {
html = html + "<ons-list-item><ons-list-item onclick='app.setServer(" + cnt + ");'>" + settings[cnt].name + "</ons-list-item><div class='right'><ons-icon icon='md-delete' onclick='app.deleteServer(" + cnt + ");'></ons-icon></div></ons-list-item>";
}
html = html + "</ons-list>";
} else {
var html = "<ons-list><ons-list-header>PCs Stored</ons-list-header>";
var html = html + "<ons-list-item><ons-list-item>Default</ons-list-item><div class='right'><ons-icon icon='md-delete'style='color:#AAA></ons-icon></div></ons-list-item>";
html = html + "</ons-list>";
}
return html;
},
setServer: function(serverId) {
//Set the server to the input server id
var settings = this.getArrayLocalStorage("settings");
var currentRemoteServer = settings[serverId].currentRemoteServer;
var currentWifiServer = settings[serverId].currentWifiServer;
localStorage.removeItem("usingServer"); //reset the currently used server
//Save the current server
localStorage.removeItem("defaultDir");
//Remove if one of these doesn't exist, and use the other.
if((!currentWifiServer)||(currentWifiServer == null)||(currentWifiServer =="")) {
localStorage.removeItem("currentWifiServer");
} else {
localStorage.setItem("currentWifiServer", currentWifiServer);
}
if((!currentRemoteServer)||(currentRemoteServer == null)||(currentRemoteServer == "")) {
localStorage.removeItem("currentRemoteServer");
} else {
localStorage.setItem("currentRemoteServer", currentRemoteServer);
}
//Set the localstorage
localStorage.setItem("currentServerName", settings[serverId].name);
navigator.notification.alert("Switched to: " + settings[serverId].name, function() {}, "Changing PC");
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = settings[serverId].name;
this.closeSettings();
return false;
},
newServer: function() {
//Create a new server.
//This is actually effectively resetting, and we will allow the normal functions to input a new one
localStorage.removeItem("usingServer");
//Remove the current one
localStorage.removeItem("currentRemoteServer");
localStorage.removeItem("currentWifiServer");
this.notify("Tap above to activate."); //Clear off old notifications
//Ask for a name of the current Server:
navigator.notification.prompt(
'Please enter a name for this PC', // message
this.saveServerName, // callback to invoke
'PC Name', // title
['Ok','Cancel'], // buttonLabels
'Main' // defaultText
);
},
deleteServer: function(serverId) {
//Delete an existing server
this.myServerId = serverId;
navigator.notification.confirm(
'Are you sure? This PC will be removed from memory.', // message
function(buttonIndex) {
if(buttonIndex == 1) {
var settings = glbThis.getArrayLocalStorage("settings");
if((settings == null)|| (settings == '')) {
//Nothing to delete
} else {
//Check if it is deleting the current entry
var deleteName = settings[glbThis.myServerId].name;
var currentServerName = localStorage.getItem("currentServerName");
if((currentServerName) && (deleteName) && (currentServerName == deleteName)) {
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = "";
localStorage.removeItem("currentRemoteServer");
localStorage.removeItem("currentWifiServer");
localStorage.removeItem("currentServerName");
}
settings.splice(glbThis.myServerId, 1); //Remove the entry entirely from array
glbThis.setArrayLocalStorage("settings", settings);
}
glbThis.openSettings(); //refresh
}
}, // callback to invoke
'Remove PC', // title
['Ok','Cancel'] // buttonLabels
);
},
saveServerName: function(results) {
//Save the server with a name - but since this is new,
//Get existing settings array
if(results.buttonIndex == 1) {
//Clicked on 'Ok'
localStorage.setItem("currentServerName", results.input1);
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = results.input1;
glbThis.closeSettings();
return;
} else {
//Clicked on 'Exit'. Do nothing.
return;
}
},
displayServerName: function() {
//Call this during initialisation on app startup
var currentServerName = localStorage.getItem("currentServerName");
if((currentServerName) && (currentServerName != null)) {
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = currentServerName;
} else {
document.getElementById("currentPC").innerHTML = "";
}
},
saveIdInput: function(status) {
//Save the idInput. input true/false true = 'start with a hash'
// false = 'start with blank'
//Get existing settings array
if(status == true) {
//Show a hash by default
localStorage.setItem("initialHash", "true");
} else {
//Remove the hash by default
localStorage.setItem("initialHash", "false");
}
},
enterServerManually: function(message) {
var _this = this;
//Ask for a name of the current Server:
navigator.notification.prompt(
message, // message
_this.saveServerAddress, // callback to invoke
'Set Server Manually', // title
['Ok','Cancel'], // buttonLabels
'http://' + _this.lan + ':5566' // defaultText
);
return false;
},
saveServerAddress: function(result) {
var _this = this;
switch(result.buttonIndex) {
case 1:
//Clicked on 'Ok'
//Called from enterServerManually
localStorage.setItem("currentWifiServer", result.input1);
localStorage.setItem("usingServer", result.input1);
//Now try to connect
_this.findServer(function(err) {
alert("Got it error:" + err); //TESTING REMOVE ME
if(err) {
glbThis.notify("Sorry, we cannot connect to the server");
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
localStorage.removeItem("currentWifiServer");
} else {
//Now we are connected - so we can get the photo
glbThis.bigButton();
}
});
break;
default:
//Clicked on 'Cancel'
break;
}
return false;
},
displayIdInput: function() {
//Call this during initialisation on app startup
var initialHash = localStorage.getItem("initialHash");
if((initialHash) && (initialHash != null)) {
//Now refresh the current ID field
if(initialHash == "true") {
document.getElementById("always-create-folder").checked = true;
} else {
document.getElementById("always-create-folder").checked = false;
}
}
},
saveServer: function() {
//Run this after a successful upload
var currentServerName = localStorage.getItem("currentServerName");
var currentRemoteServer = localStorage.getItem("currentRemoteServer");
var currentWifiServer = localStorage.getItem("currentWifiServer");
if((!currentServerName) ||(currentServerName == null)) currentServerName = "Default";
if((!currentRemoteServer) ||(currentRemoteServer == null)) currentRemoteServer = "";
if((!currentWifiServer) ||(currentWifiServer == null)) currentWifiServer = "";
var settings = glbThis.getArrayLocalStorage("settings");
//Create a new entry - which will be blank to being with
var newSetting = {
"name": currentServerName, //As input by the user
"currentRemoteServer": currentRemoteServer,
"currentWifiServer": currentWifiServer
};
if((settings == null)|| (settings == '')) {
//Creating an array for the first time
var settings = [];
settings.push(newSetting); //Save back to the array
} else {
//Check if we are writing over the existing entries
var writeOver = false;
for(cnt = 0; cnt< settings.length; cnt++) {
if(settings[cnt].name == currentServerName) {
writeOver = true;
settings[cnt] = newSetting;
}
}
if(writeOver == false) {
settings.push(newSetting); //Save back to the array
}
}
//Save back to the persistent settings
glbThis.setArrayLocalStorage("settings", settings);
return;
},
//Array storage for app permanent settings (see http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/)
setArrayLocalStorage: function(mykey, myobj) {
return localStorage.setItem(mykey, JSON.stringify(myobj));
},
getArrayLocalStorage: function(mykey) {
return JSON.parse(localStorage.getItem(mykey));
}
};
| www/js/index.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//Source code Copyright (c) 2018 AtomJump Ltd. (New Zealand)
var deleteThisFile = {}; //Global object for image taken, to be deleted
var centralPairingUrl = "https://atomjump.com/med-genid.php"; //Redirects to an https connection. In future try setting to http://atomjump.org/med-genid.php
var glbThis = {}; //Used as a global error handler
var retryIfNeeded = []; //A global pushable list with the repeat attempts
var checkComplete = []; //A global pushable list with the repeat checks to see if image is on PC
var retryNum = 0;
//See: https://stackoverflow.com/questions/14787705/phonegap-cordova-filetransfer-abort-not-working-as-expected
// basic implementation of hash map of FileTransfer objects
// so that given a key, an abort function can find the right FileTransfer to abort
function SimpleHashMap()
{
this.items = {};
this.setItem = function(key, value) { this.items[key] = value; }
this.getItem = function(key)
{
if (this.hasItem(key)) { return this.items[key]; }
return undefined;
}
this.hasItem = function(key) { return this.items.hasOwnProperty(key); }
this.removeItem = function(key)
{
if (this.hasItem(key)) { delete this.items[key]; }
}
}
var fileTransferMap = new SimpleHashMap();
var app = {
// Application Constructor
initialize: function() {
glbThis = this;
this.bindEvents();
//Set display name
this.displayServerName();
//Initialise the id field
this.displayIdInput();
//Check if there are any residual photos that need to be sent again
glbThis.loopLocalPhotos();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
if(parentElement) {
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
} else {
console.log('Failed Received Event: ' + id);
}
},
processPicture: function(imageURIin)
{
var _this = this;
glbThis = this;
//Called from takePicture(), after the image file URI has been shifted into a persistent file
//Reconnect once
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
var thisImageURI = imageURIin;
var idEntered = document.getElementById("id-entered").value;
_this.findServer(function(err) {
if(err) {
glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds.");
//Search again in 10 seconds:
var passedImageURI = thisImageURI;
var idEnteredB = idEntered;
setTimeout(function() {
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
glbThis.uploadPhoto(passedImageURI, idEnteredB, newFilename);
}, 10000);
} else {
//Now we are connected - so we can get the filename
_this.determineFilename(thisImageURI, idEntered, function(err, newFilename, imageURI) {
if(err) {
//There was a problem getting the filename from the disk file
glbThis.notify("Sorry, we cannot process the filename of the photo " + idEntered + ". If this happens consistently, please report the problem to medimage.co.nz");
} else {
//Store in case the app quits unexpectably
_this.recordLocalPhoto( imageURI, idEntered, newFilename);
//Now we are connected, upload the photo again
glbThis.uploadPhoto(imageURI, idEntered, newFilename);
}
});
}
});
},
takePicture: function() {
var _this = this;
glbThis = this;
navigator.camera.getPicture( function( imageURI ) {
//Move picture into persistent storage
//Grab the file name of the photo in the temporary directory
var currentName = imageURI.replace(/^.*[\\\/]/, '');
//Create a new name for the photo
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
window.resolveLocalFileSystemURI( imageURI, function(fileEntry) {
var myFile = fileEntry;
try {
//Try moving the file to permanent storage
window.resolveLocalFileSystemURL( cordova.file.dataDirectory,
function(directory) {
try {
myFile.moveTo(directory, newFileName, function(success){
//Moved it to permanent storage successfully
//success.fullPath contains the path to the photo in permanent storage
if(success.nativeURL) {
glbThis.processPicture(success.nativeURL);
} else {
glbThis.notify("Sorry we could not find the moved photo on the phone. Please let medimage.co.nz know that a moveFile() has not worked correctly.");
}
}, function(err){
//an error occured moving file - send anyway, even if it is in the temporary folder
glbThis.processPicture(imageURI);
});
} catch(err) {
//A problem moving the file but send the temp file anyway
glbThis.processPicture(imageURI);
}
}, function(err) {
//an error occured moving file - send anyway, even if it is in the temporary folder
glbThis.processPicture(imageURI);
});
} catch(err) {
//A proble occured determining if the persistent folder existed
glbThis.processPicture(imageURI);
}
},
function(err) {
//Could not resolve local file
glbThis.notify("Sorry we could not find the photo on the phone.");
});
},
function( message ) {
//An error or cancellation
glbThis.notify( message );
},
{
quality: 100,
destinationType: Camera.DestinationType.FILE_URI
});
},
recordLocalPhoto: function(imageURI, idEntered, fileName) {
//Save into our localPhotos array, in case the app quits
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
var newPhoto = {
"imageURI" : imageURI,
"idEntered" : idEntered,
"fileName" : fileName,
"status" : "send"
}; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel'
localPhotos.push(newPhoto);
glbThis.setArrayLocalStorage("localPhotos", localPhotos);
return true;
},
arrayRemoveNulls: function(arr) {
var newArray = [];
for(var cnt = 0; cnt < arr.length; cnt++) {
if(arr[cnt] && arr[cnt] != null) {
newArray.push(arr[cnt]);
}
}
return newArray;
},
removeLocalPhoto: function(imageURI) {
//Loop through the current array and remove
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
for(var cnt = 0; cnt< localPhotos.length; cnt++) {
if(localPhotos[cnt].imageURI === imageURI) {
localPhotos[cnt] = null; //Need the delete first to get rid of subobjects
localPhotos = glbThis.arrayRemoveNulls(localPhotos);
//Set back the storage of the array
glbThis.setArrayLocalStorage("localPhotos", localPhotos);
return;
}
}
},
changeLocalPhotoStatus: function(imageURI, newStatus, fullData) {
//Input:
//imageURI - unique image address on phone filesystem
//newStatus can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel'
//If onserver, the optional parameter 'fullGet', is the URL to call to check if the file is back on the server
//Note: during the cancel, each removeLocalPhoto could occur at any time (async) depending on the filesystem speed,
//so the removeLocalPhoto does a sync load, delete from array, and write back.
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
for(var cnt = 0; cnt< localPhotos.length; cnt++) {
if(localPhotos[cnt].imageURI === imageURI) {
if(newStatus === "cancel") {
//Delete the photo
window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
//Remove the file from the phone
fileEntry.remove();
//Remove entry from the array
glbThis.removeLocalPhoto(imageURI);
}, function(evt) {
//Some form of error case. We likely couldn't find the file, but we still want to remove the entry from the array
//in this case
var errorCode = null;
if(evt.code) {
errorCode = evt.code;
}
if(evt.target && evt.target.error.code) {
errorCode = evt.target.error.code;
}
if(errorCode === 1) {
//The photo is not there. Remove anyway
//Remove entry from the array
glbThis.removeLocalPhoto(imageURI);
} else {
glbThis.notify("Sorry, there was a problem removing the photo on the phone. Error code: " + evt.target.error.code);
//Remove entry from the array
glbThis.removeLocalPhoto(imageURI);
}
});
} else {
localPhotos[cnt].status = newStatus;
if((newStatus == "onserver")&&(fullData)) {
localPhotos[cnt].fullData = fullData;
}
//Set back the storage of the array
glbThis.setArrayLocalStorage("localPhotos", localPhotos);
}
}
}
//Note: don't put any post proccessing down here. The resolveLocalFileSystem is async.
},
loopLocalPhotos: function() {
//Get a photo, one at a time, in the array format:
/* {
"imageURI" : imageURI,
"idEntered" : idEntered,
"fileName" : fileName,
"fullData" : fullDataObject - optional
"status" : "send"
}; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel'
and attempt to upload them.
*/
var photoDetails = null;
var localPhotos = glbThis.getArrayLocalStorage("localPhotos");
if(!localPhotos) {
localPhotos = [];
}
for(var cnt = 0; cnt< localPhotos.length; cnt++) {
var newPhoto = localPhotos[cnt];
if(newPhoto) {
if(newPhoto.status == 'onserver') {
//OK - so it was successfully put onto the server. Recheck to see if it needs to be uploaded again
if(newPhoto.fullData) {
try {
var fullData = newPhoto.fullData;
if(fullData.details && fullData.details.imageURI) {
fullData.loopCnt = 11;
fullData.slowLoopCnt = null; //Start again with a quick loop
checkComplete.push(fullData);
var thisImageURI = fullData.details.imageURI;
glbThis.check(thisImageURI); //This will only upload again if it finds it hasn't been transferred off the
} else {
//This is a case where full details are not available. Do nothing.
glbThis.changeLocalPhotoStatus(newPhoto.imageURI, "cancel");
}
} catch(err) {
//There was a problem parsing the data.
glbThis.changeLocalPhotoStatus(newPhoto.imageURI, "cancel");
}
} else {
//No fullData was added - resend anyway
glbThis.changeLocalPhotoStatus(newPhoto.imageURI, "cancel");
}
} else {
//Needs to be resent
glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName);
}
}
}
return;
},
get: function(url, cb) {
var alreadyReturned = false;
var request = new XMLHttpRequest();
request.open("GET", url, true);
var getTimeout = setTimeout(function() {
if(alreadyReturned == false) { //Don't double up with onerror
alreadyReturned = true;
cb(url, null, "timeout"); // Assume it hasn't gone through - we have a 404 error checking the server
}
}, 5000);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
clearTimeout(getTimeout);
cb(url, request.responseText); // -> request.responseText <- is a result
} else {
cb(url, null);
}
}
}
request.onerror = function() {
if (request.status != 200) {
if(alreadyReturned == false) { //Don't double up with timeout
clearTimeout(getTimeout);
alreadyReturned = true;
cb(url, null);
}
}
}
request.send();
},
scanlan: function(port, cb) {
var _this = this;
if(_this.lan) {
var lan = _this.lan;
totalScanned = 0;
for(var cnt=0; cnt< 255; cnt++){
var machine = cnt.toString();
var url = 'http://' + lan + machine + ':' + port;
this.get(url, function(goodurl, resp, timeout) {
if(resp) {
//This is a good server
totalScanned ++;
//Save the first TODO: if more than one, open another screen here
localStorage.setItem("currentWifiServer", goodurl);
clearInterval(scanning);
cb(goodurl, null);
} else {
if(timeout && timeout == "timeout") {
//Just a timeout
totalScanned ++;
_this.notify("Scanning Wifi. Responses:" + totalScanned);
} else {
//Some form of null error message. Don't count these.
}
}
});
}
var pausing = false;
//timeout check every 6 secs
var scanning = setInterval(function() {
if(totalScanned < 255) {
//Let a user decide to continue
if(pausing == false) {
pausing = true; //Pausing prevents it from opening up more windows
if(confirm("Timeout finding your Wifi server. Note: you have scanned for http://" + lan + "[range of 0-255]:" + port + ", and received " + totalScanned + " responses. Do you wish to keep scanning?")) {
//Yes, do nothing and wait.
pausing = false; //Can start asking again
} else {
//Exit out of here
clearInterval(scanning);
cb(null, "Timeout finding your Wifi server.</br></br><a href='javascript:' onclick=\"app.enterServerManually('We scanned for http://" + lan + "[range of 0-255]:" + port + ", and received " + totalScanned + " responses, but no servers. You can enter this manually below:');\">More Details</a>");
}
}
} else { //Total scanned is complete
//Have scanned the full range, error out of here.
clearInterval(scanning);
cb(null, "We couldn't see your Wifi server.</br></br><a href='javascript:' onclick=\"app.enterServerManually('We scanned for http://" + lan + "[range of 0-255]:" + port + ", and received " + totalScanned + " responses, but no servers. You can enter this manually below:');\">More Details</a>");
}
}, 8000);
} else {
//No lan detected
cb(null,"Local Wifi not detected.<br/><br/><a href='javascript:' onclick=\"app.enterServerManually('Sorry, we could not detect the LAN. You can enter the server address manually below:');\">More Details</a>");
}
},
notify: function(msg) {
//Set the user message
document.getElementById("notify").innerHTML = msg;
},
cancelNotify: function(msg) {
//Set the user message
document.getElementById("cancel-trans").innerHTML = msg;
},
cancelUpload: function(cancelURI) {
var ft = fileTransferMap.getItem(cancelURI);
if (ft)
{
ft.abort(glbThis.win, glbThis.fail);
//remove the photo
glbThis.changeLocalPhotoStatus(cancelURI, "cancel");
}
},
determineFilename: function(imageURIin, idEntered, cb) {
//Determines the filename to use based on the imageURI of the photo,
//and the id entered into the text field.
//Calls back with: cb(err, newFilename, imageURI)
// where err is null for no error, or text of the error,
// and the newFilename as a text string which includes the .jpg at the end
// imageURI is the local filesystem resolved URI
//It will use the current date / time from the phone, thought this format varies slightly
//phone to phone.
//Have connected OK to a server
var idEnteredB = idEntered;
window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) {
deleteThisFile = fileEntry; //Store globally
var imageURI = fileEntry.toURL();
var tempName = idEnteredB;
if((tempName == '')||(tempName == null)) {
tempName = 'image';
}
var initialHash = localStorage.getItem("initialHash");
if((initialHash)&&(initialHash != null)) {
if(initialHash == 'true') {
//Prepend the initial hash
tempName = "#" + tempName;
}
} else {
//Not set, so prepend the initial hash by default
tempName = "#" + tempName;
}
var defaultDir = localStorage.getItem("defaultDir");
if((defaultDir)&&(defaultDir != null)) {
//A hash code signifies a directory to write to
tempName = "#" + defaultDir + " " + tempName;
}
var myoutFile = tempName.replace(/ /g,'-');
var idEnteredC = idEnteredB; //Get a 2nd tier of variable
navigator.globalization.dateToString(
new Date(),
function (date) {
var mydt = date.value.replace(/:/g,'-');
mydt = mydt.replace(/ /g,'-');
mydt = mydt.replace(/\//g,'-');
var aDate = new Date();
var seconds = aDate.getSeconds();
mydt = mydt + "-" + seconds;
mydt = mydt.replace(/,/g,''); //remove any commas from iphone
mydt = mydt.replace(/\./g,'-'); //remove any fullstops
var myNewFileName = myoutFile + '-' + mydt + '.jpg';
cb(null, myNewFileName, imageURI);
},
function () {
navigator.notification.alert('Sorry, there was an error getting the current date\n');
cb("Sorry, there was an error getting the current date");
},
{ formatLength:'medium', selector:'date and time'}
); //End of function in globalization date to string
}, function(evt) {
//An error accessing the file
//and potentially delete phone version
glbThis.changeLocalPhotoStatus(myImageURIin, 'cancel');
cb("Sorry, we could not access the photo file");
}); //End of resolveLocalFileSystemURI
},
uploadPhoto: function(imageURIin, idEntered, newFilename) {
var _this = this;
var usingServer = localStorage.getItem("usingServer");
var idEnteredB = idEntered;
if((!usingServer)||(usingServer == null)) {
//No remove server already connected to, find the server now. And then call upload again
_this.findServer(function(err) {
if(err) {
window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again
glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds.");
//Search again in 10 seconds:
var scope = this;
scope.imageURIin = imageURIin;
scope.idEnteredB = idEnteredB;
scope.newFilename = newFilename;
setTimeout(function() {
glbThis.uploadPhoto(scope.imageURIin, scope.idEnteredB, scope.newFilename)
}, 10000);
} else {
//Now we are connected, upload the photo again
glbThis.uploadPhoto(imageURIin, idEnteredB, newFilename);
}
});
return;
} else {
//Have connected OK to a server
var myImageURIin = imageURIin;
var imageURI = imageURIin;
var options = new FileUploadOptions();
options.fileKey="file1";
options.mimeType="image/jpeg";
var params = new Object();
params.title = idEntered;
if((params.title == '')||(params.title == null)) {
if((idEnteredB == '')||(idEnteredB == null)) {
params.title = 'image';
} else {
params.title = idEnteredB;
}
}
options.fileName = newFilename;
options.params = params;
options.chunkedMode = false; //chunkedMode = false does work, but still having some issues. =true may only work on newer systems?
options.headers = {
Connection: "close"
}
options.idEntered = idEnteredB;
var ft = new FileTransfer();
_this.notify("Uploading " + params.title);
_this.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#f7afbb;\" size=\"30px\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + imageURI + "');\"></ons-icon><br/>Cancel");
ft.onprogress = _this.progress;
var serverReq = usingServer + '/api/photo';
var repeatIfNeeded = {
"imageURI" : imageURI,
"serverReq" : serverReq,
"options" :options,
"failureCount": 0,
"nextAttemptSec": 15
};
retryIfNeeded.push(repeatIfNeeded);
fileTransferMap.setItem(imageURI, ft); //Make sure we can abort this photo later
//Keep the screen awake as we upload
window.plugins.insomnia.keepAwake();
var myImageURI = repeatIfNeeded.imageURI;
ft.upload(imageURI, serverReq, function(result) {
glbThis.win(result, myImageURI);
}, function(result) {
glbThis.fail(result, myImageURI);
}, options);
} //End of connected to a server OK
},
progress: function(progressEvent) {
var statusDom = document.querySelector('#status');
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
statusDom.innerHTML = perc + "% uploaded...";
} else {
if(statusDom.innerHTML == "") {
statusDom.innerHTML = "Uploading";
} else {
statusDom.innerHTML += ".";
}
}
},
retry: function(existingText) {
window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again
var repeatIfNeeded = retryIfNeeded.pop();
if(repeatIfNeeded) {
//Resend within a minute here
var t = new Date();
t.setSeconds(t.getSeconds() + repeatIfNeeded.nextAttemptSec);
var timein = (repeatIfNeeded.nextAttemptSec*1000); //In microseconds
repeatIfNeeded.nextAttemptSec *= 3; //Increase the delay between attempts each time to save battery
if(repeatIfNeeded.nextAttemptSec > 21600) repeatIfNeeded.nextAttemptSec = 21600; //If longer than 6 hours gap, make 6 hours (that is 60x60x6)
var hrMin = t.getHours() + ":" + t.getMinutes();
glbThis.notify(existingText + " Retrying " + repeatIfNeeded.options.params.title + " at " + hrMin);
repeatIfNeeded.failureCount += 1; //Increase this
if(repeatIfNeeded.failureCount > 2) {
//Have tried too many attempts - try to reconnect completely (i.e. go
//from wifi to network and vica versa
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
glbThis.uploadPhoto(repeatIfNeeded.imageURI, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.fileName);
//Clear any existing timeouts
if(repeatIfNeeded.retryTimeout) {
clearTimeout(repeatIfNeeded.retryTimeout);
}
//Clear the current transfer too
repeatIfNeeded.ft.abort();
return;
} else {
//OK in the first few attempts - keep the current connection and try again
//Wait 10 seconds+ here before trying the next upload
repeatIfNeeded.retryTimeout = setTimeout(function() {
repeatIfNeeded.ft = new FileTransfer();
repeatIfNeeded.ft.onprogress = glbThis.progress;
glbThis.notify("Trying to upload " + repeatIfNeeded.options.params.title);
glbThis.cancelNotify("<ons-icon size=\"30px\" style=\"vertical-align: middle; color:#f7afbb;\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + repeatIfNeeded.imageURI + "');\"></ons-icon><br/>Cancel");
retryIfNeeded.push(repeatIfNeeded);
//Keep the screen awake as we upload
window.plugins.insomnia.keepAwake();
var myImageURI = repeatIfNeeded.imageURI;
repeatIfNeeded.ft.upload(repeatIfNeeded.imageURI, repeatIfNeeded.serverReq,
function(result) {
glbThis.win(result, myImageURI);
},function(result) {
glbThis.fail(result, myImageURI);
}, repeatIfNeeded.options);
}, timein); //Wait 10 seconds before trying again
}
}
},
removeCheckComplete: function(imageURI) {
//Loop through the current array and remove the entries
for(var cnt = 0; cnt< checkComplete.length; cnt++) {
if(checkComplete[cnt].details && checkComplete[cnt].details.imageURI && checkComplete[cnt].details.imageURI === imageURI) {
checkComplete[cnt] = null; //Need the delete first to get rid of subobjects
}
}
//Remove the null array entries
checkComplete = glbThis.arrayRemoveNulls(checkComplete);
return;
},
removeRetryIfNeeded: function(imageURI) {
//Loop through the current array and remove the entries
for(var cnt = 0; cnt< retryIfNeeded.length; cnt++) {
if(retryIfNeeded[cnt].imageURI === imageURI) {
retryIfNeeded[cnt] = null; //Need the delete first to get rid of subobjects
}
}
//Remove the null array entries
retryIfNeeded = glbThis.arrayRemoveNulls(retryIfNeeded);
return;
},
check: function(imageURI){
//Checks to see if the next photo on the server (in the checkComplete stack) has been sent on to the PC successfully. If not it will keep pinging until is has been dealt with, or it times out.
var startSlowLoop = false;
var nowChecking = null;
for(var cnt = 0; cnt < checkComplete.length; cnt++) {
if(checkComplete[cnt].details.imageURI === imageURI) {
nowChecking = JSON.parse(JSON.stringify(checkComplete[cnt]));
checkComplete[cnt].loopCnt --; //Decrement the original
if(nowChecking.loopCnt <= 0) {
//Now continue to check with this photo, but only once every 30 seconds, 100 times (i.e. about 45 minutes).
if(!nowChecking.slowLoopCnt) {
//Need to set a slow count
checkComplete[cnt].slowLoopCnt = 100;
startSlowLoop = true;
} else {
//Decrement the slow loop
checkComplete[cnt].slowLoopCnt --;
}
}
}
}
if(!nowChecking) {
//This check is complete, already. Strictly speaking we shouldn't get here unless we've been deleted
return;
}
nowChecking.loopCnt --;
if(nowChecking.loopCnt <= 0) {
//Have finished - remove interval and report back
if(startSlowLoop == true) {
//Have now finished the frequent checks. Move into slower checks.
var myTitle = "Image";
if(nowChecking.details && nowChecking.details.options && nowChecking.details.options.params && nowChecking.details.options.params.title && nowChecking.details.options.params.title != "") {
myTitle = nowChecking.details.options.params.title;
}
document.getElementById("notify").innerHTML = "You are experiencing a slightly longer transfer time than normal, likely due to a slow network. Your image " + myTitle + " should be delivered shortly. <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">Forget</a>";
window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep, we could be here for a while.
//The file exists on the server still - try again in 30 seconds
var thisScope = {};
thisScope.imageURI = imageURI;
setTimeout(function() {
glbThis.check(thisScope.imageURI);
}, 30000);
} else {
//Count down inside the slower checks
nowChecking.slowLoopCnt --;
if(nowChecking.slowLoopCnt <= 0) {
//Have finished the long count down, and given up
document.getElementById("notify").innerHTML = "Sorry, the image is on the remote server, but has not been delivered to your local PC. We will try again once your app restarts. <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">Forget</a>";
glbThis.cancelNotify(""); //Remove any cancel icons
} else {
//Otherwise in the long count down
var myNowChecking = nowChecking;
glbThis.get(nowChecking.fullGet, function(url, resp) {
if((resp === "false")||(resp === false)) {
//File no longer exists, success!
glbThis.cancelNotify(""); //Remove any transfer icons
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
glbThis.removeCheckComplete(myNowChecking.details.imageURI);
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1;
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! ';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more;
}
}
} else {
return;
}
//and delete phone version
if(myNowChecking.details) {
glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel');
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.';
}
} else {
//The file exists on the server still - try again in 30 seconds
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
var moreLength = (checkComplete.length + retryIfNeeded.length);
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(!nowChecking.slowLoopCnt) {
nowChecking.slowLoopCnt = 100; //Init
}
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' has not finished transferring. Checking again in 30 seconds. ' + myNowChecking.slowLoopCnt;
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' has not finished transferring. Checking again in 30 seconds.' + more + ' ' + myNowChecking.slowLoopCnt;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more + myNowChecking.slowLoopCnt;
}
}
} else {
return;
}
var thisScope = {};
if(myNowChecking && myNowChecking.details) {
thisScope.imageURI = myNowChecking.details.imageURI;
setTimeout(function() {
glbThis.check(thisScope.imageURI);
}, 30000);
}
}
});
}
}
} else {
//Try a get request to the check
//Get the current file data
glbThis.cancelNotify(""); //Remove any cancel icons
var myNowChecking = nowChecking;
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1; //The -1 is to not include the current in the count
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..' + more;
} else {
document.getElementById("notify").innerHTML = 'Image on server. Transferring to PC..' + more;
}
}
glbThis.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#DDD;\" size=\"20px\" spin icon=\"fa-spinner\"></ons-icon><br/>");
} else {
return;
}
var myNowChecking = nowChecking;
glbThis.get(nowChecking.fullGet, function(url, resp) {
if((resp === "false")||(resp === false)) {
//File no longer exists, success!
glbThis.cancelNotify(""); //Remove any transfer icons
glbThis.removeCheckComplete(myNowChecking.details.imageURI);
var myTitle = "Image";
if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") {
myTitle = myNowChecking.details.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
var moreLength = (checkComplete.length + retryIfNeeded.length);
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more;
}
}
} else {
return;
}
//and delete phone version
if(myNowChecking.details) {
glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel');
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more + ' Note: The image will be resent on a restart to verify.';
}
} else {
//The file exists on the server still - try again in a few moments
var thisScope = {};
if(myNowChecking && myNowChecking.details) {
thisScope.imageURI = myNowChecking.details.imageURI;
setTimeout(function() {
glbThis.check(thisScope.imageURI);
}, 2000);
}
}
});
}
},
win: function(r, imageURI) {
//Have finished transferring the file to the server
window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again
document.querySelector('#status').innerHTML = ""; //Clear progress status
glbThis.cancelNotify(""); //Remove any cancel icons
//Check if this was a transfer to the remote server
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
if((r.responseCode == 200)||(r.response.indexOf("200") != -1)) {
var remoteServer = localStorage.getItem("serverRemote");
if(remoteServer == 'false') {
//i.e. Wifi case
glbThis.cancelNotify(""); //Remove any transfer icons
//and delete phone version of file
var repeatIfNeeded = null;
for(var cnt=0; cnt< retryIfNeeded.length; cnt++) {
if(retryIfNeeded[cnt].imageURI === imageURI) {
repeatIfNeeded = JSON.parse(JSON.stringify(retryIfNeeded[cnt]));
}
}
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1;
if(moreLength >= 0) {
if(moreLength == 0) {
var more = "";
} else {
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
}
} else {
return;
}
var myTitle = "Image";
if(repeatIfNeeded) {
glbThis.removeRetryIfNeeded(repeatIfNeeded.imageURI);
if(repeatIfNeeded && repeatIfNeeded.options && repeatIfNeeded.options.params && repeatIfNeeded.options.params.title && repeatIfNeeded.options.params.title != "") {
myTitle = repeatIfNeeded.options.params.title;
if(myTitle === "image") myTitle = "Image";
document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more;
} else {
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more;
}
glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'cancel');
} else {
//Trying to check, but no file on stack
document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more + ' Note: The image will be resent on a restart to verify.';
}
} else {
//Onto remote server - now do some pings to check we have got to the PC
//and delete phone version of file
var repeatIfNeeded = null;
for(var cnt=0; cnt< retryIfNeeded.length; cnt++) {
if(retryIfNeeded[cnt].imageURI === imageURI) {
repeatIfNeeded = JSON.parse(JSON.stringify(retryIfNeeded[cnt]));
}
}
var moreLength = (checkComplete.length + retryIfNeeded.length) - 1;
var more = " <a style=\"color:#f7afbb; text-decoration: none;\" href=\"javascript:\" onclick=\"app.askForgetAllPhotos(); return false;\">" + moreLength + " more</a>";
var myTitle = "Image";
if(repeatIfNeeded && repeatIfNeeded.options && repeatIfNeeded.options.params && repeatIfNeeded.options.params.title && repeatIfNeeded.options.params.title != "") {
myTitle = repeatIfNeeded.options.params.title;
}
if(myTitle === "image") myTitle = "Image";
if(moreLength >= 0) {
if(moreLength == 0) {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..';
} else {
if(myTitle != "") {
document.getElementById("notify").innerHTML = myTitle + ' on server. Transferring to PC..' + more;
} else {
document.getElementById("notify").innerHTML = 'Image on server. Transferring to PC..' + more;
}
}
glbThis.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#DDD;\" size=\"20px\" spin icon=\"fa-spinner\"></ons-icon><br/>");
} else {
return;
}
if(repeatIfNeeded) {
var thisFile = repeatIfNeeded.options.fileName;
var usingServer = localStorage.getItem("usingServer");
if(usingServer) { //Note, we have had a case of a null server here. In this case
//simply don't do any follow on checks.
var fullGet = usingServer + '/check=' + encodeURIComponent(thisFile);
var nowChecking = {};
nowChecking.loopCnt = 11; //Max timeout = 11*2 = 22 secs but also a timeout of 5 seconds on the request.
nowChecking.fullGet = fullGet;
nowChecking.details = repeatIfNeeded;
checkComplete.push(nowChecking);
//Set an 'onserver' status
glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'onserver', nowChecking);
var self = {};
self.thisImageURI = repeatIfNeeded.imageURI;
setTimeout(function() { //Wait two seconds and then do a check
glbThis.check(self.thisImageURI);
}, 2000);
glbThis.removeRetryIfNeeded(repeatIfNeeded.imageURI);
} else {
//Set an 'onserver' status, and remove this entry
glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'onserver', nowChecking);
glbThis.removeRetryIfNeeded(repeatIfNeeded.imageURI);
}
} else {
//Trying to check, but no file on stack
}
} //End of if(remoteServer == 'false')
//Save the current server settings for future reuse
glbThis.saveServer();
} else {
//Retry sending
glbThis.retry("");
}
},
fail: function(error, imageURI) {
window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep
document.querySelector('#status').innerHTML = ""; //Clear progress status
glbThis.cancelNotify(""); //Remove any cancel icons
switch(error.code)
{
case 1:
glbThis.notify("The photo was uploaded.");
//Remove the photo from the list
glbThis.changeLocalPhotoStatus(imageURI, 'cancel');
break;
case 2:
glbThis.notify("Sorry you have tried to send it to an invalid URL.");
break;
case 3:
glbThis.notify("Waiting for better reception..");
glbThis.retry("Waiting for better reception...</br>");
break;
case 4:
glbThis.notify("Your image transfer was aborted.");
//No need to retry here: glbThis.retry("Sorry, your image transfer was aborted.</br>");
break;
default:
glbThis.notify("An error has occurred: Code = " + error.code);
break;
}
},
forgetAllPhotos: function() {
//Loop through all photos in retryIfNeeded, checkComplete and localPhotos and remove them
//all.
var _this = this;
glbThis = this;
for(var cnta = 0; cnta < retryIfNeeded.length; cnta++) {
if(retryIfNeeded[cnta].imageURI) {
_this.cancelUpload(retryIfNeeded[cnta].imageURI);
_this.removeRetryIfNeeded(retryIfNeeded[cnta].imageURI);
}
}
for(var cntb = 0; cntb < checkComplete.length; cntb++) {
if(checkComplete[cntb].details && checkComplete[cntb].details.imageURI) {
_this.removeCheckComplete(checkComplete[cntb].details.imageURI);
}
}
var localPhotos = _this.getArrayLocalStorage("localPhotos");
for(var cntc = 0; cntc < localPhotos.length; cntc++) {
if(localPhotos[cntc].imageURI) {
_this.changeLocalPhotoStatus(localPhotos[cntc].imageURI, 'cancel');
}
}
glbThis.notify("All photos have been deleted and forgotten.");
glbThis.cancelNotify(""); //Remove any cancel icons
},
askForgetAllPhotos: function() {
//Ask if we want to remove all the photos on the system
//Get a live current photo count
var moreLength = checkComplete.length + retryIfNeeded.length;
if(moreLength == 1) {
var moreStr = "is " + moreLength + " photo";
} else {
var moreStr = "are " + moreLength + " photos";
}
navigator.notification.confirm(
'There ' + moreStr + ' in memory. Do you want to forget and delete all of these photos? (Some of them may have been sent already)', // message
function(buttonIndex) {
if(buttonIndex == 1) {
glbThis.forgetAllPhotos();
return;
} else {
return;
}
}, // callback to invoke
'Forget Photos', // title
['Yes','No'] // buttonLabels
);
},
getip: function(cb) {
var _this = glbThis;
//timeout after 3 secs -rerun this.findServer()
var iptime = setTimeout(function() {
var err = "You don't appear to be connected to your wifi. Please connect and try again.";
cb(null, err);
}, 5000);
networkinterface.getWiFiIPAddress(function(ipInfo) {
_this.ip = ipInfo.ip; //note: we could use ipInfo.subnet here but, this could be a 16-bit subnet rather than 24-bit?
var len = ipInfo.ip.lastIndexOf('\.') + 1;
_this.lan = ipInfo.ip.substr(0,len);
clearTimeout(iptime);
cb(null);
},
function(err) {
var retErr = "Sorry, there was a problem getting your IP address.<br/><br/><a href='javascript:' onclick=\"navigator.notification.alert('Error: " + err + "', function() {}, 'More Details');\">More Details</a>";
cb(null, retErr);
});
},
factoryReset: function() {
//We have connected to a server OK
var _this = this;
navigator.notification.confirm(
'Are you sure? All your saved PCs and other settings will be cleared.', // message
function(buttonIndex) {
if(buttonIndex == 1) {
localStorage.clear();
localStorage.removeItem("usingServer"); //Init it
localStorage.removeItem("defaultDir"); //Init it
localStorage.removeItem("currentRemoteServer");
localStorage.removeItem("currentWifiServer");
localStorage.setItem("initialHash", 'true'); //Default to write a folder
document.getElementById("always-create-folder").checked = true;
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = "";
alert("Cleared all saved PCs.");
glbThis.openSettings();
}
}, // callback to invoke
'Clear Settings', // title
['Ok','Cancel'] // buttonLabels
);
return false;
},
checkDefaultDir: function(server) {
//Check if the default server has a default dir eg. input:
// http://123.123.123.123:5566/write/fshoreihtskhfv
//Where the defaultDir would be 'fshoreihtskhfv'
//Returns '{ server: "http://123.123.123.123:5566", dir: "fshoreihtskhfv"'
var requiredStr = "/write/";
var startsAt = server.indexOf(requiredStr);
if(startsAt >= 0) {
//Get the default dir after the /write/ string
var startFrom = startsAt + requiredStr.length;
var defaultDir = server.substr(startFrom);
var properServer = server.substr(0, startsAt);
return { server: properServer, dir: defaultDir };
} else {
return { server: server, dir: "" };
}
},
connect: function(results) {
//Save the server with a name
//Get existing settings array
switch(results.buttonIndex) {
case 1:
//Clicked on 'Ok'
//Start the pairing process
var pairUrl = centralPairingUrl + '?compare=' + results.input1;
glbThis.notify("Pairing..");
glbThis.get(pairUrl, function(url, resp) {
if(resp) {
resp = resp.replace('\n', '')
if(resp == 'nomatch') {
glbThis.notify("Sorry, there was no match for that code.");
return;
} else {
var server = resp;
glbThis.notify("Pairing success.");
//And save this server
localStorage.setItem("currentRemoteServer",server);
localStorage.removeItem("currentWifiServer"); //Clear the wifi
localStorage.removeItem("usingServer"); //Init it
localStorage.removeItem("defaultDir"); //Init it
navigator.notification.confirm(
'Do you want to connect via WiFi, if it is available, also?', // message
function(buttonIndex) {
if(buttonIndex == 1) {
//yes, we also want to connect via wifi
glbThis.checkWifi(function(err) {
if(err) {
//An error finding wifi
glbThis.notify(err);
glbThis.bigButton();
} else {
//Ready to take a picture, rerun with this
//wifi server
glbThis.notify("WiFi paired successfully.");
glbThis.bigButton();
}
});
} else {
glbThis.notify("Pairing success, without WiFi.");
glbThis.bigButton();
}
}, // callback to invoke
'Pairing Success!', // title
['Yes','No'] // buttonLabels
);
return;
}
} else {
//A 404 response
glbThis.notify("Sorry, we could not connect to the pairing server. Please try again.");
}
}); //end of get
return;
break;
case 2:
//Clicked on 'Wifi only'
//Otherwise, first time we are running the app this session
localStorage.removeItem("currentWifiServer"); //Clear the wifi
localStorage.removeItem("currentRemoteServer"); //Clear the wifi
localStorage.removeItem("usingServer"); //Init it
localStorage.removeItem("defaultDir"); //Init it
glbThis.checkWifi(function(err) {
if(err) {
//An error finding server - likely need to enter a pairing code. Warn the user
glbThis.notify(err);
} else {
//Ready to take a picture, rerun
glbThis.notify("Wifi paired successfully.");
glbThis.bigButton();
}
});
return;
break;
default:
//Clicked on 'Cancel'
break;
}
},
bigButton: function() {
//Called when pushing the big button
var _this = this;
var foundRemoteServer = null;
var foundWifiServer = null;
foundRemoteServer = localStorage.getItem("currentRemoteServer");
foundWifiServer = localStorage.getItem("currentWifiServer");
if(((foundRemoteServer == null)||(foundRemoteServer == ""))&&
((foundWifiServer == null)||(foundWifiServer == ""))) {
//Likely need to enter a pairing code. Warn the user
//No current server - first time with this new connection
//We have connected to a server OK
navigator.notification.prompt(
'Please enter the 4 letter pairing code from your PC.', // message
glbThis.connect, // callback to invoke
'New Connection', // title
['Ok','Use Wifi Only','Cancel'], // buttonLabels
'' // defaultText
);
} else {
//Ready to take a picture
_this.takePicture();
}
},
checkWifi: function(cb) {
glbThis.notify("Checking Wifi connection");
this.getip(function(ip, err) {
if(err) {
cb(err);
return;
}
glbThis.notify("Scanning Wifi");
glbThis.scanlan('5566', function(url, err) {
if(err) {
cb(err);
} else {
cb(null);
}
});
});
},
getOptions: function(guid, cb) {
//Input a server dir e.g. uPSE4UWHmJ8XqFUqvf
// where the last part is the guid.
//Get a URL like this: https://atomjump.com/med-settings.php?type=get&guid=uPSE4UWHmJ8XqFUqvf
//to get a .json array of options.
var settingsUrl = "https://atomjump.com/med-settings.php?type=get&guid=" + guid;
glbThis.get(settingsUrl, function(url, resp) {
if(resp != "") {
var options = JSON.stringify(resp); //Or is it without the json parsing?
if(options) {
//Set local storage
//localStorage.removeItem("serverOptions");
localStorage.setItem("serverOptions", options);
cb(null);
} else {
cb("No options");
}
} else {
cb("No options");
}
});
},
clearOptions: function() {
localStorage.removeItem("serverOptions");
},
findServer: function(cb) {
//Check storage for any saved current servers, and set the remote and wifi servers
//along with splitting any subdirectories, ready for use by the the uploader.
//Then actually try to connect - if wifi is an option, use that first
var _this = this;
var alreadyReturned = false;
var found = false;
//Clear off
var foundRemoteServer = null;
var foundWifiServer = null;
var foundRemoteDir = null;
var foundWifiDir = null;
var usingServer = null;
this.clearOptions();
//Early out
usingServer = localStorage.getItem("usingServer");
if((usingServer)&&(usingServer != null)) {
cb(null);
return;
}
foundRemoteServer = localStorage.getItem("currentRemoteServer");
foundWifiServer = localStorage.getItem("currentWifiServer");
if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "")) {
//Already found a remote server
//Generate the directory split, if any. Setting RAM foundServer and defaultDir
var split = this.checkDefaultDir(foundRemoteServer);
foundRemoteServer = split.server;
foundRemoteDir = split.dir;
} else {
foundRemoteServer = null;
foundRemoteDir = null;
}
//Check if we have a Wifi option
if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "")) {
//Already found wifi
//Generate the directory split, if any. Setting RAM foundServer and defaultDir
var split = this.checkDefaultDir(foundWifiServer);
foundWifiServer = split.server;
foundWifiDir = split.dir;
} else {
foundWifiServer = null;
foundWifiDir = null;
}
//Early out:
if((foundWifiServer == null)&&(foundRemoteServer == null)) {
cb('No known server.');
return;
}
//Now try the wifi server as the first option to use if it exists:
if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "null")) {
//Ping the wifi server
glbThis.notify('Trying to connect to the wifi server..');
//Timeout after 5 secs for the following ping
var scanning = setTimeout(function() {
glbThis.notify('Timeout finding your wifi server.</br>Trying remote server..');
//Else can't communicate with the wifi server at this time.
//Try the remote server
if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "null")) {
var scanningB = setTimeout(function() {
//Timed out connecting to the remote server - that was the
//last option.
localStorage.removeItem("usingServer");
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
if(alreadyReturned == false) {
alreadyReturned = true;
cb('No server found');
}
}, 6000);
glbThis.get(foundRemoteServer, function(url, resp) {
if(resp != "") {
//Success, got a connection to the remote server
clearTimeout(scanningB); //Ensure we don't error out
localStorage.setItem("usingServer", foundRemoteServer);
localStorage.setItem("serverRemote", 'true');
localStorage.setItem("defaultDir", foundRemoteDir);
if(alreadyReturned == false) {
alreadyReturned = true;
//Get any global options
glbThis.getOptions(foundRemoteDir);
cb(null);
}
clearTimeout(scanning); //Ensure we don't error out
}
});
} else {
//Only wifi existed
localStorage.removeItem("usingServer");
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
if(alreadyReturned == false) {
alreadyReturned = true;
cb('No server found');
}
}
}, 2000);
//Ping the wifi server
glbThis.get(foundWifiServer, function(url, resp) {
if(resp != "") {
//Success, got a connection to the wifi
clearTimeout(scanning); //Ensure we don't error out
localStorage.setItem("usingServer", foundWifiServer);
localStorage.setItem("defaultDir", foundWifiDir);
localStorage.setItem("serverRemote", 'false');
if(alreadyReturned == false) {
alreadyReturned = true;
cb(null); //Success found server
}
}
});
} else {
//OK - no wifi option - go straight to the remote server
//Try the remote server
glbThis.notify('Trying to connect to the remote server....');
var scanning = setTimeout(function() {
//Timed out connecting to the remote server - that was the
//last option.
localStorage.removeItem("usingServer");
localStorage.removeItem("defaultDir");
localStorage.removeItem("serverRemote");
if(alreadyReturned == false) {
alreadyReturned = true;
cb('No server found');
}
}, 6000);
_this.get(foundRemoteServer, function(url, resp) {
if(resp != "") {
//Success, got a connection to the remote server
localStorage.setItem("usingServer", foundRemoteServer);
localStorage.setItem("defaultDir", foundRemoteDir);
localStorage.setItem("serverRemote", 'true');
if(alreadyReturned == false) {
alreadyReturned = true;
//Get any global options
glbThis.getOptions(foundRemoteDir);
cb(null);
}
clearTimeout(scanning); //Ensure we don't error out
}
});
}
},
/* Settings Functions */
openSettings: function() {
//Open the settings screen
var html = this.listServers();
document.getElementById("settings").innerHTML = html;
document.getElementById("settings-popup").style.display = "block";
},
closeSettings: function() {
//Close the settings screen
document.getElementById("settings-popup").style.display = "none";
},
listServers: function() {
//List the available servers
var settings = this.getArrayLocalStorage("settings");
if(settings) {
var html = "<ons-list><ons-list-header>Select a PC to use now:</ons-list-header>";
//Convert the array into html
for(var cnt=0; cnt< settings.length; cnt++) {
html = html + "<ons-list-item><ons-list-item onclick='app.setServer(" + cnt + ");'>" + settings[cnt].name + "</ons-list-item><div class='right'><ons-icon icon='md-delete' onclick='app.deleteServer(" + cnt + ");'></ons-icon></div></ons-list-item>";
}
html = html + "</ons-list>";
} else {
var html = "<ons-list><ons-list-header>PCs Stored</ons-list-header>";
var html = html + "<ons-list-item><ons-list-item>Default</ons-list-item><div class='right'><ons-icon icon='md-delete'style='color:#AAA></ons-icon></div></ons-list-item>";
html = html + "</ons-list>";
}
return html;
},
setServer: function(serverId) {
//Set the server to the input server id
var settings = this.getArrayLocalStorage("settings");
var currentRemoteServer = settings[serverId].currentRemoteServer;
var currentWifiServer = settings[serverId].currentWifiServer;
localStorage.removeItem("usingServer"); //reset the currently used server
//Save the current server
localStorage.removeItem("defaultDir");
//Remove if one of these doesn't exist, and use the other.
if((!currentWifiServer)||(currentWifiServer == null)||(currentWifiServer =="")) {
localStorage.removeItem("currentWifiServer");
} else {
localStorage.setItem("currentWifiServer", currentWifiServer);
}
if((!currentRemoteServer)||(currentRemoteServer == null)||(currentRemoteServer == "")) {
localStorage.removeItem("currentRemoteServer");
} else {
localStorage.setItem("currentRemoteServer", currentRemoteServer);
}
//Set the localstorage
localStorage.setItem("currentServerName", settings[serverId].name);
navigator.notification.alert("Switched to: " + settings[serverId].name, function() {}, "Changing PC");
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = settings[serverId].name;
this.closeSettings();
return false;
},
newServer: function() {
//Create a new server.
//This is actually effectively resetting, and we will allow the normal functions to input a new one
localStorage.removeItem("usingServer");
//Remove the current one
localStorage.removeItem("currentRemoteServer");
localStorage.removeItem("currentWifiServer");
this.notify("Tap above to activate."); //Clear off old notifications
//Ask for a name of the current Server:
navigator.notification.prompt(
'Please enter a name for this PC', // message
this.saveServerName, // callback to invoke
'PC Name', // title
['Ok','Cancel'], // buttonLabels
'Main' // defaultText
);
},
deleteServer: function(serverId) {
//Delete an existing server
this.myServerId = serverId;
navigator.notification.confirm(
'Are you sure? This PC will be removed from memory.', // message
function(buttonIndex) {
if(buttonIndex == 1) {
var settings = glbThis.getArrayLocalStorage("settings");
if((settings == null)|| (settings == '')) {
//Nothing to delete
} else {
//Check if it is deleting the current entry
var deleteName = settings[glbThis.myServerId].name;
var currentServerName = localStorage.getItem("currentServerName");
if((currentServerName) && (deleteName) && (currentServerName == deleteName)) {
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = "";
localStorage.removeItem("currentRemoteServer");
localStorage.removeItem("currentWifiServer");
localStorage.removeItem("currentServerName");
}
settings.splice(glbThis.myServerId, 1); //Remove the entry entirely from array
glbThis.setArrayLocalStorage("settings", settings);
}
glbThis.openSettings(); //refresh
}
}, // callback to invoke
'Remove PC', // title
['Ok','Cancel'] // buttonLabels
);
},
saveServerName: function(results) {
//Save the server with a name - but since this is new,
//Get existing settings array
if(results.buttonIndex == 1) {
//Clicked on 'Ok'
localStorage.setItem("currentServerName", results.input1);
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = results.input1;
glbThis.closeSettings();
return;
} else {
//Clicked on 'Exit'. Do nothing.
return;
}
},
displayServerName: function() {
//Call this during initialisation on app startup
var currentServerName = localStorage.getItem("currentServerName");
if((currentServerName) && (currentServerName != null)) {
//Now refresh the current server display
document.getElementById("currentPC").innerHTML = currentServerName;
} else {
document.getElementById("currentPC").innerHTML = "";
}
},
saveIdInput: function(status) {
//Save the idInput. input true/false true = 'start with a hash'
// false = 'start with blank'
//Get existing settings array
if(status == true) {
//Show a hash by default
localStorage.setItem("initialHash", "true");
} else {
//Remove the hash by default
localStorage.setItem("initialHash", "false");
}
},
enterServerManually: function(message) {
var _this = this;
//Ask for a name of the current Server:
navigator.notification.prompt(
message, // message
_this.saveServerAddress, // callback to invoke
'Set Server Manually', // title
['Ok','Cancel'], // buttonLabels
'http://' + _this.lan + ':5566' // defaultText
);
return false;
},
saveServerAddress: function(result) {
var _this = this;
switch(result.buttonIndex) {
case 1:
//Clicked on 'Ok'
//Called from enterServerManually
localStorage.setItem("currentWifiServer", result.input1);
localStorage.setItem("usingServer", result.input1);
//Now try to connect
_this.findServer(function(err) {
alert("Got it error:" + err); //TESTING REMOVE ME
if(err) {
glbThis.notify("Sorry, we cannot connect to the server");
localStorage.removeItem("usingServer"); //This will force a reconnection
localStorage.removeItem("defaultDir");
localStorage.removeItem("currentWifiServer");
} else {
//Now we are connected - so we can get the photo
glbThis.bigButton();
}
});
break;
default:
//Clicked on 'Cancel'
break;
}
return false;
},
displayIdInput: function() {
//Call this during initialisation on app startup
var initialHash = localStorage.getItem("initialHash");
if((initialHash) && (initialHash != null)) {
//Now refresh the current ID field
if(initialHash == "true") {
document.getElementById("always-create-folder").checked = true;
} else {
document.getElementById("always-create-folder").checked = false;
}
}
},
saveServer: function() {
//Run this after a successful upload
var currentServerName = localStorage.getItem("currentServerName");
var currentRemoteServer = localStorage.getItem("currentRemoteServer");
var currentWifiServer = localStorage.getItem("currentWifiServer");
if((!currentServerName) ||(currentServerName == null)) currentServerName = "Default";
if((!currentRemoteServer) ||(currentRemoteServer == null)) currentRemoteServer = "";
if((!currentWifiServer) ||(currentWifiServer == null)) currentWifiServer = "";
var settings = glbThis.getArrayLocalStorage("settings");
//Create a new entry - which will be blank to being with
var newSetting = {
"name": currentServerName, //As input by the user
"currentRemoteServer": currentRemoteServer,
"currentWifiServer": currentWifiServer
};
if((settings == null)|| (settings == '')) {
//Creating an array for the first time
var settings = [];
settings.push(newSetting); //Save back to the array
} else {
//Check if we are writing over the existing entries
var writeOver = false;
for(cnt = 0; cnt< settings.length; cnt++) {
if(settings[cnt].name == currentServerName) {
writeOver = true;
settings[cnt] = newSetting;
}
}
if(writeOver == false) {
settings.push(newSetting); //Save back to the array
}
}
//Save back to the persistent settings
glbThis.setArrayLocalStorage("settings", settings);
return;
},
//Array storage for app permanent settings (see http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/)
setArrayLocalStorage: function(mykey, myobj) {
return localStorage.setItem(mykey, JSON.stringify(myobj));
},
getArrayLocalStorage: function(mykey) {
return JSON.parse(localStorage.getItem(mykey));
}
};
| find server
| www/js/index.js | find server | <ide><path>ww/js/index.js
<ide> clearInterval(scanning);
<ide> cb(goodurl, null);
<ide> } else {
<del> if(timeout && timeout == "timeout") {
<del> //Just a timeout
<del> totalScanned ++;
<del> _this.notify("Scanning Wifi. Responses:" + totalScanned);
<del> } else {
<del> //Some form of null error message. Don't count these.
<del> }
<add>
<add> totalScanned ++;
<add> _this.notify("Scanning Wifi. Responses:" + totalScanned);
<add>
<ide> }
<ide>
<ide> |
|
Java | apache-2.0 | 48ed4e370fcf01dc098c17111a49e88e73a278ce | 0 | JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse | package edu.harvard.iq.dataverse.api;
import edu.harvard.iq.dataverse.ControlledVocabularyValue;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.DataFileServiceBean;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DatasetField;
import edu.harvard.iq.dataverse.DatasetFieldCompoundValue;
import edu.harvard.iq.dataverse.DatasetFieldServiceBean;
import edu.harvard.iq.dataverse.DatasetFieldType;
import edu.harvard.iq.dataverse.DatasetFieldValue;
import edu.harvard.iq.dataverse.DatasetLock;
import edu.harvard.iq.dataverse.DatasetServiceBean;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.Dataverse;
import edu.harvard.iq.dataverse.DataverseServiceBean;
import edu.harvard.iq.dataverse.DataverseSession;
import edu.harvard.iq.dataverse.EjbDataverseEngine;
import edu.harvard.iq.dataverse.MetadataBlock;
import edu.harvard.iq.dataverse.MetadataBlockServiceBean;
import edu.harvard.iq.dataverse.PermissionServiceBean;
import edu.harvard.iq.dataverse.UserNotification;
import edu.harvard.iq.dataverse.UserNotificationServiceBean;
import static edu.harvard.iq.dataverse.api.AbstractApiBean.error;
import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;
import edu.harvard.iq.dataverse.authorization.DataverseRole;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.RoleAssignee;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.batch.jobs.importer.ImportMode;
import edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleException;
import edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleUtil;
import edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse;
import edu.harvard.iq.dataverse.dataset.DatasetThumbnail;
import edu.harvard.iq.dataverse.dataset.DatasetUtil;
import edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper;
import edu.harvard.iq.dataverse.datasetutility.DataFileTagException;
import edu.harvard.iq.dataverse.datasetutility.NoFilesException;
import edu.harvard.iq.dataverse.datasetutility.OptionalFileParams;
import edu.harvard.iq.dataverse.engine.command.Command;
import edu.harvard.iq.dataverse.engine.command.DataverseRequest;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand;
import edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.CreatePrivateUrlCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetLinkingDataverseCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeletePrivateUrlCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DestroyDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetSpecificPublishedDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetLatestAccessibleDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetLatestPublishedDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetPrivateUrlCommand;
import edu.harvard.iq.dataverse.engine.command.impl.ImportFromFileSystemCommand;
import edu.harvard.iq.dataverse.engine.command.impl.LinkDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.ListRoleAssignments;
import edu.harvard.iq.dataverse.engine.command.impl.ListVersionsCommand;
import edu.harvard.iq.dataverse.engine.command.impl.MoveDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.PublishDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.PublishDatasetResult;
import edu.harvard.iq.dataverse.engine.command.impl.RequestRsyncScriptCommand;
import edu.harvard.iq.dataverse.engine.command.impl.ReturnDatasetToAuthorCommand;
import edu.harvard.iq.dataverse.engine.command.impl.SetDatasetCitationDateCommand;
import edu.harvard.iq.dataverse.engine.command.impl.SubmitDatasetForReviewCommand;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetTargetURLCommand;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetThumbnailCommand;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetVersionCommand;
import edu.harvard.iq.dataverse.export.DDIExportServiceBean;
import edu.harvard.iq.dataverse.export.ExportService;
import edu.harvard.iq.dataverse.ingest.IngestServiceBean;
import edu.harvard.iq.dataverse.privateurl.PrivateUrl;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import edu.harvard.iq.dataverse.util.EjbUtil;
import edu.harvard.iq.dataverse.util.SystemConfig;
import edu.harvard.iq.dataverse.util.json.JsonParseException;
import static edu.harvard.iq.dataverse.util.json.JsonPrinter.*;
import edu.harvard.iq.dataverse.workflow.Workflow;
import edu.harvard.iq.dataverse.workflow.WorkflowContext;
import edu.harvard.iq.dataverse.workflow.WorkflowServiceBean;
import java.io.InputStream;
import java.io.StringReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
@Path("datasets")
public class Datasets extends AbstractApiBean {
private static final Logger logger = Logger.getLogger(Datasets.class.getCanonicalName());
@Inject DataverseSession session;
@EJB
DatasetServiceBean datasetService;
@EJB
DataverseServiceBean dataverseService;
@EJB
UserNotificationServiceBean userNotificationService;
@EJB
PermissionServiceBean permissionService;
@EJB
AuthenticationServiceBean authenticationServiceBean;
@EJB
DDIExportServiceBean ddiExportService;
@EJB
DatasetFieldServiceBean datasetfieldService;
@EJB
MetadataBlockServiceBean metadataBlockService;
@EJB
DataFileServiceBean fileService;
@EJB
IngestServiceBean ingestService;
@EJB
EjbDataverseEngine commandEngine;
/**
* Used to consolidate the way we parse and handle dataset versions.
* @param <T>
*/
private interface DsVersionHandler<T> {
T handleLatest();
T handleDraft();
T handleSpecific( long major, long minor );
T handleLatestPublished();
}
@GET
@Path("{id}")
public Response getDataset(@PathParam("id") String id) {
return response( req -> {
final Dataset retrieved = execCommand(new GetDatasetCommand(req, findDatasetOrDie(id)));
final DatasetVersion latest = execCommand(new GetLatestAccessibleDatasetVersionCommand(req, retrieved));
final JsonObjectBuilder jsonbuilder = json(retrieved);
return allowCors(ok(jsonbuilder.add("latestVersion", (latest != null) ? json(latest) : null)));
});
}
// TODO:
// This API call should, ideally, call findUserOrDie() and the GetDatasetCommand
// to obtain the dataset that we are trying to export - which would handle
// Auth in the process... For now, Auth isn't necessary - since export ONLY
// WORKS on published datasets, which are open to the world. -- L.A. 4.5
@GET
@Path("/export")
@Produces({"application/xml", "application/json"})
public Response exportDataset(@QueryParam("persistentId") String persistentId, @QueryParam("exporter") String exporter) {
try {
Dataset dataset = datasetService.findByGlobalId(persistentId);
if (dataset == null) {
return error(Response.Status.NOT_FOUND, "A dataset with the persistentId " + persistentId + " could not be found.");
}
ExportService instance = ExportService.getInstance(settingsSvc);
String xml = instance.getExportAsString(dataset, exporter);
// I'm wondering if this going to become a performance problem
// with really GIANT datasets,
// the fact that we are passing these exports, blobs of JSON, and,
// especially, DDI XML as complete strings. It would be nicer
// if we could stream instead - and the export service already can
// give it to as as a stream; then we could start sending the
// output to the remote client as soon as we got the first bytes,
// without waiting for the whole thing to be generated and buffered...
// (the way Access API streams its output).
// -- L.A., 4.5
logger.fine("xml to return: " + xml);
String mediaType = MediaType.TEXT_PLAIN;//PM - output formats appear to be either JSON or XML, unclear why text/plain is being used as default content-type.
if (instance.isXMLFormat(exporter)){
mediaType = MediaType.APPLICATION_XML;
}
return allowCors(Response.ok()
.entity(xml)
.type(mediaType).
build());
} catch (Exception wr) {
return error(Response.Status.FORBIDDEN, "Export Failed");
}
}
@DELETE
@Path("{id}")
public Response deleteDataset( @PathParam("id") String id) {
return response( req -> {
execCommand( new DeleteDatasetCommand(req, findDatasetOrDie(id)));
return ok("Dataset " + id + " deleted");
});
}
@DELETE
@Path("{id}/destroy")
public Response destroyDataset( @PathParam("id") String id) {
return response( req -> {
execCommand( new DestroyDatasetCommand(findDatasetOrDie(id), req) );
return ok("Dataset " + id + " destroyed");
});
}
@DELETE
@Path("{datasetId}/deleteLink/{linkedDataverseId}")
public Response deleteDatasetLinkingDataverse( @PathParam("datasetId") String datasetId, @PathParam("linkedDataverseId") String linkedDataverseId) {
boolean index = true;
return response(req -> {
execCommand(new DeleteDatasetLinkingDataverseCommand(req, findDatasetOrDie(datasetId), findDatasetLinkingDataverseOrDie(datasetId, linkedDataverseId), index));
return ok("Link from Dataset " + datasetId + " to linked Dataverse " + linkedDataverseId + " deleted");
});
}
@PUT
@Path("{id}/citationdate")
public Response setCitationDate( @PathParam("id") String id, String dsfTypeName) {
return response( req -> {
if ( dsfTypeName.trim().isEmpty() ){
return badRequest("Please provide a dataset field type in the requst body.");
}
DatasetFieldType dsfType = null;
if (!":publicationDate".equals(dsfTypeName)) {
dsfType = datasetFieldSvc.findByName(dsfTypeName);
if (dsfType == null) {
return badRequest("Dataset Field Type Name " + dsfTypeName + " not found.");
}
}
execCommand(new SetDatasetCitationDateCommand(req, findDatasetOrDie(id), dsfType));
return ok("Citation Date for dataset " + id + " set to: " + (dsfType != null ? dsfType.getDisplayName() : "default"));
});
}
@DELETE
@Path("{id}/citationdate")
public Response useDefaultCitationDate( @PathParam("id") String id) {
return response( req -> {
execCommand(new SetDatasetCitationDateCommand(req, findDatasetOrDie(id), null));
return ok("Citation Date for dataset " + id + " set to default");
});
}
@GET
@Path("{id}/versions")
public Response listVersions( @PathParam("id") String id ) {
return allowCors(response( req ->
ok( execCommand( new ListVersionsCommand(req, findDatasetOrDie(id)) )
.stream()
.map( d -> json(d) )
.collect(toJsonArray()))));
}
@GET
@Path("{id}/versions/{versionId}")
public Response getVersion( @PathParam("id") String datasetId, @PathParam("versionId") String versionId) {
return allowCors(response( req -> {
DatasetVersion dsv = getDatasetVersionOrDie(req, versionId, findDatasetOrDie(datasetId));
return (dsv == null || dsv.getId() == null) ? notFound("Dataset version not found")
: ok(json(dsv));
}));
}
@GET
@Path("{id}/versions/{versionId}/files")
public Response getVersionFiles( @PathParam("id") String datasetId, @PathParam("versionId") String versionId) {
return allowCors(response( req -> ok( jsonFileMetadatas(
getDatasetVersionOrDie(req, versionId, findDatasetOrDie(datasetId)).getFileMetadatas()))));
}
@GET
@Path("{id}/versions/{versionId}/metadata")
public Response getVersionMetadata( @PathParam("id") String datasetId, @PathParam("versionId") String versionId) {
return allowCors(response( req -> ok(
jsonByBlocks(
getDatasetVersionOrDie(req, versionId, findDatasetOrDie(datasetId) )
.getDatasetFields()))));
}
@GET
@Path("{id}/versions/{versionNumber}/metadata/{block}")
public Response getVersionMetadataBlock( @PathParam("id") String datasetId,
@PathParam("versionNumber") String versionNumber,
@PathParam("block") String blockName ) {
return allowCors(response( req -> {
DatasetVersion dsv = getDatasetVersionOrDie(req, versionNumber, findDatasetOrDie(datasetId) );
Map<MetadataBlock, List<DatasetField>> fieldsByBlock = DatasetField.groupByBlock(dsv.getDatasetFields());
for ( Map.Entry<MetadataBlock, List<DatasetField>> p : fieldsByBlock.entrySet() ) {
if ( p.getKey().getName().equals(blockName) ) {
return ok(json(p.getKey(), p.getValue()));
}
}
return notFound("metadata block named " + blockName + " not found");
}));
}
@DELETE
@Path("{id}/versions/{versionId}")
public Response deleteDraftVersion( @PathParam("id") String id, @PathParam("versionId") String versionId ){
if ( ! ":draft".equals(versionId) ) {
return badRequest("Only the :draft version can be deleted");
}
return response( req -> {
execCommand( new DeleteDatasetVersionCommand(req, findDatasetOrDie(id)) );
return ok("Draft version of dataset " + id + " deleted");
});
}
@GET
@Path("{id}/modifyRegistration")
public Response updateDatasetTargetURL(@PathParam("id") String id ) {
return response( req -> {
execCommand(new UpdateDatasetTargetURLCommand(findDatasetOrDie(id), req));
return ok("Dataset " + id + " target url updated");
});
}
@GET
@Path("/modifyRegistrationAll")
public Response updateDatasetTargetURLAll() {
return response( req -> {
datasetService.findAll().forEach( ds -> {
try {
execCommand(new UpdateDatasetTargetURLCommand(findDatasetOrDie(ds.getId().toString()), req));
} catch (WrappedResponse ex) {
Logger.getLogger(Datasets.class.getName()).log(Level.SEVERE, null, ex);
}
});
return ok("Update All Dataset target url completed");
});
}
@PUT
@Path("{id}/versions/{versionId}")
public Response updateDraftVersion( String jsonBody, @PathParam("id") String id, @PathParam("versionId") String versionId ){
if ( ! ":draft".equals(versionId) ) {
return error( Response.Status.BAD_REQUEST, "Only the :draft version can be updated");
}
try ( StringReader rdr = new StringReader(jsonBody) ) {
DataverseRequest req = createDataverseRequest(findUserOrDie());
Dataset ds = findDatasetOrDie(id);
JsonObject json = Json.createReader(rdr).readObject();
DatasetVersion incomingVersion = jsonParser().parseDatasetVersion(json);
// clear possibly stale fields from the incoming dataset version.
// creation and modification dates are updated by the commands.
incomingVersion.setId(null);
incomingVersion.setVersionNumber(null);
incomingVersion.setMinorVersionNumber(null);
incomingVersion.setVersionState(DatasetVersion.VersionState.DRAFT);
incomingVersion.setDataset(ds);
incomingVersion.setCreateTime(null);
incomingVersion.setLastUpdateTime(null);
boolean updateDraft = ds.getLatestVersion().isDraft();
DatasetVersion managedVersion = execCommand( updateDraft
? new UpdateDatasetVersionCommand(req, incomingVersion)
: new CreateDatasetVersionCommand(req, ds, incomingVersion));
return ok( json(managedVersion) );
} catch (JsonParseException ex) {
logger.log(Level.SEVERE, "Semantic error parsing dataset version Json: " + ex.getMessage(), ex);
return error( Response.Status.BAD_REQUEST, "Error parsing dataset version: " + ex.getMessage() );
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@PUT
@Path("{id}/deleteMetadata")
public Response deleteVersionMetadata(String jsonBody, @PathParam("id") String id) throws WrappedResponse {
DataverseRequest req = createDataverseRequest(findUserOrDie());
return processDatasetFieldDataDelete(jsonBody, id, req);
}
private Response processDatasetFieldDataDelete(String jsonBody, String id, DataverseRequest req) {
try (StringReader rdr = new StringReader(jsonBody)) {
Dataset ds = findDatasetOrDie(id);
JsonObject json = Json.createReader(rdr).readObject();
DatasetVersion dsv = ds.getEditVersion();
List<DatasetField> fields = new LinkedList<>();
DatasetField singleField = null;
JsonArray fieldsJson = json.getJsonArray("fields");
if (fieldsJson == null) {
singleField = jsonParser().parseField(json, Boolean.FALSE);
fields.add(singleField);
} else {
fields = jsonParser().parseMultipleFields(json);
}
dsv.setVersionState(DatasetVersion.VersionState.DRAFT);
List<ControlledVocabularyValue> controlledVocabularyItemsToRemove = new ArrayList();
List<DatasetFieldValue> datasetFieldValueItemsToRemove = new ArrayList();
List<DatasetFieldCompoundValue> datasetFieldCompoundValueItemsToRemove = new ArrayList();
for (DatasetField updateField : fields) {
boolean found = false;
for (DatasetField dsf : dsv.getDatasetFields()) {
if (dsf.getDatasetFieldType().equals(updateField.getDatasetFieldType())) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
if (updateField.getDatasetFieldType().isControlledVocabulary()) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
for (ControlledVocabularyValue cvv : updateField.getControlledVocabularyValues()) {
for (ControlledVocabularyValue existing : dsf.getControlledVocabularyValues()) {
if (existing.getStrValue().equals(cvv.getStrValue())) {
found = true;
controlledVocabularyItemsToRemove.add(existing);
}
}
if (!found) {
logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + cvv.getStrValue() + " not found.");
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + cvv.getStrValue() + " not found.");
}
}
for (ControlledVocabularyValue remove : controlledVocabularyItemsToRemove) {
dsf.getControlledVocabularyValues().remove(remove);
}
} else {
if (dsf.getSingleControlledVocabularyValue().getStrValue().equals(updateField.getSingleControlledVocabularyValue().getStrValue())) {
found = true;
dsf.setSingleControlledVocabularyValue(null);
}
}
} else {
if (!updateField.getDatasetFieldType().isCompound()) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
for (DatasetFieldValue dfv : updateField.getDatasetFieldValues()) {
for (DatasetFieldValue edsfv : dsf.getDatasetFieldValues()) {
if (edsfv.getDisplayValue().equals(dfv.getDisplayValue())) {
found = true;
datasetFieldValueItemsToRemove.add(dfv);
}
}
if (!found) {
logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + dfv.getDisplayValue() + " not found.");
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + dfv.getDisplayValue() + " not found.");
}
}
datasetFieldValueItemsToRemove.forEach((remove) -> {
dsf.getDatasetFieldValues().remove(remove);
});
} else {
if (dsf.getSingleValue().getDisplayValue().equals(updateField.getSingleValue().getDisplayValue())) {
found = true;
dsf.setSingleValue(null);
}
}
} else {
for (DatasetFieldCompoundValue dfcv : updateField.getDatasetFieldCompoundValues()) {
String deleteVal = getCompoundDisplayValue(dfcv);
for (DatasetFieldCompoundValue existing : dsf.getDatasetFieldCompoundValues()) {
String existingString = getCompoundDisplayValue(existing);
if (existingString.equals(deleteVal)) {
found = true;
datasetFieldCompoundValueItemsToRemove.add(existing);
}
}
datasetFieldCompoundValueItemsToRemove.forEach((remove) -> {
dsf.getDatasetFieldCompoundValues().remove(remove);
});
if (!found) {
logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + deleteVal + " not found.");
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + deleteVal + " not found.");
}
}
}
}
} else {
found = true;
dsf.setSingleValue(null);
dsf.setSingleControlledVocabularyValue(null);
}
break;
}
}
if (!found){
String displayValue = !updateField.getDisplayValue().isEmpty() ? updateField.getDisplayValue() : updateField.getCompoundDisplayValue();
logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + displayValue + " not found." );
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + displayValue + " not found." );
}
}
boolean updateDraft = ds.getLatestVersion().isDraft();
DatasetVersion managedVersion = execCommand(updateDraft
? new UpdateDatasetVersionCommand(req, dsv)
: new CreateDatasetVersionCommand(req, ds, dsv));
return ok(json(managedVersion));
} catch (JsonParseException ex) {
logger.log(Level.SEVERE, "Semantic error parsing dataset update Json: " + ex.getMessage(), ex);
return error(Response.Status.BAD_REQUEST, "Error processing metadata delete: " + ex.getMessage());
} catch (WrappedResponse ex) {
logger.log(Level.SEVERE, "Delete metadata error: " + ex.getMessage(), ex);
return ex.getResponse();
}
}
private String getCompoundDisplayValue (DatasetFieldCompoundValue dscv){
String returnString = "";
for (DatasetField dsf : dscv.getChildDatasetFields()) {
for (String value : dsf.getValues()) {
if (!(value == null)) {
returnString += (returnString.isEmpty() ? "" : "; ") + value.trim();
}
}
}
return returnString;
}
@PUT
@Path("{id}/editMetadata")
public Response editVersionMetadata(String jsonBody, @PathParam("id") String id, @QueryParam("replace") Boolean replace) throws WrappedResponse{
Boolean replaceData = replace != null;
DataverseRequest req = createDataverseRequest(findUserOrDie());
return processDatasetUpdate(jsonBody, id, req, replaceData);
}
private Response processDatasetUpdate(String jsonBody, String id, DataverseRequest req, Boolean replaceData){
try (StringReader rdr = new StringReader(jsonBody)) {
Dataset ds = findDatasetOrDie(id);
JsonObject json = Json.createReader(rdr).readObject();
DatasetVersion dsv = ds.getEditVersion();
List<DatasetField> fields = new LinkedList<>();
DatasetField singleField = null;
JsonArray fieldsJson = json.getJsonArray("fields");
if( fieldsJson == null ){
singleField = jsonParser().parseField(json, Boolean.FALSE);
fields.add(singleField);
} else{
fields = jsonParser().parseMultipleFields(json);
}
validateDatasetFieldValues(fields);
dsv.setVersionState(DatasetVersion.VersionState.DRAFT);
//loop through the update fields
// and compare to the version fields
//if exist add/replace values
//if not add entire dsf
for (DatasetField updateField : fields) {
boolean found = false;
for (DatasetField dsf : dsv.getDatasetFields()) {
if (dsf.getDatasetFieldType().equals(updateField.getDatasetFieldType())) {
found = true;
if (dsf.isEmpty() || dsf.getDatasetFieldType().isAllowMultiples() || replaceData ) {
if(replaceData){
if(dsf.getDatasetFieldType().isAllowMultiples()){
dsf.setDatasetFieldCompoundValues(new ArrayList());
dsf.setDatasetFieldValues(new ArrayList());
dsf.getControlledVocabularyValues().clear();
} else {
dsf.setSingleValue("");
dsf.setSingleControlledVocabularyValue(null);
}
}
if (updateField.getDatasetFieldType().isControlledVocabulary()) {
if (dsf.getDatasetFieldType().isAllowMultiples()){
for (ControlledVocabularyValue cvv : updateField.getControlledVocabularyValues()) {
if (!dsf.getDisplayValue().contains(cvv.getStrValue())) {
dsf.getControlledVocabularyValues().add(cvv);
}
}
} else {
dsf.setSingleControlledVocabularyValue(updateField.getSingleControlledVocabularyValue());
}
} else {
if (!updateField.getDatasetFieldType().isCompound()) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
for (DatasetFieldValue dfv : updateField.getDatasetFieldValues()) {
if (!dsf.getDisplayValue().contains(dfv.getDisplayValue())) {
dfv.setDatasetField(dsf);
dsf.getDatasetFieldValues().add(dfv);
}
}
} else {
dsf.setSingleValue(updateField.getValue());
}
} else {
for (DatasetFieldCompoundValue dfcv : updateField.getDatasetFieldCompoundValues()) {
if (!dsf.getCompoundDisplayValue().contains(updateField.getCompoundDisplayValue())) {
dfcv.setParentDatasetField(dsf);
dsf.setDatasetVersion(dsv);
dsf.getDatasetFieldCompoundValues().add(dfcv);
}
}
}
}
} else {
if (!dsf.isEmpty() && !dsf.getDatasetFieldType().isAllowMultiples() || !replaceData) {
return error(Response.Status.BAD_REQUEST, "You may not add data to a field that already has data and does not allow multiples. Use replace=true to replace existing data (" + dsf.getDatasetFieldType().getDisplayName() + ")" );
}
}
break;
}
}
if(!found){
updateField.setDatasetVersion(dsv);
dsv.getDatasetFields().add(updateField);
}
}
boolean updateDraft = ds.getLatestVersion().isDraft();
DatasetVersion managedVersion = execCommand(updateDraft
? new UpdateDatasetVersionCommand(req, dsv)
: new CreateDatasetVersionCommand(req, ds, dsv));
return ok(json(managedVersion));
} catch (JsonParseException ex) {
logger.log(Level.SEVERE, "Semantic error parsing dataset update Json: " + ex.getMessage(), ex);
return error(Response.Status.BAD_REQUEST, "Error parsing dataset update: " + ex.getMessage());
} catch (WrappedResponse ex) {
logger.log(Level.SEVERE, "Update metdata error: " + ex.getMessage(), ex);
return ex.getResponse();
}
}
private void validateDatasetFieldValues(List<DatasetField> fields) throws JsonParseException {
StringBuilder error = new StringBuilder();
for (DatasetField dsf : fields) {
if (dsf.getDatasetFieldType().isAllowMultiples() && dsf.getControlledVocabularyValues().isEmpty()
&& dsf.getDatasetFieldCompoundValues().isEmpty() && dsf.getDatasetFieldValues().isEmpty()) {
error.append("Empty multiple value for field ").append(dsf.getDatasetFieldType().getDisplayName()).append(" ");
} else if (!dsf.getDatasetFieldType().isAllowMultiples() && dsf.getSingleValue().getValue().isEmpty()) {
error.append("Empty value for field ").append(dsf.getDatasetFieldType().getDisplayName()).append(" ");
}
}
if (!error.toString().isEmpty()) {
throw new JsonParseException(error.toString());
}
}
/**
* @deprecated This was shipped as a GET but should have been a POST, see https://github.com/IQSS/dataverse/issues/2431
*/
@GET
@Path("{id}/actions/:publish")
@Deprecated
public Response publishDataseUsingGetDeprecated( @PathParam("id") String id, @QueryParam("type") String type ) {
logger.info("publishDataseUsingGetDeprecated called on id " + id + ". Encourage use of POST rather than GET, which is deprecated.");
return publishDataset(id, type);
}
@POST
@Path("{id}/actions/:publish")
public Response publishDataset(@PathParam("id") String id, @QueryParam("type") String type) {
try {
if (type == null) {
return error(Response.Status.BAD_REQUEST, "Missing 'type' parameter (either 'major' or 'minor').");
}
type = type.toLowerCase();
boolean isMinor;
switch (type) {
case "minor":
isMinor = true;
break;
case "major":
isMinor = false;
break;
default:
return error(Response.Status.BAD_REQUEST, "Illegal 'type' parameter value '" + type + "'. It needs to be either 'major' or 'minor'.");
}
Dataset ds = findDatasetOrDie(id);
PublishDatasetResult res = execCommand(new PublishDatasetCommand(ds,
createDataverseRequest(findAuthenticatedUserOrDie()),
isMinor));
return res.isCompleted() ? ok(json(res.getDataset())) : accepted(json(res.getDataset()));
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@POST
@Path("{id}/move/{targetDataverseAlias}")
public Response moveDataset(@PathParam("id") String id, @PathParam("targetDataverseAlias") String targetDataverseAlias, @QueryParam("forceMove") Boolean force) {
try{
User u = findUserOrDie();
Dataset ds = findDatasetOrDie(id);
Dataverse target = dataverseService.findByAlias(targetDataverseAlias);
if (target == null){
return error(Response.Status.BAD_REQUEST, "Target Dataverse not found.");
}
//Command requires Super user - it will be tested by the command
execCommand(new MoveDatasetCommand(
createDataverseRequest(u), ds, target, force
));
return ok("Dataset moved successfully");
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@PUT
@Path("{linkedDatasetId}/link/{linkingDataverseAlias}")
public Response linkDataset(@PathParam("linkedDatasetId") String linkedDatasetId, @PathParam("linkingDataverseAlias") String linkingDataverseAlias) {
try{
User u = findUserOrDie();
Dataset linked = findDatasetOrDie(linkedDatasetId);
Dataverse linking = findDataverseOrDie(linkingDataverseAlias);
if (linked == null){
return error(Response.Status.BAD_REQUEST, "Linked Dataset not found.");
}
if (linking == null){
return error(Response.Status.BAD_REQUEST, "Linking Dataverse not found.");
}
execCommand(new LinkDatasetCommand(
createDataverseRequest(u), linking, linked
));
return ok("Dataset " + linked.getId() + " linked successfully to " + linking.getAlias());
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@GET
@Path("{id}/links")
public Response getLinks(@PathParam("id") String idSupplied ) {
try {
User u = findUserOrDie();
if (!u.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Not a superuser");
}
Dataset dataset = findDatasetOrDie(idSupplied);
long datasetId = dataset.getId();
List<Dataverse> dvsThatLinkToThisDatasetId = dataverseSvc.findDataversesThatLinkToThisDatasetId(datasetId);
JsonArrayBuilder dataversesThatLinkToThisDatasetIdBuilder = Json.createArrayBuilder();
for (Dataverse dataverse : dvsThatLinkToThisDatasetId) {
dataversesThatLinkToThisDatasetIdBuilder.add(dataverse.getAlias() + " (id " + dataverse.getId() + ")");
}
JsonObjectBuilder response = Json.createObjectBuilder();
response.add("dataverses that link to dataset id " + datasetId, dataversesThatLinkToThisDatasetIdBuilder);
return ok(response);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
/**
* @todo Make this real. Currently only used for API testing. Copied from
* the equivalent API endpoint for dataverses and simplified with values
* hard coded.
*/
@POST
@Path("{identifier}/assignments")
public Response createAssignment(String userOrGroup, @PathParam("identifier") String id, @QueryParam("key") String apiKey) {
boolean apiTestingOnly = true;
if (apiTestingOnly) {
return error(Response.Status.FORBIDDEN, "This is only for API tests.");
}
try {
Dataset dataset = findDatasetOrDie(id);
RoleAssignee assignee = findAssignee(userOrGroup);
if (assignee == null) {
return error(Response.Status.BAD_REQUEST, "Assignee not found");
}
DataverseRole theRole = rolesSvc.findBuiltinRoleByAlias("admin");
String privateUrlToken = null;
return ok(
json(execCommand(new AssignRoleCommand(assignee, theRole, dataset, createDataverseRequest(findUserOrDie()), privateUrlToken))));
} catch (WrappedResponse ex) {
logger.log(Level.WARNING, "Can''t create assignment: {0}", ex.getMessage());
return ex.getResponse();
}
}
@GET
@Path("{identifier}/assignments")
public Response getAssignments(@PathParam("identifier") String id) {
return response( req ->
ok( execCommand(
new ListRoleAssignments(req, findDatasetOrDie(id)))
.stream().map(ra->json(ra)).collect(toJsonArray())) );
}
@GET
@Path("{id}/privateUrl")
public Response getPrivateUrlData(@PathParam("id") String idSupplied) {
return response( req -> {
PrivateUrl privateUrl = execCommand(new GetPrivateUrlCommand(req, findDatasetOrDie(idSupplied)));
return (privateUrl != null) ? ok(json(privateUrl))
: error(Response.Status.NOT_FOUND, "Private URL not found.");
});
}
@POST
@Path("{id}/privateUrl")
public Response createPrivateUrl(@PathParam("id") String idSupplied) {
return response( req ->
ok(json(execCommand(
new CreatePrivateUrlCommand(req, findDatasetOrDie(idSupplied))))));
}
@DELETE
@Path("{id}/privateUrl")
public Response deletePrivateUrl(@PathParam("id") String idSupplied) {
return response( req -> {
Dataset dataset = findDatasetOrDie(idSupplied);
PrivateUrl privateUrl = execCommand(new GetPrivateUrlCommand(req, dataset));
if (privateUrl != null) {
execCommand(new DeletePrivateUrlCommand(req, dataset));
return ok("Private URL deleted.");
} else {
return notFound("No Private URL to delete.");
}
});
}
@GET
@Path("{id}/thumbnail/candidates")
public Response getDatasetThumbnailCandidates(@PathParam("id") String idSupplied) {
try {
Dataset dataset = findDatasetOrDie(idSupplied);
boolean canUpdateThumbnail = false;
try {
canUpdateThumbnail = permissionSvc.requestOn(createDataverseRequest(findUserOrDie()), dataset).canIssue(UpdateDatasetThumbnailCommand.class);
} catch (WrappedResponse ex) {
logger.info("Exception thrown while trying to figure out permissions while getting thumbnail for dataset id " + dataset.getId() + ": " + ex.getLocalizedMessage());
}
if (!canUpdateThumbnail) {
return error(Response.Status.FORBIDDEN, "You are not permitted to list dataset thumbnail candidates.");
}
JsonArrayBuilder data = Json.createArrayBuilder();
boolean considerDatasetLogoAsCandidate = true;
for (DatasetThumbnail datasetThumbnail : DatasetUtil.getThumbnailCandidates(dataset, considerDatasetLogoAsCandidate)) {
JsonObjectBuilder candidate = Json.createObjectBuilder();
String base64image = datasetThumbnail.getBase64image();
if (base64image != null) {
logger.fine("found a candidate!");
candidate.add("base64image", base64image);
}
DataFile dataFile = datasetThumbnail.getDataFile();
if (dataFile != null) {
candidate.add("dataFileId", dataFile.getId());
}
data.add(candidate);
}
return ok(data);
} catch (WrappedResponse ex) {
return error(Response.Status.NOT_FOUND, "Could not find dataset based on id supplied: " + idSupplied + ".");
}
}
@GET
@Produces({"image/png"})
@Path("{id}/thumbnail")
public InputStream getDatasetThumbnail(@PathParam("id") String idSupplied) {
try {
Dataset dataset = findDatasetOrDie(idSupplied);
return DatasetUtil.getThumbnailAsInputStream(dataset);
} catch (WrappedResponse ex) {
return null;
}
}
// TODO: Rather than only supporting looking up files by their database IDs (dataFileIdSupplied), consider supporting persistent identifiers.
@POST
@Path("{id}/thumbnail/{dataFileId}")
public Response setDataFileAsThumbnail(@PathParam("id") String idSupplied, @PathParam("dataFileId") long dataFileIdSupplied) {
try {
DatasetThumbnail datasetThumbnail = execCommand(new UpdateDatasetThumbnailCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied), UpdateDatasetThumbnailCommand.UserIntent.setDatasetFileAsThumbnail, dataFileIdSupplied, null));
return ok("Thumbnail set to " + datasetThumbnail.getBase64image());
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@POST
@Path("{id}/thumbnail")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadDatasetLogo(@PathParam("id") String idSupplied, @FormDataParam("file") InputStream inputStream
) {
try {
DatasetThumbnail datasetThumbnail = execCommand(new UpdateDatasetThumbnailCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied), UpdateDatasetThumbnailCommand.UserIntent.setNonDatasetFileAsThumbnail, null, inputStream));
return ok("Thumbnail is now " + datasetThumbnail.getBase64image());
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@DELETE
@Path("{id}/thumbnail")
public Response removeDatasetLogo(@PathParam("id") String idSupplied) {
try {
DatasetThumbnail datasetThumbnail = execCommand(new UpdateDatasetThumbnailCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied), UpdateDatasetThumbnailCommand.UserIntent.removeThumbnail, null, null));
return ok("Dataset thumbnail removed.");
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@GET
@Path("{identifier}/dataCaptureModule/rsync")
public Response getRsync(@PathParam("identifier") String id) {
//TODO - does it make sense to switch this to dataset identifier for consistency with the rest of the DCM APIs?
if (!DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
return error(Response.Status.METHOD_NOT_ALLOWED, SettingsServiceBean.Key.UploadMethods + " does not contain " + SystemConfig.FileUploadMethods.RSYNC + ".");
}
Dataset dataset = null;
try {
dataset = findDatasetOrDie(id);
AuthenticatedUser user = findAuthenticatedUserOrDie();
ScriptRequestResponse scriptRequestResponse = execCommand(new RequestRsyncScriptCommand(createDataverseRequest(user), dataset));
DatasetLock lock = datasetService.addDatasetLock(dataset.getId(), DatasetLock.Reason.DcmUpload, user.getId(), "script downloaded");
if (lock == null) {
logger.log(Level.WARNING, "Failed to lock the dataset (dataset id={0})", dataset.getId());
return error(Response.Status.FORBIDDEN, "Failed to lock the dataset (dataset id="+dataset.getId()+")");
}
return ok(scriptRequestResponse.getScript(), MediaType.valueOf(MediaType.TEXT_PLAIN));
} catch (WrappedResponse wr) {
return wr.getResponse();
} catch (EJBException ex) {
return error(Response.Status.INTERNAL_SERVER_ERROR, "Something went wrong attempting to download rsync script: " + EjbUtil.ejbExceptionToString(ex));
}
}
@POST
@Path("{identifier}/dataCaptureModule/checksumValidation")
public Response receiveChecksumValidationResults(@PathParam("identifier") String id, JsonObject jsonFromDcm) {
logger.log(Level.FINE, "jsonFromDcm: {0}", jsonFromDcm);
AuthenticatedUser authenticatedUser = null;
try {
authenticatedUser = findAuthenticatedUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.BAD_REQUEST, "Authentication is required.");
}
if (!authenticatedUser.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
String statusMessageFromDcm = jsonFromDcm.getString("status");
try {
Dataset dataset = findDatasetOrDie(id);
if ("validation passed".equals(statusMessageFromDcm)) {
String uploadFolder = jsonFromDcm.getString("uploadFolder");
int totalSize = jsonFromDcm.getInt("totalSize");
ImportMode importMode = ImportMode.MERGE;
try {
JsonObject jsonFromImportJobKickoff = execCommand(new ImportFromFileSystemCommand(createDataverseRequest(findUserOrDie()), dataset, uploadFolder, new Long(totalSize), importMode));
long jobId = jsonFromImportJobKickoff.getInt("executionId");
String message = jsonFromImportJobKickoff.getString("message");
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("jobId", jobId);
job.add("message", message);
return ok(job);
} catch (WrappedResponse wr) {
String message = wr.getMessage();
return error(Response.Status.INTERNAL_SERVER_ERROR, "Uploaded files have passed checksum validation but something went wrong while attempting to put the files into Dataverse. Message was '" + message + "'.");
}
} else if ("validation failed".equals(statusMessageFromDcm)) {
Map<String, AuthenticatedUser> distinctAuthors = permissionService.getDistinctUsersWithPermissionOn(Permission.EditDataset, dataset);
distinctAuthors.values().forEach((value) -> {
userNotificationService.sendNotification((AuthenticatedUser) value, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
List<AuthenticatedUser> superUsers = authenticationServiceBean.findSuperUsers();
if (superUsers != null && !superUsers.isEmpty()) {
superUsers.forEach((au) -> {
userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
}
return ok("User notified about checksum validation failure.");
} else {
return error(Response.Status.BAD_REQUEST, "Unexpected status cannot be processed: " + statusMessageFromDcm);
}
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@POST
@Path("{id}/submitForReview")
public Response submitForReview(@PathParam("id") String idSupplied) {
try {
Dataset updatedDataset = execCommand(new SubmitDatasetForReviewCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied)));
JsonObjectBuilder result = Json.createObjectBuilder();
boolean inReview = updatedDataset.isLockedFor(DatasetLock.Reason.InReview);
result.add("inReview", inReview);
result.add("message", "Dataset id " + updatedDataset.getId() + " has been submitted for review.");
return ok(result);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@POST
@Path("{id}/returnToAuthor")
public Response returnToAuthor(@PathParam("id") String idSupplied, String jsonBody) {
if (jsonBody == null || jsonBody.isEmpty()) {
return error(Response.Status.BAD_REQUEST, "You must supply JSON to this API endpoint and it must contain a reason for returning the dataset.");
}
StringReader rdr = new StringReader(jsonBody);
JsonObject json = Json.createReader(rdr).readObject();
try {
Dataset dataset = findDatasetOrDie(idSupplied);
String reasonForReturn = null;
reasonForReturn = json.getString("reasonForReturn");
// TODO: Once we add a box for the curator to type into, pass the reason for return to the ReturnDatasetToAuthorCommand and delete this check and call to setReturnReason on the API side.
if (reasonForReturn == null || reasonForReturn.isEmpty()) {
return error(Response.Status.BAD_REQUEST, "You must enter a reason for returning a dataset to the author(s).");
}
AuthenticatedUser authenticatedUser = findAuthenticatedUserOrDie();
Dataset updatedDataset = execCommand(new ReturnDatasetToAuthorCommand(createDataverseRequest(authenticatedUser), dataset, reasonForReturn ));
boolean inReview = updatedDataset.isLockedFor(DatasetLock.Reason.InReview);
JsonObjectBuilder result = Json.createObjectBuilder();
result.add("inReview", inReview);
result.add("message", "Dataset id " + updatedDataset.getId() + " has been sent back to the author(s).");
return ok(result);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
/**
* Add a File to an existing Dataset
*
* @param idSupplied
* @param jsonData
* @param fileInputStream
* @param contentDispositionHeader
* @param formDataBodyPart
* @return
*/
@POST
@Path("{id}/add")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response addFileToDataset(@PathParam("id") String idSupplied,
@FormDataParam("jsonData") String jsonData,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
@FormDataParam("file") final FormDataBodyPart formDataBodyPart
){
// -------------------------------------
// (1) Get the user from the API key
// -------------------------------------
User authUser;
try {
authUser = findUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN,
ResourceBundle.getBundle("Bundle").getString("file.addreplace.error.auth")
);
}
//---------------------------------------
// (1A) Make sure that the upload type is not rsync
// -------------------------------------
if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
return error(Response.Status.METHOD_NOT_ALLOWED, SettingsServiceBean.Key.UploadMethods + " contains " + SystemConfig.FileUploadMethods.RSYNC + ". Please use rsync file upload.");
}
// -------------------------------------
// (2) Get the Dataset Id
//
// -------------------------------------
Dataset dataset;
Long datasetId;
try {
dataset = findDatasetOrDie(idSupplied);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
// -------------------------------------
// (3) Get the file name and content type
// -------------------------------------
String newFilename = contentDispositionHeader.getFileName();
String newFileContentType = formDataBodyPart.getMediaType().toString();
// (2a) Load up optional params via JSON
//---------------------------------------
OptionalFileParams optionalFileParams = null;
msgt("(api) jsonData: " + jsonData);
try {
optionalFileParams = new OptionalFileParams(jsonData);
} catch (DataFileTagException ex) {
return error( Response.Status.BAD_REQUEST, ex.getMessage());
}
//-------------------
// (3) Create the AddReplaceFileHelper object
//-------------------
msg("ADD!");
DataverseRequest dvRequest2 = createDataverseRequest(authUser);
AddReplaceFileHelper addFileHelper = new AddReplaceFileHelper(dvRequest2,
ingestService,
datasetService,
fileService,
permissionSvc,
commandEngine,
systemConfig);
//-------------------
// (4) Run "runAddFileByDatasetId"
//-------------------
addFileHelper.runAddFileByDataset(dataset,
newFilename,
newFileContentType,
fileInputStream,
optionalFileParams);
if (addFileHelper.hasError()){
return error(addFileHelper.getHttpErrorCode(), addFileHelper.getErrorMessagesAsString("\n"));
}else{
String successMsg = ResourceBundle.getBundle("Bundle").getString("file.addreplace.success.add");
try {
//msgt("as String: " + addFileHelper.getSuccessResult());
/**
* @todo We need a consistent, sane way to communicate a human
* readable message to an API client suitable for human
* consumption. Imagine if the UI were built in Angular or React
* and we want to return a message from the API as-is to the
* user. Human readable.
*/
logger.fine("successMsg: " + successMsg);
return ok(addFileHelper.getSuccessResultAsJsonObjectBuilder());
//"Look at that! You added a file! (hey hey, it may have worked)");
} catch (NoFilesException ex) {
Logger.getLogger(Files.class.getName()).log(Level.SEVERE, null, ex);
return error(Response.Status.BAD_REQUEST, "NoFileException! Serious Error! See administrator!");
}
}
} // end: addFileToDataset
private void msg(String m){
//System.out.println(m);
logger.fine(m);
}
private void dashes(){
msg("----------------");
}
private void msgt(String m){
dashes(); msg(m); dashes();
}
private <T> T handleVersion( String versionId, DsVersionHandler<T> hdl )
throws WrappedResponse {
switch (versionId) {
case ":latest": return hdl.handleLatest();
case ":draft": return hdl.handleDraft();
case ":latest-published": return hdl.handleLatestPublished();
default:
try {
String[] versions = versionId.split("\\.");
switch (versions.length) {
case 1:
return hdl.handleSpecific(Long.parseLong(versions[0]), (long)0.0);
case 2:
return hdl.handleSpecific( Long.parseLong(versions[0]), Long.parseLong(versions[1]) );
default:
throw new WrappedResponse(error( Response.Status.BAD_REQUEST, "Illegal version identifier '" + versionId + "'"));
}
} catch ( NumberFormatException nfe ) {
throw new WrappedResponse( error( Response.Status.BAD_REQUEST, "Illegal version identifier '" + versionId + "'") );
}
}
}
private DatasetVersion getDatasetVersionOrDie( final DataverseRequest req, String versionNumber, final Dataset ds ) throws WrappedResponse {
DatasetVersion dsv = execCommand( handleVersion(versionNumber, new DsVersionHandler<Command<DatasetVersion>>(){
@Override
public Command<DatasetVersion> handleLatest() {
return new GetLatestAccessibleDatasetVersionCommand(req, ds);
}
@Override
public Command<DatasetVersion> handleDraft() {
return new GetDraftDatasetVersionCommand(req, ds);
}
@Override
public Command<DatasetVersion> handleSpecific(long major, long minor) {
return new GetSpecificPublishedDatasetVersionCommand(req, ds, major, minor);
}
@Override
public Command<DatasetVersion> handleLatestPublished() {
return new GetLatestPublishedDatasetVersionCommand(req, ds);
}
}));
if ( dsv == null || dsv.getId() == null ) {
throw new WrappedResponse( notFound("Dataset version " + versionNumber + " of dataset " + ds.getId() + " not found") );
}
return dsv;
}
}
| src/main/java/edu/harvard/iq/dataverse/api/Datasets.java | package edu.harvard.iq.dataverse.api;
import edu.harvard.iq.dataverse.ControlledVocabularyValue;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.DataFileServiceBean;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DatasetField;
import edu.harvard.iq.dataverse.DatasetFieldCompoundValue;
import edu.harvard.iq.dataverse.DatasetFieldServiceBean;
import edu.harvard.iq.dataverse.DatasetFieldType;
import edu.harvard.iq.dataverse.DatasetFieldValue;
import edu.harvard.iq.dataverse.DatasetLock;
import edu.harvard.iq.dataverse.DatasetServiceBean;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.Dataverse;
import edu.harvard.iq.dataverse.DataverseServiceBean;
import edu.harvard.iq.dataverse.DataverseSession;
import edu.harvard.iq.dataverse.EjbDataverseEngine;
import edu.harvard.iq.dataverse.MetadataBlock;
import edu.harvard.iq.dataverse.MetadataBlockServiceBean;
import edu.harvard.iq.dataverse.PermissionServiceBean;
import edu.harvard.iq.dataverse.UserNotification;
import edu.harvard.iq.dataverse.UserNotificationServiceBean;
import static edu.harvard.iq.dataverse.api.AbstractApiBean.error;
import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;
import edu.harvard.iq.dataverse.authorization.DataverseRole;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.RoleAssignee;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.batch.jobs.importer.ImportMode;
import edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleException;
import edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleUtil;
import edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse;
import edu.harvard.iq.dataverse.dataset.DatasetThumbnail;
import edu.harvard.iq.dataverse.dataset.DatasetUtil;
import edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper;
import edu.harvard.iq.dataverse.datasetutility.DataFileTagException;
import edu.harvard.iq.dataverse.datasetutility.NoFilesException;
import edu.harvard.iq.dataverse.datasetutility.OptionalFileParams;
import edu.harvard.iq.dataverse.engine.command.Command;
import edu.harvard.iq.dataverse.engine.command.DataverseRequest;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand;
import edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.CreatePrivateUrlCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetLinkingDataverseCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DeletePrivateUrlCommand;
import edu.harvard.iq.dataverse.engine.command.impl.DestroyDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetSpecificPublishedDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetLatestAccessibleDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetLatestPublishedDatasetVersionCommand;
import edu.harvard.iq.dataverse.engine.command.impl.GetPrivateUrlCommand;
import edu.harvard.iq.dataverse.engine.command.impl.ImportFromFileSystemCommand;
import edu.harvard.iq.dataverse.engine.command.impl.LinkDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.ListRoleAssignments;
import edu.harvard.iq.dataverse.engine.command.impl.ListVersionsCommand;
import edu.harvard.iq.dataverse.engine.command.impl.MoveDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.PublishDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.PublishDatasetResult;
import edu.harvard.iq.dataverse.engine.command.impl.RequestRsyncScriptCommand;
import edu.harvard.iq.dataverse.engine.command.impl.ReturnDatasetToAuthorCommand;
import edu.harvard.iq.dataverse.engine.command.impl.SetDatasetCitationDateCommand;
import edu.harvard.iq.dataverse.engine.command.impl.SubmitDatasetForReviewCommand;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetTargetURLCommand;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetThumbnailCommand;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetVersionCommand;
import edu.harvard.iq.dataverse.export.DDIExportServiceBean;
import edu.harvard.iq.dataverse.export.ExportService;
import edu.harvard.iq.dataverse.ingest.IngestServiceBean;
import edu.harvard.iq.dataverse.privateurl.PrivateUrl;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import edu.harvard.iq.dataverse.util.EjbUtil;
import edu.harvard.iq.dataverse.util.SystemConfig;
import edu.harvard.iq.dataverse.util.json.JsonParseException;
import static edu.harvard.iq.dataverse.util.json.JsonPrinter.*;
import edu.harvard.iq.dataverse.workflow.Workflow;
import edu.harvard.iq.dataverse.workflow.WorkflowContext;
import edu.harvard.iq.dataverse.workflow.WorkflowServiceBean;
import java.io.InputStream;
import java.io.StringReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
@Path("datasets")
public class Datasets extends AbstractApiBean {
private static final Logger logger = Logger.getLogger(Datasets.class.getCanonicalName());
@Inject DataverseSession session;
@EJB
DatasetServiceBean datasetService;
@EJB
DataverseServiceBean dataverseService;
@EJB
UserNotificationServiceBean userNotificationService;
@EJB
PermissionServiceBean permissionService;
@EJB
AuthenticationServiceBean authenticationServiceBean;
@EJB
DDIExportServiceBean ddiExportService;
@EJB
DatasetFieldServiceBean datasetfieldService;
@EJB
MetadataBlockServiceBean metadataBlockService;
@EJB
DataFileServiceBean fileService;
@EJB
IngestServiceBean ingestService;
@EJB
EjbDataverseEngine commandEngine;
/**
* Used to consolidate the way we parse and handle dataset versions.
* @param <T>
*/
private interface DsVersionHandler<T> {
T handleLatest();
T handleDraft();
T handleSpecific( long major, long minor );
T handleLatestPublished();
}
@GET
@Path("{id}")
public Response getDataset(@PathParam("id") String id) {
return response( req -> {
final Dataset retrieved = execCommand(new GetDatasetCommand(req, findDatasetOrDie(id)));
final DatasetVersion latest = execCommand(new GetLatestAccessibleDatasetVersionCommand(req, retrieved));
final JsonObjectBuilder jsonbuilder = json(retrieved);
return allowCors(ok(jsonbuilder.add("latestVersion", (latest != null) ? json(latest) : null)));
});
}
// TODO:
// This API call should, ideally, call findUserOrDie() and the GetDatasetCommand
// to obtain the dataset that we are trying to export - which would handle
// Auth in the process... For now, Auth isn't necessary - since export ONLY
// WORKS on published datasets, which are open to the world. -- L.A. 4.5
@GET
@Path("/export")
@Produces({"application/xml", "application/json"})
public Response exportDataset(@QueryParam("persistentId") String persistentId, @QueryParam("exporter") String exporter) {
try {
Dataset dataset = datasetService.findByGlobalId(persistentId);
if (dataset == null) {
return error(Response.Status.NOT_FOUND, "A dataset with the persistentId " + persistentId + " could not be found.");
}
ExportService instance = ExportService.getInstance(settingsSvc);
String xml = instance.getExportAsString(dataset, exporter);
// I'm wondering if this going to become a performance problem
// with really GIANT datasets,
// the fact that we are passing these exports, blobs of JSON, and,
// especially, DDI XML as complete strings. It would be nicer
// if we could stream instead - and the export service already can
// give it to as as a stream; then we could start sending the
// output to the remote client as soon as we got the first bytes,
// without waiting for the whole thing to be generated and buffered...
// (the way Access API streams its output).
// -- L.A., 4.5
logger.fine("xml to return: " + xml);
String mediaType = MediaType.TEXT_PLAIN;//PM - output formats appear to be either JSON or XML, unclear why text/plain is being used as default content-type.
if (instance.isXMLFormat(exporter)){
mediaType = MediaType.APPLICATION_XML;
}
return allowCors(Response.ok()
.entity(xml)
.type(mediaType).
build());
} catch (Exception wr) {
return error(Response.Status.FORBIDDEN, "Export Failed");
}
}
@DELETE
@Path("{id}")
public Response deleteDataset( @PathParam("id") String id) {
return response( req -> {
execCommand( new DeleteDatasetCommand(req, findDatasetOrDie(id)));
return ok("Dataset " + id + " deleted");
});
}
@DELETE
@Path("{id}/destroy")
public Response destroyDataset( @PathParam("id") String id) {
return response( req -> {
execCommand( new DestroyDatasetCommand(findDatasetOrDie(id), req) );
return ok("Dataset " + id + " destroyed");
});
}
@DELETE
@Path("{datasetId}/deleteLink/{linkedDataverseId}")
public Response deleteDatasetLinkingDataverse( @PathParam("datasetId") String datasetId, @PathParam("linkedDataverseId") String linkedDataverseId) {
boolean index = true;
return response(req -> {
execCommand(new DeleteDatasetLinkingDataverseCommand(req, findDatasetOrDie(datasetId), findDatasetLinkingDataverseOrDie(datasetId, linkedDataverseId), index));
return ok("Link from Dataset " + datasetId + " to linked Dataverse " + linkedDataverseId + " deleted");
});
}
@PUT
@Path("{id}/citationdate")
public Response setCitationDate( @PathParam("id") String id, String dsfTypeName) {
return response( req -> {
if ( dsfTypeName.trim().isEmpty() ){
return badRequest("Please provide a dataset field type in the requst body.");
}
DatasetFieldType dsfType = null;
if (!":publicationDate".equals(dsfTypeName)) {
dsfType = datasetFieldSvc.findByName(dsfTypeName);
if (dsfType == null) {
return badRequest("Dataset Field Type Name " + dsfTypeName + " not found.");
}
}
execCommand(new SetDatasetCitationDateCommand(req, findDatasetOrDie(id), dsfType));
return ok("Citation Date for dataset " + id + " set to: " + (dsfType != null ? dsfType.getDisplayName() : "default"));
});
}
@DELETE
@Path("{id}/citationdate")
public Response useDefaultCitationDate( @PathParam("id") String id) {
return response( req -> {
execCommand(new SetDatasetCitationDateCommand(req, findDatasetOrDie(id), null));
return ok("Citation Date for dataset " + id + " set to default");
});
}
@GET
@Path("{id}/versions")
public Response listVersions( @PathParam("id") String id ) {
return allowCors(response( req ->
ok( execCommand( new ListVersionsCommand(req, findDatasetOrDie(id)) )
.stream()
.map( d -> json(d) )
.collect(toJsonArray()))));
}
@GET
@Path("{id}/versions/{versionId}")
public Response getVersion( @PathParam("id") String datasetId, @PathParam("versionId") String versionId) {
return allowCors(response( req -> {
DatasetVersion dsv = getDatasetVersionOrDie(req, versionId, findDatasetOrDie(datasetId));
return (dsv == null || dsv.getId() == null) ? notFound("Dataset version not found")
: ok(json(dsv));
}));
}
@GET
@Path("{id}/versions/{versionId}/files")
public Response getVersionFiles( @PathParam("id") String datasetId, @PathParam("versionId") String versionId) {
return allowCors(response( req -> ok( jsonFileMetadatas(
getDatasetVersionOrDie(req, versionId, findDatasetOrDie(datasetId)).getFileMetadatas()))));
}
@GET
@Path("{id}/versions/{versionId}/metadata")
public Response getVersionMetadata( @PathParam("id") String datasetId, @PathParam("versionId") String versionId) {
return allowCors(response( req -> ok(
jsonByBlocks(
getDatasetVersionOrDie(req, versionId, findDatasetOrDie(datasetId) )
.getDatasetFields()))));
}
@GET
@Path("{id}/versions/{versionNumber}/metadata/{block}")
public Response getVersionMetadataBlock( @PathParam("id") String datasetId,
@PathParam("versionNumber") String versionNumber,
@PathParam("block") String blockName ) {
return allowCors(response( req -> {
DatasetVersion dsv = getDatasetVersionOrDie(req, versionNumber, findDatasetOrDie(datasetId) );
Map<MetadataBlock, List<DatasetField>> fieldsByBlock = DatasetField.groupByBlock(dsv.getDatasetFields());
for ( Map.Entry<MetadataBlock, List<DatasetField>> p : fieldsByBlock.entrySet() ) {
if ( p.getKey().getName().equals(blockName) ) {
return ok(json(p.getKey(), p.getValue()));
}
}
return notFound("metadata block named " + blockName + " not found");
}));
}
@DELETE
@Path("{id}/versions/{versionId}")
public Response deleteDraftVersion( @PathParam("id") String id, @PathParam("versionId") String versionId ){
if ( ! ":draft".equals(versionId) ) {
return badRequest("Only the :draft version can be deleted");
}
return response( req -> {
execCommand( new DeleteDatasetVersionCommand(req, findDatasetOrDie(id)) );
return ok("Draft version of dataset " + id + " deleted");
});
}
@GET
@Path("{id}/modifyRegistration")
public Response updateDatasetTargetURL(@PathParam("id") String id ) {
return response( req -> {
execCommand(new UpdateDatasetTargetURLCommand(findDatasetOrDie(id), req));
return ok("Dataset " + id + " target url updated");
});
}
@GET
@Path("/modifyRegistrationAll")
public Response updateDatasetTargetURLAll() {
return response( req -> {
datasetService.findAll().forEach( ds -> {
try {
execCommand(new UpdateDatasetTargetURLCommand(findDatasetOrDie(ds.getId().toString()), req));
} catch (WrappedResponse ex) {
Logger.getLogger(Datasets.class.getName()).log(Level.SEVERE, null, ex);
}
});
return ok("Update All Dataset target url completed");
});
}
@PUT
@Path("{id}/versions/{versionId}")
public Response updateDraftVersion( String jsonBody, @PathParam("id") String id, @PathParam("versionId") String versionId ){
if ( ! ":draft".equals(versionId) ) {
return error( Response.Status.BAD_REQUEST, "Only the :draft version can be updated");
}
try ( StringReader rdr = new StringReader(jsonBody) ) {
DataverseRequest req = createDataverseRequest(findUserOrDie());
Dataset ds = findDatasetOrDie(id);
JsonObject json = Json.createReader(rdr).readObject();
DatasetVersion incomingVersion = jsonParser().parseDatasetVersion(json);
// clear possibly stale fields from the incoming dataset version.
// creation and modification dates are updated by the commands.
incomingVersion.setId(null);
incomingVersion.setVersionNumber(null);
incomingVersion.setMinorVersionNumber(null);
incomingVersion.setVersionState(DatasetVersion.VersionState.DRAFT);
incomingVersion.setDataset(ds);
incomingVersion.setCreateTime(null);
incomingVersion.setLastUpdateTime(null);
boolean updateDraft = ds.getLatestVersion().isDraft();
DatasetVersion managedVersion = execCommand( updateDraft
? new UpdateDatasetVersionCommand(req, incomingVersion)
: new CreateDatasetVersionCommand(req, ds, incomingVersion));
return ok( json(managedVersion) );
} catch (JsonParseException ex) {
logger.log(Level.SEVERE, "Semantic error parsing dataset version Json: " + ex.getMessage(), ex);
return error( Response.Status.BAD_REQUEST, "Error parsing dataset version: " + ex.getMessage() );
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@PUT
@Path("{id}/deleteMetadata")
public Response deleteVersionMetadata(String jsonBody, @PathParam("id") String id) throws WrappedResponse {
DataverseRequest req = createDataverseRequest(findUserOrDie());
return processDatasetFieldDataDelete(jsonBody, id, req);
}
private Response processDatasetFieldDataDelete(String jsonBody, String id, DataverseRequest req) {
try (StringReader rdr = new StringReader(jsonBody)) {
Dataset ds = findDatasetOrDie(id);
JsonObject json = Json.createReader(rdr).readObject();
DatasetVersion dsv = ds.getEditVersion();
List<DatasetField> fields = new LinkedList<>();
DatasetField singleField = null;
JsonArray fieldsJson = json.getJsonArray("fields");
if (fieldsJson == null) {
singleField = jsonParser().parseField(json, Boolean.FALSE);
fields.add(singleField);
} else {
fields = jsonParser().parseMultipleFields(json);
}
dsv.setVersionState(DatasetVersion.VersionState.DRAFT);
List<ControlledVocabularyValue> controlledVocabularyItemsToRemove = new ArrayList();
List<DatasetFieldValue> datasetFieldValueItemsToRemove = new ArrayList();
List<DatasetFieldCompoundValue> datasetFieldCompoundValueItemsToRemove = new ArrayList();
for (DatasetField updateField : fields) {
boolean found = false;
for (DatasetField dsf : dsv.getDatasetFields()) {
if (dsf.getDatasetFieldType().equals(updateField.getDatasetFieldType())) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
if (updateField.getDatasetFieldType().isControlledVocabulary()) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
for (ControlledVocabularyValue cvv : updateField.getControlledVocabularyValues()) {
for (ControlledVocabularyValue existing : dsf.getControlledVocabularyValues()) {
if (existing.getStrValue().equals(cvv.getStrValue())) {
found = true;
controlledVocabularyItemsToRemove.add(existing);
}
}
if (!found) {
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + cvv.getStrValue() + " not found.");
}
}
for (ControlledVocabularyValue remove : controlledVocabularyItemsToRemove) {
dsf.getControlledVocabularyValues().remove(remove);
}
} else {
if (dsf.getSingleControlledVocabularyValue().getStrValue().equals(updateField.getSingleControlledVocabularyValue().getStrValue())) {
found = true;
dsf.setSingleControlledVocabularyValue(null);
}
}
} else {
if (!updateField.getDatasetFieldType().isCompound()) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
for (DatasetFieldValue dfv : updateField.getDatasetFieldValues()) {
for (DatasetFieldValue edsfv : dsf.getDatasetFieldValues()) {
if (edsfv.getDisplayValue().equals(dfv.getDisplayValue())) {
found = true;
datasetFieldValueItemsToRemove.add(dfv);
}
}
if (!found) {
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + dfv.getDisplayValue() + " not found.");
}
}
datasetFieldValueItemsToRemove.forEach((remove) -> {
dsf.getDatasetFieldValues().remove(remove);
});
} else {
if (dsf.getSingleValue().getDisplayValue().equals(updateField.getSingleValue().getDisplayValue())) {
found = true;
dsf.setSingleValue(null);
}
}
} else {
for (DatasetFieldCompoundValue dfcv : updateField.getDatasetFieldCompoundValues()) {
String deleteVal = getCompoundDisplayValue(dfcv);
for (DatasetFieldCompoundValue existing : dsf.getDatasetFieldCompoundValues()) {
String existingString = getCompoundDisplayValue(existing);
if (existingString.equals(deleteVal)) {
found = true;
datasetFieldCompoundValueItemsToRemove.add(existing);
}
}
datasetFieldCompoundValueItemsToRemove.forEach((remove) -> {
dsf.getDatasetFieldCompoundValues().remove(remove);
});
if (!found) {
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + deleteVal + " not found.");
}
}
}
}
} else {
found = true;
dsf.setSingleValue(null);
dsf.setSingleControlledVocabularyValue(null);
}
break;
}
}
if (!found){
String displayValue = !updateField.getDisplayValue().isEmpty() ? updateField.getDisplayValue() : updateField.getCompoundDisplayValue();
return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + displayValue + " not found." );
}
}
boolean updateDraft = ds.getLatestVersion().isDraft();
DatasetVersion managedVersion = execCommand(updateDraft
? new UpdateDatasetVersionCommand(req, dsv)
: new CreateDatasetVersionCommand(req, ds, dsv));
return ok(json(managedVersion));
} catch (JsonParseException ex) {
logger.log(Level.SEVERE, "Semantic error parsing dataset update Json: " + ex.getMessage(), ex);
return error(Response.Status.BAD_REQUEST, "Error processing metadata delete: " + ex.getMessage());
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
private String getCompoundDisplayValue (DatasetFieldCompoundValue dscv){
String returnString = "";
for (DatasetField dsf : dscv.getChildDatasetFields()) {
for (String value : dsf.getValues()) {
if (!(value == null)) {
returnString += (returnString.isEmpty() ? "" : "; ") + value.trim();
}
}
}
return returnString;
}
@PUT
@Path("{id}/editMetadata")
public Response editVersionMetadata(String jsonBody, @PathParam("id") String id, @QueryParam("replace") Boolean replace) throws WrappedResponse{
Boolean replaceData = replace != null;
DataverseRequest req = createDataverseRequest(findUserOrDie());
return processDatasetUpdate(jsonBody, id, req, replaceData);
}
private Response processDatasetUpdate(String jsonBody, String id, DataverseRequest req, Boolean replaceData){
try (StringReader rdr = new StringReader(jsonBody)) {
Dataset ds = findDatasetOrDie(id);
JsonObject json = Json.createReader(rdr).readObject();
DatasetVersion dsv = ds.getEditVersion();
List<DatasetField> fields = new LinkedList<>();
DatasetField singleField = null;
JsonArray fieldsJson = json.getJsonArray("fields");
if( fieldsJson == null ){
singleField = jsonParser().parseField(json, Boolean.FALSE);
fields.add(singleField);
} else{
fields = jsonParser().parseMultipleFields(json);
}
validateDatasetFieldValues(fields);
dsv.setVersionState(DatasetVersion.VersionState.DRAFT);
//loop through the update fields
// and compare to the version fields
//if exist add/replace values
//if not add entire dsf
for (DatasetField updateField : fields) {
boolean found = false;
for (DatasetField dsf : dsv.getDatasetFields()) {
if (dsf.getDatasetFieldType().equals(updateField.getDatasetFieldType())) {
found = true;
if (dsf.isEmpty() || dsf.getDatasetFieldType().isAllowMultiples() || replaceData ) {
if(replaceData){
if(dsf.getDatasetFieldType().isAllowMultiples()){
dsf.setDatasetFieldCompoundValues(new ArrayList());
dsf.setDatasetFieldValues(new ArrayList());
dsf.getControlledVocabularyValues().clear();
} else {
dsf.setSingleValue("");
dsf.setSingleControlledVocabularyValue(null);
}
}
if (updateField.getDatasetFieldType().isControlledVocabulary()) {
if (dsf.getDatasetFieldType().isAllowMultiples()){
for (ControlledVocabularyValue cvv : updateField.getControlledVocabularyValues()) {
if (!dsf.getDisplayValue().contains(cvv.getStrValue())) {
dsf.getControlledVocabularyValues().add(cvv);
}
}
} else {
dsf.setSingleControlledVocabularyValue(updateField.getSingleControlledVocabularyValue());
}
} else {
if (!updateField.getDatasetFieldType().isCompound()) {
if (dsf.getDatasetFieldType().isAllowMultiples()) {
for (DatasetFieldValue dfv : updateField.getDatasetFieldValues()) {
if (!dsf.getDisplayValue().contains(dfv.getDisplayValue())) {
dfv.setDatasetField(dsf);
dsf.getDatasetFieldValues().add(dfv);
}
}
} else {
dsf.setSingleValue(updateField.getValue());
}
} else {
for (DatasetFieldCompoundValue dfcv : updateField.getDatasetFieldCompoundValues()) {
if (!dsf.getCompoundDisplayValue().contains(updateField.getCompoundDisplayValue())) {
dfcv.setParentDatasetField(dsf);
dsf.setDatasetVersion(dsv);
dsf.getDatasetFieldCompoundValues().add(dfcv);
}
}
}
}
} else {
if (!dsf.isEmpty() && !dsf.getDatasetFieldType().isAllowMultiples() || !replaceData) {
return error(Response.Status.BAD_REQUEST, "You may not add data to a field that already has data and does not allow multiples. Use replace=true to replace existing data (" + dsf.getDatasetFieldType().getDisplayName() + ")" );
}
}
break;
}
}
if(!found){
updateField.setDatasetVersion(dsv);
dsv.getDatasetFields().add(updateField);
}
}
boolean updateDraft = ds.getLatestVersion().isDraft();
DatasetVersion managedVersion = execCommand(updateDraft
? new UpdateDatasetVersionCommand(req, dsv)
: new CreateDatasetVersionCommand(req, ds, dsv));
return ok(json(managedVersion));
} catch (JsonParseException ex) {
logger.log(Level.SEVERE, "Semantic error parsing dataset update Json: " + ex.getMessage(), ex);
return error(Response.Status.BAD_REQUEST, "Error parsing dataset update: " + ex.getMessage());
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
private void validateDatasetFieldValues(List<DatasetField> fields) throws JsonParseException {
StringBuilder error = new StringBuilder();
for (DatasetField dsf : fields) {
if (dsf.getDatasetFieldType().isAllowMultiples() && dsf.getControlledVocabularyValues().isEmpty()
&& dsf.getDatasetFieldCompoundValues().isEmpty() && dsf.getDatasetFieldValues().isEmpty()) {
error.append("Empty multiple value for field ").append(dsf.getDatasetFieldType().getDisplayName()).append(" ");
} else if (!dsf.getDatasetFieldType().isAllowMultiples() && dsf.getSingleValue().getValue().isEmpty()) {
error.append("Empty value for field ").append(dsf.getDatasetFieldType().getDisplayName()).append(" ");
}
}
if (!error.toString().isEmpty()) {
throw new JsonParseException(error.toString());
}
}
/**
* @deprecated This was shipped as a GET but should have been a POST, see https://github.com/IQSS/dataverse/issues/2431
*/
@GET
@Path("{id}/actions/:publish")
@Deprecated
public Response publishDataseUsingGetDeprecated( @PathParam("id") String id, @QueryParam("type") String type ) {
logger.info("publishDataseUsingGetDeprecated called on id " + id + ". Encourage use of POST rather than GET, which is deprecated.");
return publishDataset(id, type);
}
@POST
@Path("{id}/actions/:publish")
public Response publishDataset(@PathParam("id") String id, @QueryParam("type") String type) {
try {
if (type == null) {
return error(Response.Status.BAD_REQUEST, "Missing 'type' parameter (either 'major' or 'minor').");
}
type = type.toLowerCase();
boolean isMinor;
switch (type) {
case "minor":
isMinor = true;
break;
case "major":
isMinor = false;
break;
default:
return error(Response.Status.BAD_REQUEST, "Illegal 'type' parameter value '" + type + "'. It needs to be either 'major' or 'minor'.");
}
Dataset ds = findDatasetOrDie(id);
PublishDatasetResult res = execCommand(new PublishDatasetCommand(ds,
createDataverseRequest(findAuthenticatedUserOrDie()),
isMinor));
return res.isCompleted() ? ok(json(res.getDataset())) : accepted(json(res.getDataset()));
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@POST
@Path("{id}/move/{targetDataverseAlias}")
public Response moveDataset(@PathParam("id") String id, @PathParam("targetDataverseAlias") String targetDataverseAlias, @QueryParam("forceMove") Boolean force) {
try{
User u = findUserOrDie();
Dataset ds = findDatasetOrDie(id);
Dataverse target = dataverseService.findByAlias(targetDataverseAlias);
if (target == null){
return error(Response.Status.BAD_REQUEST, "Target Dataverse not found.");
}
//Command requires Super user - it will be tested by the command
execCommand(new MoveDatasetCommand(
createDataverseRequest(u), ds, target, force
));
return ok("Dataset moved successfully");
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@PUT
@Path("{linkedDatasetId}/link/{linkingDataverseAlias}")
public Response linkDataset(@PathParam("linkedDatasetId") String linkedDatasetId, @PathParam("linkingDataverseAlias") String linkingDataverseAlias) {
try{
User u = findUserOrDie();
Dataset linked = findDatasetOrDie(linkedDatasetId);
Dataverse linking = findDataverseOrDie(linkingDataverseAlias);
if (linked == null){
return error(Response.Status.BAD_REQUEST, "Linked Dataset not found.");
}
if (linking == null){
return error(Response.Status.BAD_REQUEST, "Linking Dataverse not found.");
}
execCommand(new LinkDatasetCommand(
createDataverseRequest(u), linking, linked
));
return ok("Dataset " + linked.getId() + " linked successfully to " + linking.getAlias());
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@GET
@Path("{id}/links")
public Response getLinks(@PathParam("id") String idSupplied ) {
try {
User u = findUserOrDie();
if (!u.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Not a superuser");
}
Dataset dataset = findDatasetOrDie(idSupplied);
long datasetId = dataset.getId();
List<Dataverse> dvsThatLinkToThisDatasetId = dataverseSvc.findDataversesThatLinkToThisDatasetId(datasetId);
JsonArrayBuilder dataversesThatLinkToThisDatasetIdBuilder = Json.createArrayBuilder();
for (Dataverse dataverse : dvsThatLinkToThisDatasetId) {
dataversesThatLinkToThisDatasetIdBuilder.add(dataverse.getAlias() + " (id " + dataverse.getId() + ")");
}
JsonObjectBuilder response = Json.createObjectBuilder();
response.add("dataverses that link to dataset id " + datasetId, dataversesThatLinkToThisDatasetIdBuilder);
return ok(response);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
/**
* @todo Make this real. Currently only used for API testing. Copied from
* the equivalent API endpoint for dataverses and simplified with values
* hard coded.
*/
@POST
@Path("{identifier}/assignments")
public Response createAssignment(String userOrGroup, @PathParam("identifier") String id, @QueryParam("key") String apiKey) {
boolean apiTestingOnly = true;
if (apiTestingOnly) {
return error(Response.Status.FORBIDDEN, "This is only for API tests.");
}
try {
Dataset dataset = findDatasetOrDie(id);
RoleAssignee assignee = findAssignee(userOrGroup);
if (assignee == null) {
return error(Response.Status.BAD_REQUEST, "Assignee not found");
}
DataverseRole theRole = rolesSvc.findBuiltinRoleByAlias("admin");
String privateUrlToken = null;
return ok(
json(execCommand(new AssignRoleCommand(assignee, theRole, dataset, createDataverseRequest(findUserOrDie()), privateUrlToken))));
} catch (WrappedResponse ex) {
logger.log(Level.WARNING, "Can''t create assignment: {0}", ex.getMessage());
return ex.getResponse();
}
}
@GET
@Path("{identifier}/assignments")
public Response getAssignments(@PathParam("identifier") String id) {
return response( req ->
ok( execCommand(
new ListRoleAssignments(req, findDatasetOrDie(id)))
.stream().map(ra->json(ra)).collect(toJsonArray())) );
}
@GET
@Path("{id}/privateUrl")
public Response getPrivateUrlData(@PathParam("id") String idSupplied) {
return response( req -> {
PrivateUrl privateUrl = execCommand(new GetPrivateUrlCommand(req, findDatasetOrDie(idSupplied)));
return (privateUrl != null) ? ok(json(privateUrl))
: error(Response.Status.NOT_FOUND, "Private URL not found.");
});
}
@POST
@Path("{id}/privateUrl")
public Response createPrivateUrl(@PathParam("id") String idSupplied) {
return response( req ->
ok(json(execCommand(
new CreatePrivateUrlCommand(req, findDatasetOrDie(idSupplied))))));
}
@DELETE
@Path("{id}/privateUrl")
public Response deletePrivateUrl(@PathParam("id") String idSupplied) {
return response( req -> {
Dataset dataset = findDatasetOrDie(idSupplied);
PrivateUrl privateUrl = execCommand(new GetPrivateUrlCommand(req, dataset));
if (privateUrl != null) {
execCommand(new DeletePrivateUrlCommand(req, dataset));
return ok("Private URL deleted.");
} else {
return notFound("No Private URL to delete.");
}
});
}
@GET
@Path("{id}/thumbnail/candidates")
public Response getDatasetThumbnailCandidates(@PathParam("id") String idSupplied) {
try {
Dataset dataset = findDatasetOrDie(idSupplied);
boolean canUpdateThumbnail = false;
try {
canUpdateThumbnail = permissionSvc.requestOn(createDataverseRequest(findUserOrDie()), dataset).canIssue(UpdateDatasetThumbnailCommand.class);
} catch (WrappedResponse ex) {
logger.info("Exception thrown while trying to figure out permissions while getting thumbnail for dataset id " + dataset.getId() + ": " + ex.getLocalizedMessage());
}
if (!canUpdateThumbnail) {
return error(Response.Status.FORBIDDEN, "You are not permitted to list dataset thumbnail candidates.");
}
JsonArrayBuilder data = Json.createArrayBuilder();
boolean considerDatasetLogoAsCandidate = true;
for (DatasetThumbnail datasetThumbnail : DatasetUtil.getThumbnailCandidates(dataset, considerDatasetLogoAsCandidate)) {
JsonObjectBuilder candidate = Json.createObjectBuilder();
String base64image = datasetThumbnail.getBase64image();
if (base64image != null) {
logger.fine("found a candidate!");
candidate.add("base64image", base64image);
}
DataFile dataFile = datasetThumbnail.getDataFile();
if (dataFile != null) {
candidate.add("dataFileId", dataFile.getId());
}
data.add(candidate);
}
return ok(data);
} catch (WrappedResponse ex) {
return error(Response.Status.NOT_FOUND, "Could not find dataset based on id supplied: " + idSupplied + ".");
}
}
@GET
@Produces({"image/png"})
@Path("{id}/thumbnail")
public InputStream getDatasetThumbnail(@PathParam("id") String idSupplied) {
try {
Dataset dataset = findDatasetOrDie(idSupplied);
return DatasetUtil.getThumbnailAsInputStream(dataset);
} catch (WrappedResponse ex) {
return null;
}
}
// TODO: Rather than only supporting looking up files by their database IDs (dataFileIdSupplied), consider supporting persistent identifiers.
@POST
@Path("{id}/thumbnail/{dataFileId}")
public Response setDataFileAsThumbnail(@PathParam("id") String idSupplied, @PathParam("dataFileId") long dataFileIdSupplied) {
try {
DatasetThumbnail datasetThumbnail = execCommand(new UpdateDatasetThumbnailCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied), UpdateDatasetThumbnailCommand.UserIntent.setDatasetFileAsThumbnail, dataFileIdSupplied, null));
return ok("Thumbnail set to " + datasetThumbnail.getBase64image());
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@POST
@Path("{id}/thumbnail")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadDatasetLogo(@PathParam("id") String idSupplied, @FormDataParam("file") InputStream inputStream
) {
try {
DatasetThumbnail datasetThumbnail = execCommand(new UpdateDatasetThumbnailCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied), UpdateDatasetThumbnailCommand.UserIntent.setNonDatasetFileAsThumbnail, null, inputStream));
return ok("Thumbnail is now " + datasetThumbnail.getBase64image());
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@DELETE
@Path("{id}/thumbnail")
public Response removeDatasetLogo(@PathParam("id") String idSupplied) {
try {
DatasetThumbnail datasetThumbnail = execCommand(new UpdateDatasetThumbnailCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied), UpdateDatasetThumbnailCommand.UserIntent.removeThumbnail, null, null));
return ok("Dataset thumbnail removed.");
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@GET
@Path("{identifier}/dataCaptureModule/rsync")
public Response getRsync(@PathParam("identifier") String id) {
//TODO - does it make sense to switch this to dataset identifier for consistency with the rest of the DCM APIs?
if (!DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
return error(Response.Status.METHOD_NOT_ALLOWED, SettingsServiceBean.Key.UploadMethods + " does not contain " + SystemConfig.FileUploadMethods.RSYNC + ".");
}
Dataset dataset = null;
try {
dataset = findDatasetOrDie(id);
AuthenticatedUser user = findAuthenticatedUserOrDie();
ScriptRequestResponse scriptRequestResponse = execCommand(new RequestRsyncScriptCommand(createDataverseRequest(user), dataset));
DatasetLock lock = datasetService.addDatasetLock(dataset.getId(), DatasetLock.Reason.DcmUpload, user.getId(), "script downloaded");
if (lock == null) {
logger.log(Level.WARNING, "Failed to lock the dataset (dataset id={0})", dataset.getId());
return error(Response.Status.FORBIDDEN, "Failed to lock the dataset (dataset id="+dataset.getId()+")");
}
return ok(scriptRequestResponse.getScript(), MediaType.valueOf(MediaType.TEXT_PLAIN));
} catch (WrappedResponse wr) {
return wr.getResponse();
} catch (EJBException ex) {
return error(Response.Status.INTERNAL_SERVER_ERROR, "Something went wrong attempting to download rsync script: " + EjbUtil.ejbExceptionToString(ex));
}
}
@POST
@Path("{identifier}/dataCaptureModule/checksumValidation")
public Response receiveChecksumValidationResults(@PathParam("identifier") String id, JsonObject jsonFromDcm) {
logger.log(Level.FINE, "jsonFromDcm: {0}", jsonFromDcm);
AuthenticatedUser authenticatedUser = null;
try {
authenticatedUser = findAuthenticatedUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.BAD_REQUEST, "Authentication is required.");
}
if (!authenticatedUser.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
String statusMessageFromDcm = jsonFromDcm.getString("status");
try {
Dataset dataset = findDatasetOrDie(id);
if ("validation passed".equals(statusMessageFromDcm)) {
String uploadFolder = jsonFromDcm.getString("uploadFolder");
int totalSize = jsonFromDcm.getInt("totalSize");
ImportMode importMode = ImportMode.MERGE;
try {
JsonObject jsonFromImportJobKickoff = execCommand(new ImportFromFileSystemCommand(createDataverseRequest(findUserOrDie()), dataset, uploadFolder, new Long(totalSize), importMode));
long jobId = jsonFromImportJobKickoff.getInt("executionId");
String message = jsonFromImportJobKickoff.getString("message");
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("jobId", jobId);
job.add("message", message);
return ok(job);
} catch (WrappedResponse wr) {
String message = wr.getMessage();
return error(Response.Status.INTERNAL_SERVER_ERROR, "Uploaded files have passed checksum validation but something went wrong while attempting to put the files into Dataverse. Message was '" + message + "'.");
}
} else if ("validation failed".equals(statusMessageFromDcm)) {
Map<String, AuthenticatedUser> distinctAuthors = permissionService.getDistinctUsersWithPermissionOn(Permission.EditDataset, dataset);
distinctAuthors.values().forEach((value) -> {
userNotificationService.sendNotification((AuthenticatedUser) value, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
List<AuthenticatedUser> superUsers = authenticationServiceBean.findSuperUsers();
if (superUsers != null && !superUsers.isEmpty()) {
superUsers.forEach((au) -> {
userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
}
return ok("User notified about checksum validation failure.");
} else {
return error(Response.Status.BAD_REQUEST, "Unexpected status cannot be processed: " + statusMessageFromDcm);
}
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
@POST
@Path("{id}/submitForReview")
public Response submitForReview(@PathParam("id") String idSupplied) {
try {
Dataset updatedDataset = execCommand(new SubmitDatasetForReviewCommand(createDataverseRequest(findUserOrDie()), findDatasetOrDie(idSupplied)));
JsonObjectBuilder result = Json.createObjectBuilder();
boolean inReview = updatedDataset.isLockedFor(DatasetLock.Reason.InReview);
result.add("inReview", inReview);
result.add("message", "Dataset id " + updatedDataset.getId() + " has been submitted for review.");
return ok(result);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@POST
@Path("{id}/returnToAuthor")
public Response returnToAuthor(@PathParam("id") String idSupplied, String jsonBody) {
if (jsonBody == null || jsonBody.isEmpty()) {
return error(Response.Status.BAD_REQUEST, "You must supply JSON to this API endpoint and it must contain a reason for returning the dataset.");
}
StringReader rdr = new StringReader(jsonBody);
JsonObject json = Json.createReader(rdr).readObject();
try {
Dataset dataset = findDatasetOrDie(idSupplied);
String reasonForReturn = null;
reasonForReturn = json.getString("reasonForReturn");
// TODO: Once we add a box for the curator to type into, pass the reason for return to the ReturnDatasetToAuthorCommand and delete this check and call to setReturnReason on the API side.
if (reasonForReturn == null || reasonForReturn.isEmpty()) {
return error(Response.Status.BAD_REQUEST, "You must enter a reason for returning a dataset to the author(s).");
}
AuthenticatedUser authenticatedUser = findAuthenticatedUserOrDie();
Dataset updatedDataset = execCommand(new ReturnDatasetToAuthorCommand(createDataverseRequest(authenticatedUser), dataset, reasonForReturn ));
boolean inReview = updatedDataset.isLockedFor(DatasetLock.Reason.InReview);
JsonObjectBuilder result = Json.createObjectBuilder();
result.add("inReview", inReview);
result.add("message", "Dataset id " + updatedDataset.getId() + " has been sent back to the author(s).");
return ok(result);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
/**
* Add a File to an existing Dataset
*
* @param idSupplied
* @param jsonData
* @param fileInputStream
* @param contentDispositionHeader
* @param formDataBodyPart
* @return
*/
@POST
@Path("{id}/add")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response addFileToDataset(@PathParam("id") String idSupplied,
@FormDataParam("jsonData") String jsonData,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
@FormDataParam("file") final FormDataBodyPart formDataBodyPart
){
// -------------------------------------
// (1) Get the user from the API key
// -------------------------------------
User authUser;
try {
authUser = findUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN,
ResourceBundle.getBundle("Bundle").getString("file.addreplace.error.auth")
);
}
//---------------------------------------
// (1A) Make sure that the upload type is not rsync
// -------------------------------------
if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
return error(Response.Status.METHOD_NOT_ALLOWED, SettingsServiceBean.Key.UploadMethods + " contains " + SystemConfig.FileUploadMethods.RSYNC + ". Please use rsync file upload.");
}
// -------------------------------------
// (2) Get the Dataset Id
//
// -------------------------------------
Dataset dataset;
Long datasetId;
try {
dataset = findDatasetOrDie(idSupplied);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
// -------------------------------------
// (3) Get the file name and content type
// -------------------------------------
String newFilename = contentDispositionHeader.getFileName();
String newFileContentType = formDataBodyPart.getMediaType().toString();
// (2a) Load up optional params via JSON
//---------------------------------------
OptionalFileParams optionalFileParams = null;
msgt("(api) jsonData: " + jsonData);
try {
optionalFileParams = new OptionalFileParams(jsonData);
} catch (DataFileTagException ex) {
return error( Response.Status.BAD_REQUEST, ex.getMessage());
}
//-------------------
// (3) Create the AddReplaceFileHelper object
//-------------------
msg("ADD!");
DataverseRequest dvRequest2 = createDataverseRequest(authUser);
AddReplaceFileHelper addFileHelper = new AddReplaceFileHelper(dvRequest2,
ingestService,
datasetService,
fileService,
permissionSvc,
commandEngine,
systemConfig);
//-------------------
// (4) Run "runAddFileByDatasetId"
//-------------------
addFileHelper.runAddFileByDataset(dataset,
newFilename,
newFileContentType,
fileInputStream,
optionalFileParams);
if (addFileHelper.hasError()){
return error(addFileHelper.getHttpErrorCode(), addFileHelper.getErrorMessagesAsString("\n"));
}else{
String successMsg = ResourceBundle.getBundle("Bundle").getString("file.addreplace.success.add");
try {
//msgt("as String: " + addFileHelper.getSuccessResult());
/**
* @todo We need a consistent, sane way to communicate a human
* readable message to an API client suitable for human
* consumption. Imagine if the UI were built in Angular or React
* and we want to return a message from the API as-is to the
* user. Human readable.
*/
logger.fine("successMsg: " + successMsg);
return ok(addFileHelper.getSuccessResultAsJsonObjectBuilder());
//"Look at that! You added a file! (hey hey, it may have worked)");
} catch (NoFilesException ex) {
Logger.getLogger(Files.class.getName()).log(Level.SEVERE, null, ex);
return error(Response.Status.BAD_REQUEST, "NoFileException! Serious Error! See administrator!");
}
}
} // end: addFileToDataset
private void msg(String m){
//System.out.println(m);
logger.fine(m);
}
private void dashes(){
msg("----------------");
}
private void msgt(String m){
dashes(); msg(m); dashes();
}
private <T> T handleVersion( String versionId, DsVersionHandler<T> hdl )
throws WrappedResponse {
switch (versionId) {
case ":latest": return hdl.handleLatest();
case ":draft": return hdl.handleDraft();
case ":latest-published": return hdl.handleLatestPublished();
default:
try {
String[] versions = versionId.split("\\.");
switch (versions.length) {
case 1:
return hdl.handleSpecific(Long.parseLong(versions[0]), (long)0.0);
case 2:
return hdl.handleSpecific( Long.parseLong(versions[0]), Long.parseLong(versions[1]) );
default:
throw new WrappedResponse(error( Response.Status.BAD_REQUEST, "Illegal version identifier '" + versionId + "'"));
}
} catch ( NumberFormatException nfe ) {
throw new WrappedResponse( error( Response.Status.BAD_REQUEST, "Illegal version identifier '" + versionId + "'") );
}
}
}
private DatasetVersion getDatasetVersionOrDie( final DataverseRequest req, String versionNumber, final Dataset ds ) throws WrappedResponse {
DatasetVersion dsv = execCommand( handleVersion(versionNumber, new DsVersionHandler<Command<DatasetVersion>>(){
@Override
public Command<DatasetVersion> handleLatest() {
return new GetLatestAccessibleDatasetVersionCommand(req, ds);
}
@Override
public Command<DatasetVersion> handleDraft() {
return new GetDraftDatasetVersionCommand(req, ds);
}
@Override
public Command<DatasetVersion> handleSpecific(long major, long minor) {
return new GetSpecificPublishedDatasetVersionCommand(req, ds, major, minor);
}
@Override
public Command<DatasetVersion> handleLatestPublished() {
return new GetLatestPublishedDatasetVersionCommand(req, ds);
}
}));
if ( dsv == null || dsv.getId() == null ) {
throw new WrappedResponse( notFound("Dataset version " + versionNumber + " of dataset " + ds.getId() + " not found") );
}
return dsv;
}
}
| #3599 Post update/delete errors to log
| src/main/java/edu/harvard/iq/dataverse/api/Datasets.java | #3599 Post update/delete errors to log | <ide><path>rc/main/java/edu/harvard/iq/dataverse/api/Datasets.java
<ide> }
<ide> }
<ide> if (!found) {
<add> logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + cvv.getStrValue() + " not found.");
<ide> return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + cvv.getStrValue() + " not found.");
<ide> }
<ide> }
<ide> }
<ide> }
<ide> if (!found) {
<add> logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + dfv.getDisplayValue() + " not found.");
<ide> return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + dfv.getDisplayValue() + " not found.");
<ide> }
<ide> }
<ide> datasetFieldCompoundValueItemsToRemove.forEach((remove) -> {
<ide> dsf.getDatasetFieldCompoundValues().remove(remove);
<ide> });
<del> if (!found) {
<add> if (!found) {
<add> logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + deleteVal + " not found.");
<ide> return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + deleteVal + " not found.");
<ide> }
<ide> }
<ide> }
<ide> if (!found){
<ide> String displayValue = !updateField.getDisplayValue().isEmpty() ? updateField.getDisplayValue() : updateField.getCompoundDisplayValue();
<add> logger.log(Level.SEVERE, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + displayValue + " not found." );
<ide> return error(Response.Status.BAD_REQUEST, "Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + displayValue + " not found." );
<ide> }
<ide> }
<ide> return error(Response.Status.BAD_REQUEST, "Error processing metadata delete: " + ex.getMessage());
<ide>
<ide> } catch (WrappedResponse ex) {
<add> logger.log(Level.SEVERE, "Delete metadata error: " + ex.getMessage(), ex);
<ide> return ex.getResponse();
<ide>
<ide> }
<ide> return error(Response.Status.BAD_REQUEST, "Error parsing dataset update: " + ex.getMessage());
<ide>
<ide> } catch (WrappedResponse ex) {
<add> logger.log(Level.SEVERE, "Update metdata error: " + ex.getMessage(), ex);
<ide> return ex.getResponse();
<ide>
<ide> } |
|
Java | agpl-3.0 | 5dc3d4329d69ecc55f6a7f6e6ce8219de33d18c4 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | ecf419ea-2e5f-11e5-9284-b827eb9e62be | hello.java | eceeafa0-2e5f-11e5-9284-b827eb9e62be | ecf419ea-2e5f-11e5-9284-b827eb9e62be | hello.java | ecf419ea-2e5f-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>eceeafa0-2e5f-11e5-9284-b827eb9e62be
<add>ecf419ea-2e5f-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | d697ce9cb255f4cd65abe05c3550175d9cd61ffa | 0 | nikboyd/axiom-lib-java | /**
* Copyright 2015 Nikolas Boyd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axiom_tools.services;
import java.util.*;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.axiom_tools.codecs.ValueMap;
import org.axiom_tools.domain.Contact;
import org.axiom_tools.domain.EmailAddress;
import org.springframework.stereotype.Service;
import org.axiom_tools.domain.Person;
import org.axiom_tools.domain.PhoneNumber;
import org.axiom_tools.faces.IPersonService;
import org.axiom_tools.storage.StorageMechanism;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* A service for maintaining Persons and their Contact information.
* @author nik
*/
@Service
@Transactional
@Path(IPersonService.BasePath)
public class PersonFacade implements IPersonService {
private static final String Empty = "";
private static final String Wild = "%";
@Autowired
private StorageMechanism.Registry registry;
@Override
public Response listPersons(String name, String city, String zip) {
List<Person> results = Person.like(Wild + name + Wild);
return Response.ok(results).build();
}
@Override
public Response createPerson(String personJSON) {
Person sample = Person.fromJSON(personJSON);
Person p = sample.saveItem();
ValueMap result = ValueMap.withID(p.getKey());
return Response.ok(result.toJSON()).build();
}
@Override
public Response savePerson(long personID, String personJSON) {
Person sample = Person.fromJSON(personJSON);
if (sample.getKey() != personID) {
return Response.status(Status.CONFLICT).build();
}
Person p = Person.withKey(personID).findItem();
if (p == null) {
return Response.status(Status.GONE).build();
}
p = sample.saveItem();
return Response.ok(p).build();
}
@Override
public Response getPerson(long personID) {
Person p = Person.withKey(personID).findItem();
if (p == null) {
return Response.status(Status.GONE).build();
}
else {
return Response.ok(p).build();
}
}
@Override
public Response getPersonWithHash(Contact.Type idType, String personID) {
switch (idType) {
case hash: {
Person result = Person.named(personID).findWithHash();
Person[] results = { result };
return Response.ok(Arrays.asList(results)).build();
}
case email: {
List<Person> results = Person.findSimilar(EmailAddress.from(personID));
return Response.ok(results).build();
}
case phone: {
List<Person> results = Person.findSimilar(PhoneNumber.from(personID));
return Response.ok(results).build();
}
}
Person[] results = { };
return Response.ok(Arrays.asList(results)).build();
}
@Override
public Response deletePerson(long personID) {
Person p = Person.withKey(personID).findItem();
if (p == null) {
return Response.status(Status.GONE).build();
}
boolean gone = p.removeItem();
return Response.accepted().build();
}
@Override
public Response deletePersonWithHash(Contact.Type idType, String personID) {
switch (idType) {
case hash: {
Person p = Person.named(personID).findWithHash();
if (p == null) {
return Response.status(Status.GONE).build();
}
boolean gone = p.removeItem();
return Response.accepted().build();
}
case email: {
List<Person> results = Person.findSimilar(EmailAddress.from(personID));
if (results.isEmpty()) {
return Response.status(Status.GONE).build();
}
boolean gone = results.get(0).removeItem();
return Response.accepted().build();
}
case phone: {
List<Person> results = Person.findSimilar(PhoneNumber.from(personID));
if (results.isEmpty()) {
return Response.status(Status.GONE).build();
}
boolean gone = results.get(0).removeItem();
return Response.accepted().build();
}
}
return Response.accepted().build();
}
}
| axiom-service/src/main/java/org/axiom_tools/services/PersonFacade.java | /**
* Copyright 2015 Nikolas Boyd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axiom_tools.services;
import java.util.*;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.axiom_tools.codecs.ValueMap;
import org.axiom_tools.domain.Contact;
import org.axiom_tools.domain.EmailAddress;
import org.springframework.stereotype.Service;
import org.axiom_tools.domain.Person;
import org.axiom_tools.domain.PhoneNumber;
import org.axiom_tools.faces.IPersonService;
import org.axiom_tools.storage.StorageMechanism;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* A service for maintaining Persons.
* @author nik
*/
@Service
@Transactional
@Path(IPersonService.BasePath)
public class PersonFacade implements IPersonService {
private static final String Empty = "";
private static final String Wild = "%";
@Autowired
private StorageMechanism.Registry registry;
@Override
public Response listPersons(String name, String city, String zip) {
List<Person> results = Person.like(Wild + name + Wild);
return Response.ok(results).build();
}
@Override
public Response createPerson(String personJSON) {
Person sample = Person.fromJSON(personJSON);
Person p = sample.saveItem();
ValueMap result = ValueMap.withID(p.getKey());
return Response.ok(result.toJSON()).build();
}
@Override
public Response savePerson(long personID, String personJSON) {
Person sample = Person.fromJSON(personJSON);
if (sample.getKey() != personID) {
return Response.status(Status.CONFLICT).build();
}
Person p = Person.withKey(personID).findItem();
if (p == null) {
return Response.status(Status.GONE).build();
}
p = sample.saveItem();
return Response.ok(p).build();
}
@Override
public Response getPerson(long personID) {
Person p = Person.withKey(personID).findItem();
if (p == null) {
return Response.status(Status.GONE).build();
}
else {
return Response.ok(p).build();
}
}
@Override
public Response getPersonWithHash(Contact.Type idType, String personID) {
switch (idType) {
case hash: {
Person result = Person.named(personID).findWithHash();
Person[] results = { result };
return Response.ok(Arrays.asList(results)).build();
}
case email: {
List<Person> results = Person.findSimilar(EmailAddress.from(personID));
return Response.ok(results).build();
}
case phone: {
List<Person> results = Person.findSimilar(PhoneNumber.from(personID));
return Response.ok(results).build();
}
}
Person[] results = { };
return Response.ok(Arrays.asList(results)).build();
}
@Override
public Response deletePerson(long personID) {
Person p = Person.withKey(personID).findItem();
if (p == null) {
return Response.status(Status.GONE).build();
}
boolean gone = p.removeItem();
return Response.accepted().build();
}
@Override
public Response deletePersonWithHash(Contact.Type idType, String personID) {
switch (idType) {
case hash: {
Person p = Person.named(personID).findWithHash();
if (p == null) {
return Response.status(Status.GONE).build();
}
boolean gone = p.removeItem();
return Response.accepted().build();
}
case email: {
List<Person> results = Person.findSimilar(EmailAddress.from(personID));
if (results.isEmpty()) {
return Response.status(Status.GONE).build();
}
boolean gone = results.get(0).removeItem();
return Response.accepted().build();
}
case phone: {
List<Person> results = Person.findSimilar(PhoneNumber.from(personID));
if (results.isEmpty()) {
return Response.status(Status.GONE).build();
}
boolean gone = results.get(0).removeItem();
return Response.accepted().build();
}
}
return Response.accepted().build();
}
}
| updated facade comment
| axiom-service/src/main/java/org/axiom_tools/services/PersonFacade.java | updated facade comment | <ide><path>xiom-service/src/main/java/org/axiom_tools/services/PersonFacade.java
<ide> import org.springframework.transaction.annotation.Transactional;
<ide>
<ide> /**
<del> * A service for maintaining Persons.
<add> * A service for maintaining Persons and their Contact information.
<ide> * @author nik
<ide> */
<ide> @Service |
|
Java | apache-2.0 | bab53cd9e7a91854f85fcded80b6f845e9534754 | 0 | kool79/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,dslomov/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,caot/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,xfournet/intellij-community,robovm/robovm-studio,holmes/intellij-community,diorcety/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,nicolargo/intellij-community,izonder/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,consulo/consulo,ryano144/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,ibinti/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,kdwink/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,vladmm/intellij-community,retomerz/intellij-community,joewalnes/idea-community,da1z/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,da1z/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,akosyakov/intellij-community,samthor/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ernestp/consulo,clumsy/intellij-community,dslomov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ernestp/consulo,youdonghai/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,jexp/idea2,izonder/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,jexp/idea2,TangHao1987/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,amith01994/intellij-community,semonte/intellij-community,asedunov/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,allotria/intellij-community,orekyuu/intellij-community,slisson/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,adedayo/intellij-community,da1z/intellij-community,Distrotech/intellij-community,slisson/intellij-community,xfournet/intellij-community,diorcety/intellij-community,da1z/intellij-community,ibinti/intellij-community,kdwink/intellij-community,da1z/intellij-community,ryano144/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,jagguli/intellij-community,kdwink/intellij-community,joewalnes/idea-community,asedunov/intellij-community,joewalnes/idea-community,holmes/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,slisson/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ernestp/consulo,fitermay/intellij-community,petteyg/intellij-community,dslomov/intellij-community,signed/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,Distrotech/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,supersven/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,slisson/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,caot/intellij-community,allotria/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,vladmm/intellij-community,caot/intellij-community,joewalnes/idea-community,slisson/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,vladmm/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,jexp/idea2,supersven/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,signed/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,semonte/intellij-community,ibinti/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,semonte/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,vladmm/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,hurricup/intellij-community,supersven/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,jexp/idea2,signed/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,signed/intellij-community,apixandru/intellij-community,signed/intellij-community,signed/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,consulo/consulo,fnouama/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,kool79/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,amith01994/intellij-community,samthor/intellij-community,retomerz/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,kool79/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,jexp/idea2,Distrotech/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,caot/intellij-community,fitermay/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,vladmm/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,petteyg/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,consulo/consulo,izonder/intellij-community,da1z/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,allotria/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,slisson/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,ryano144/intellij-community,semonte/intellij-community,petteyg/intellij-community,slisson/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,caot/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,consulo/consulo,caot/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,idea4bsd/idea4bsd,youdonghai/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,allotria/intellij-community,clumsy/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,FHannes/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,signed/intellij-community,supersven/intellij-community,signed/intellij-community,gnuhub/intellij-community,signed/intellij-community,kdwink/intellij-community,signed/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,robovm/robovm-studio,diorcety/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,FHannes/intellij-community,caot/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,supersven/intellij-community,ernestp/consulo,apixandru/intellij-community,hurricup/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,blademainer/intellij-community,fnouama/intellij-community,da1z/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,jagguli/intellij-community,kool79/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,clumsy/intellij-community,caot/intellij-community,fitermay/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,supersven/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,blademainer/intellij-community,allotria/intellij-community,kool79/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,blademainer/intellij-community,semonte/intellij-community,slisson/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,xfournet/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,xfournet/intellij-community,vladmm/intellij-community,fitermay/intellij-community,supersven/intellij-community,izonder/intellij-community,semonte/intellij-community,xfournet/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,semonte/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,dslomov/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,samthor/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,semonte/intellij-community,izonder/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,amith01994/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,FHannes/intellij-community,amith01994/intellij-community,apixandru/intellij-community,izonder/intellij-community,supersven/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,kool79/intellij-community,ahb0327/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,semonte/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,ernestp/consulo,slisson/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,asedunov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,apixandru/intellij-community,vladmm/intellij-community,adedayo/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,adedayo/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,vladmm/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ryano144/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,adedayo/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,clumsy/intellij-community,caot/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ernestp/consulo,ol-loginov/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,consulo/consulo,adedayo/intellij-community,amith01994/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,slisson/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,kool79/intellij-community,jexp/idea2,ol-loginov/intellij-community,holmes/intellij-community,FHannes/intellij-community,allotria/intellij-community,orekyuu/intellij-community,izonder/intellij-community,hurricup/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,petteyg/intellij-community,fnouama/intellij-community,ryano144/intellij-community,signed/intellij-community | package org.jetbrains.idea.svn;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TestDialog;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsShowConfirmationOption;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.pending.MockChangeListManagerGate;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.AbstractVcsTestCase;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.testFramework.fixtures.TempDirTestFixture;
import com.intellij.testFramework.vcs.MockChangelistBuilder;
import org.junit.After;
import org.junit.Before;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author yole
*/
public abstract class SvnTestCase extends AbstractVcsTestCase {
protected TempDirTestFixture myTempDirFixture;
private File myWcRoot;
protected String myRepoUrl;
private ChangeListManagerGate myGate;
@Before
public void setUp() throws Exception {
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
myTempDirFixture = fixtureFactory.createTempDirTestFixture();
myTempDirFixture.setUp();
final File svnRoot = new File(myTempDirFixture.getTempDirPath(), "svnroot");
svnRoot.mkdir();
File pluginRoot = new File(PathManager.getHomePath(), "svnPlugins/svn4idea");
if (!pluginRoot.isDirectory()) {
// try standalone mode
Class aClass = SvnTestCase.class;
String rootPath = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
pluginRoot = new File(rootPath).getParentFile().getParentFile().getParentFile();
}
myClientBinaryPath = new File(pluginRoot, "testData/svn/bin");
verify(runSvnAdmin("create", svnRoot.getPath()));
myWcRoot = new File(myTempDirFixture.getTempDirPath(), "wcroot");
myWcRoot.mkdir();
myRepoUrl = "file:///" + FileUtil.toSystemIndependentName(svnRoot.getPath());
verify(runSvn("co", myRepoUrl, "."));
initProject(myWcRoot);
activateVCS(SvnVcs.VCS_NAME);
myGate = new MockChangeListManagerGate(ChangeListManager.getInstance(myProject));
}
@After
public void tearDown() throws Exception {
tearDownProject();
if (myTempDirFixture != null) {
myTempDirFixture.tearDown();
myTempDirFixture = null;
}
}
protected RunResult runSvnAdmin(String... commandLine) throws IOException {
return runClient("svnadmin", null, null, commandLine);
}
protected RunResult runSvn(String... commandLine) throws IOException {
return runClient("svn", null, myWcRoot, commandLine);
}
protected void enableSilentOperation(final VcsConfiguration.StandardConfirmation op) {
setStandardConfirmation(SvnVcs.VCS_NAME, op, VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY);
}
protected void disableSilentOperation(final VcsConfiguration.StandardConfirmation op) {
setStandardConfirmation(SvnVcs.VCS_NAME, op, VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY);
}
protected void checkin() throws IOException {
verify(runSvn("ci", "-m", "test"));
}
protected void update() throws IOException {
verify(runSvn("up"));
}
protected List<Change> getAllChanges() throws VcsException {
return getChangesInScope(getAllDirtyScope());
}
protected List<Change> getChangesForFile(VirtualFile file) throws VcsException {
return getChangesInScope(getDirtyScopeForFile(file));
}
protected List<Change> getChangesInScope(final VcsDirtyScope dirtyScope) throws VcsException {
ChangeProvider changeProvider = SvnVcs.getInstance(myProject).getChangeProvider();
assert changeProvider != null;
MockChangelistBuilder builder = new MockChangelistBuilder();
changeProvider.getChanges(dirtyScope, builder, new EmptyProgressIndicator(), myGate);
return builder.getChanges();
}
protected void undo() {
final TestDialog oldTestDialog = Messages.setTestDialog(TestDialog.OK);
try {
UndoManager.getInstance(myProject).undo(null);
}
finally {
Messages.setTestDialog(oldTestDialog);
}
}
}
| plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java | package org.jetbrains.idea.svn;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TestDialog;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsShowConfirmationOption;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.pending.MockChangeListManagerGate;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.AbstractVcsTestCase;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.testFramework.fixtures.TempDirTestFixture;
import com.intellij.testFramework.vcs.MockChangelistBuilder;
import org.junit.After;
import org.junit.Before;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author yole
*/
public abstract class SvnTestCase extends AbstractVcsTestCase {
protected TempDirTestFixture myTempDirFixture;
private File myWcRoot;
protected String myRepoUrl;
private ChangeListManagerGate myGate;
@Before
public void setUp() throws Exception {
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
myTempDirFixture = fixtureFactory.createTempDirTestFixture();
myTempDirFixture.setUp();
final File svnRoot = new File(myTempDirFixture.getTempDirPath(), "svnroot");
svnRoot.mkdir();
File pluginRoot = new File(PathManager.getHomePath(), "svnPlugins/svn4idea");
if (!pluginRoot.isDirectory()) {
// try standalone mode
Class aClass = SvnTestCase.class;
String rootPath = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
pluginRoot = new File(rootPath).getParentFile().getParentFile().getParentFile();
}
myClientBinaryPath = new File(pluginRoot, "testData/svn/bin");
verify(runSvnAdmin("create", svnRoot.getPath()));
myWcRoot = new File(myTempDirFixture.getTempDirPath(), "wcroot");
myWcRoot.mkdir();
myRepoUrl = "file:///" + FileUtil.toSystemIndependentName(svnRoot.getPath());
verify(runSvn("co", myRepoUrl, "."));
initProject(myWcRoot);
activateVCS(SvnVcs.VCS_NAME);
myGate = new MockChangeListManagerGate(ChangeListManager.getInstance(myProject));
}
@After
public void tearDown() throws Exception {
tearDownProject();
if (myTempDirFixture != null) {
myTempDirFixture.tearDown();
myTempDirFixture = null;
}
}
protected RunResult runSvnAdmin(String... commandLine) throws IOException {
return runClient("svnadmin", null, null, commandLine);
}
protected RunResult runSvn(String... commandLine) throws IOException {
return runClient("svn", null, myWcRoot, commandLine);
}
protected void enableSilentOperation(final VcsConfiguration.StandardConfirmation op) {
setStandardConfirmation(SvnVcs.VCS_NAME, op, VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY);
}
protected void disableSilentOperation(final VcsConfiguration.StandardConfirmation op) {
setStandardConfirmation(SvnVcs.VCS_NAME, op, VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY);
}
protected void checkin() throws IOException {
verify(runSvn("ci", "-m", "test"));
}
protected void update() throws IOException {
verify(runSvn("up"));
}
protected List<Change> getAllChanges() throws VcsException {
return getChangesInScope(getAllDirtyScope());
}
protected List<Change> getChangesForFile(VirtualFile file) throws VcsException {
return getChangesInScope(getDirtyScopeForFile(file));
}
private List<Change> getChangesInScope(final VcsDirtyScope dirtyScope) throws VcsException {
ChangeProvider changeProvider = SvnVcs.getInstance(myProject).getChangeProvider();
assert changeProvider != null;
MockChangelistBuilder builder = new MockChangelistBuilder();
changeProvider.getChanges(dirtyScope, builder, new EmptyProgressIndicator(), myGate);
return builder.getChanges();
}
protected void undo() {
final TestDialog oldTestDialog = Messages.setTestDialog(TestDialog.OK);
try {
UndoManager.getInstance(myProject).undo(null);
}
finally {
Messages.setTestDialog(oldTestDialog);
}
}
}
| VCS: SvnDeleteTest - fixed to be stable (forgot file) | plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java | VCS: SvnDeleteTest - fixed to be stable (forgot file) | <ide><path>lugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java
<ide> return getChangesInScope(getDirtyScopeForFile(file));
<ide> }
<ide>
<del> private List<Change> getChangesInScope(final VcsDirtyScope dirtyScope) throws VcsException {
<add> protected List<Change> getChangesInScope(final VcsDirtyScope dirtyScope) throws VcsException {
<ide> ChangeProvider changeProvider = SvnVcs.getInstance(myProject).getChangeProvider();
<ide> assert changeProvider != null;
<ide> MockChangelistBuilder builder = new MockChangelistBuilder(); |
|
Java | agpl-3.0 | 09b5b1e654c1daaa753e6e0db38d4e195eb21fcc | 0 | bio4j/bio4j | package com.bio4j.model.uniprot.programs;
import com.bio4j.model.uniprot.UniprotGraph;
import com.bio4j.model.uniprot.vertices.*;
import com.bio4j.model.uniprot.edges.*;
import com.bio4j.angulillos.UntypedGraph;
import com.ohnosequences.xml.api.model.XMLElement;
import com.ohnosequences.xml.model.bio4j.UniprotDataXML;
import org.jdom2.Element;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* @author <a href="mailto:[email protected]">Pablo Pareja Tobes</a>
*/
public abstract class ImportUniprot<I extends UntypedGraph<RV,RVT,RE,RET>,RV,RVT,RE,RET> {
private static final Logger logger = Logger.getLogger("ImportUniprot");
private static FileHandler fh;
public static final String ENTRY_TAG_NAME = "entry";
public static final String ENTRY_ACCESSION_TAG_NAME = "accession";
public static final String ENTRY_NAME_TAG_NAME = "name";
public static final String ENTRY_MODIFIED_DATE_ATTRIBUTE = "modified";
public static final String ENTRY_CREATED_DATE_ATTRIBUTE = "created";
public static final String ENTRY_VERSION_ATTRIBUTE = "version";
public static final String ENTRY_DATASET_ATTRIBUTE = "dataset";
public static final String ENTRY_SEQUENCE_TAG_NAME = "sequence";
public static final String KEYWORD_TAG_NAME = "keyword";
public static final String KEYWORD_ID_ATTRIBUTE = "id";
public static final String REFERENCE_TAG_NAME = "reference";
public static final String CITATION_TAG_NAME = "citation";
public static final String GENE_LOCATION_TAG_NAME = "geneLocation";
public static final String ORGANISM_TAG_NAME = "organism";
public static final String ORGANISM_NAME_TAG_NAME = "name";
public static final String ORGANISM_NAME_TYPE_ATTRIBUTE = "type";
public static final String ORGANISM_SCIENTIFIC_NAME_TYPE = "scientific";
public static final String ORGANISM_COMMON_NAME_TYPE = "common";
public static final String ORGANISM_SYNONYM_NAME_TYPE = "synonym";
public static final String DB_REFERENCE_TAG_NAME = "dbReference";
public static final String DB_REFERENCE_TYPE_ATTRIBUTE = "type";
public static final String DB_REFERENCE_ID_ATTRIBUTE = "id";
public static final String DB_REFERENCE_VALUE_ATTRIBUTE = "value";
public static final String DB_REFERENCE_PROPERTY_TAG_NAME = "property";
public static final String INTERPRO_DB_REFERENCE_TYPE = "InterPro";
public static final String INTERPRO_ENTRY_NAME = "entry name";
public static final String GO_DB_REFERENCE_TYPE = "GO";
public static final String EVIDENCE_TYPE_ATTRIBUTE = "evidence";
public static final String SEQUENCE_MASS_ATTRIBUTE = "mass";
public static final String SEQUENCE_LENGTH_ATTRIBUTE = "length";
public static final String PROTEIN_TAG_NAME = "protein";
public static final String PROTEIN_RECOMMENDED_NAME_TAG_NAME = "recommendedName";
public static final String PROTEIN_FULL_NAME_TAG_NAME = "fullName";
public static final String PROTEIN_SHORT_NAME_TAG_NAME = "shortName";
public static final String GENE_TAG_NAME = "gene";
public static final String GENE_NAME_TAG_NAME = "name";
public static final String COMMENT_TAG_NAME = "comment";
public static final String COMMENT_TYPE_ATTRIBUTE = "type";
public static final String COMMENT_ALTERNATIVE_PRODUCTS_TYPE = "alternative products";
public static final String COMMENT_SEQUENCE_CAUTION_TYPE = "sequence caution";
public static final String SUBCELLULAR_LOCATION_TAG_NAME = "subcellularLocation";
public static final String LOCATION_TAG_NAME = "location";
public static final String COMMENT_TEXT_TAG_NAME = "text";
public static final String FEATURE_TAG_NAME = "feature";
public static final String FEATURE_TYPE_ATTRIBUTE = "type";
public static final String FEATURE_DESCRIPTION_ATTRIBUTE = "description";
public static final String STATUS_ATTRIBUTE = "status";
public static final String FEATURE_REF_ATTRIBUTE = "ref";
public static final String FEATURE_ID_ATTRIBUTE = "id";
public static final String EVIDENCE_ATTRIBUTE = "evidence";
public static final String FEATURE_LOCATION_TAG_NAME = "location";
public static final String FEATURE_ORIGINAL_TAG_NAME = "original";
public static final String FEATURE_VARIATION_TAG_NAME = "variation";
public static final String FEATURE_POSITION_TAG_NAME = "position";
public static final String FEATURE_LOCATION_BEGIN_TAG_NAME = "begin";
public static final String FEATURE_LOCATION_END_TAG_NAME = "end";
public static final String FEATURE_LOCATION_POSITION_ATTRIBUTE = "position";
public static final String FEATURE_POSITION_POSITION_ATTRIBUTE = "position";
public static final String THESIS_CITATION_TYPE = "thesis";
public static final String PATENT_CITATION_TYPE = "patent";
public static final String SUBMISSION_CITATION_TYPE = "submission";
public static final String ARTICLE_CITATION_TYPE = "journal article";
public static final String ONLINE_ARTICLE_CITATION_TYPE = "online journal article";
public static final String BOOK_CITATION_TYPE = "book";
public static final String UNPUBLISHED_OBSERVATION_CITATION_TYPE = "unpublished observations";
public static final String COMMENT_TYPE_DISEASE = "disease";
public static final String COMMENT_TYPE_FUNCTION = "function";
public static final String COMMENT_TYPE_COFACTOR = "cofactor";
public static final String COMMENT_TYPE_CATALYTIC_ACTIVITY = "catalytic activity";
public static final String COMMENT_TYPE_ENZYME_REGULATION = "enzyme regulation";
public static final String COMMENT_TYPE_BIOPHYSICOCHEMICAL_PROPERTIES = "biophysicochemical properties";
public static final String COMMENT_TYPE_SUBUNIT = "subunit";
public static final String COMMENT_TYPE_PATHWAY = "pathway";
public static final String COMMENT_TYPE_SUBCELLULAR_LOCATION = "subcellular location";
public static final String COMMENT_TYPE_TISSUE_SPECIFICITY = "tissue specificity";
public static final String COMMENT_TYPE_DEVELOPMENTAL_STAGE = "developmental stage";
public static final String COMMENT_TYPE_INDUCTION = "induction";
public static final String COMMENT_TYPE_DOMAIN = "domain";
public static final String COMMENT_TYPE_POST_TRANSLATIONAL_MODIFICATION = "PTM";
public static final String COMMENT_TYPE_RNA_EDITING = "RNA editing";
public static final String COMMENT_TYPE_MASS_SPECTROMETRY = "mass spectrometry";
public static final String COMMENT_TYPE_POLYMORPHISM = "polymorphism";
public static final String COMMENT_TYPE_DISRUPTION_PHENOTYPE = "disruption phenotype";
public static final String COMMENT_TYPE_ALLERGEN = "allergen";
public static final String COMMENT_TYPE_TOXIC_DOSE = "toxic dose";
public static final String COMMENT_TYPE_BIOTECHNOLOGY = "biotechnology";
public static final String COMMENT_TYPE_PHARMACEUTICAL = "pharmaceutical";
public static final String COMMENT_TYPE_MISCELLANEOUS = "miscellaneous";
public static final String COMMENT_TYPE_SIMILARITY = "similarity";
protected SimpleDateFormat dateFormat;
protected abstract UniprotGraph<I,RV,RVT,RE,RET> config(String dbFolder);
protected void importUniprot(String[] args) {
if (args.length != 3) {
System.out.println("This program expects the following parameters: \n"
+ "1. Uniprot xml filename \n"
+ "2. Bio4j DB folder \n"
+ "3. Config XML file");
} else {
long initTime = System.nanoTime();
File inFile = new File(args[0]);
File configFile = new File(args[2]);
String dbFolder = args[1];
String currentAccessionId = "";
//-------creating graph handlers---------------------
UniprotGraph<I,RV,RVT,RE,RET> graph = config(dbFolder);
BufferedWriter enzymeIdsNotFoundBuff = null;
BufferedWriter statsBuff = null;
int proteinCounter = 0;
int limitForPrintingOut = 10000;
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
// This block configures the logger with handler and formatter
fh = new FileHandler("ImportUniprot" + args[0].split("\\.")[0].replaceAll("/", "_") + ".log", false);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
System.out.println("Reading conf file...");
BufferedReader reader = new BufferedReader(new FileReader(configFile));
String line;
StringBuilder stBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stBuilder.append(line);
}
reader.close();
UniprotDataXML uniprotDataXML = new UniprotDataXML(stBuilder.toString());
//---creating writer for stats file-----
statsBuff = new BufferedWriter(new FileWriter(new File("ImportUniprotStats_" + inFile.getName().split("\\.")[0] + ".txt")));
reader = new BufferedReader(new FileReader(inFile));
StringBuilder entryStBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
if (line.trim().startsWith("<" + ENTRY_TAG_NAME)) {
while (!line.trim().startsWith("</" + ENTRY_TAG_NAME + ">")) {
entryStBuilder.append(line);
line = reader.readLine();
}
//linea final del organism
entryStBuilder.append(line);
//System.out.println("organismStBuilder.toString() = " + organismStBuilder.toString());
XMLElement entryXMLElem = new XMLElement(entryStBuilder.toString());
entryStBuilder.delete(0, entryStBuilder.length());
String modifiedDateSt = entryXMLElem.asJDomElement().getAttributeValue(ENTRY_MODIFIED_DATE_ATTRIBUTE);
String createdDateSt = entryXMLElem.asJDomElement().getAttributeValue(ENTRY_CREATED_DATE_ATTRIBUTE);
Integer version = Integer.parseInt(entryXMLElem.asJDomElement().getAttributeValue(ENTRY_VERSION_ATTRIBUTE));
String accessionSt = entryXMLElem.asJDomElement().getChildText(ENTRY_ACCESSION_TAG_NAME);
String nameSt = entryXMLElem.asJDomElement().getChildText(ENTRY_NAME_TAG_NAME);
String fullNameSt = getProteinFullName(entryXMLElem.asJDomElement().getChild(PROTEIN_TAG_NAME));
String shortNameSt = getProteinShortName(entryXMLElem.asJDomElement().getChild(PROTEIN_TAG_NAME));
if (shortNameSt == null) {
shortNameSt = "";
}
if (fullNameSt == null) {
fullNameSt = "";
}
currentAccessionId = accessionSt;
Element sequenceElem = entryXMLElem.asJDomElement().getChild(ENTRY_SEQUENCE_TAG_NAME);
String sequenceSt = sequenceElem.getText();
int seqLength = Integer.parseInt(sequenceElem.getAttributeValue(SEQUENCE_LENGTH_ATTRIBUTE));
float seqMass = Float.parseFloat(sequenceElem.getAttributeValue(SEQUENCE_MASS_ATTRIBUTE));
Protein<I,RV,RVT,RE,RET> protein = graph.addVertex(graph.Protein());
protein.set(graph.Protein().modifiedDate, parseDate(modifiedDateSt));
protein.set(graph.Protein().createdDate, parseDate(createdDateSt));
protein.set(graph.Protein().accession, accessionSt);
protein.set(graph.Protein().name, nameSt);
protein.set(graph.Protein().fullName, fullNameSt);
protein.set(graph.Protein().shortName, shortNameSt);
protein.set(graph.Protein().sequence, sequenceSt);
protein.set(graph.Protein().length, seqLength);
protein.set(graph.Protein().mass, String.valueOf(seqMass));
protein.set(graph.Protein().version, version);
//-----db references-------------
List<Element> dbReferenceList = entryXMLElem.asJDomElement().getChildren(DB_REFERENCE_TAG_NAME);
ArrayList<String> ensemblPlantsReferences = new ArrayList<>();
HashMap<String, String> reactomeReferences = new HashMap<>();
for (Element dbReferenceElem : dbReferenceList) {
String refId = dbReferenceElem.getAttributeValue("id");
switch (dbReferenceElem.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE)) {
case "Ensembl":
//looking for Ensembl node
Ensembl<I,RV,RVT,RE,RET> ensembl = null;
Optional<Ensembl<I,RV,RVT,RE,RET>> ensemblOptional = graph.ensemblIdIndex().getVertex(refId);
if(!ensemblOptional.isPresent()){
String moleculeIdSt = "";
String proteinSequenceIdSt = "";
String geneIdSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("protein sequence ID")) {
proteinSequenceIdSt = propertyElem.getAttributeValue("value");
}
if (propertyElem.getAttributeValue("type").equals("gene ID")) {
geneIdSt = propertyElem.getAttributeValue("value");
}
}
Element moleculeTag = dbReferenceElem.getChild("molecule");
if(moleculeTag != null){
moleculeIdSt = moleculeTag.getAttributeValue("id");
if(moleculeIdSt == null){
moleculeTag.getText();
if(moleculeIdSt == null){
moleculeIdSt = "";
}
}
}
ensembl = graph.addVertex(graph.Ensembl());
ensembl.set(graph.Ensembl().id, refId);
ensembl.set(graph.Ensembl().proteinSequenceId, proteinSequenceIdSt);
ensembl.set(graph.Ensembl().moleculeId, moleculeIdSt);
ensembl.set(graph.Ensembl().geneId, geneIdSt);
graph.raw().commit();
}else{
ensembl = ensemblOptional.get();
}
protein.addOutEdge(graph.ProteinEnsembl(), ensembl);
break;
case "PIR":
//looking for PIR node
PIR<I,RV,RVT,RE,RET> pIR = null;
Optional<PIR<I,RV,RVT,RE,RET>> optionalPIR = graph.pIRIdIndex().getVertex(refId);
if(!optionalPIR.isPresent()){
String entryNameSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("entry name")) {
entryNameSt = propertyElem.getAttributeValue("value");
}
}
pIR = graph.addVertex(graph.PIR());
pIR.set(graph.PIR().entryName, entryNameSt);
pIR.set(graph.PIR().id, refId);
graph.raw().commit();
}else{
pIR = optionalPIR.get();
}
protein.addOutEdge(graph.ProteinPIR(), pIR);
break;
case "UniGene":
//looking for UniGene node
UniGene<I,RV,RVT,RE,RET> uniGene = null;
Optional<UniGene<I,RV,RVT,RE,RET>> uniGeneOptional = graph.uniGeneIdIndex().getVertex(refId);
if(!uniGeneOptional.isPresent()){
uniGene = graph.addVertex(graph.UniGene());
uniGene.set(graph.UniGene().id, refId);
graph.raw().commit();
}else{
uniGene = uniGeneOptional.get();
}
protein.addOutEdge(graph.ProteinUniGene(), uniGene);
break;
case "KEGG":
//looking for Kegg node
Kegg<I,RV,RVT,RE,RET> kegg = null;
Optional<Kegg<I,RV,RVT,RE,RET>> optionalKegg = graph.keggIdIndex().getVertex(refId);
if(!optionalKegg.isPresent()){
kegg = graph.addVertex(graph.Kegg());
kegg.set(graph.Kegg().id, refId);
graph.raw().commit();
}else{
kegg = optionalKegg.get();
}
protein.addOutEdge(graph.ProteinKegg(), kegg);
break;
case "EMBL":
//looking for EMBL node
EMBL<I,RV,RVT,RE,RET> embl = null;
Optional<EMBL<I,RV,RVT,RE,RET>> optionalEMBL = graph.eMBLIdIndex().getVertex(refId);
if(!optionalEMBL.isPresent()){
String moleculeTypeSt = "";
String proteinSequenceIdSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("protein sequence ID")) {
proteinSequenceIdSt = propertyElem.getAttributeValue("value");
}
if (propertyElem.getAttributeValue("type").equals("molecule type")) {
moleculeTypeSt = propertyElem.getAttributeValue("value");
}
}
embl = graph.addVertex(graph.EMBL());
embl.set(graph.EMBL().id, refId);
embl.set(graph.EMBL().proteinSequenceId, proteinSequenceIdSt);
embl.set(graph.EMBL().moleculeType, moleculeTypeSt);
graph.raw().commit();
}else{
embl = optionalEMBL.get();
}
protein.addOutEdge(graph.ProteinEMBL(), embl);
break;
case "RefSeq":
//looking for RefSeq node
RefSeq<I,RV,RVT,RE,RET> refSeq = null;
Optional<RefSeq<I,RV,RVT,RE,RET>> optionalRefSeq = graph.refSeqIdIndex().getVertex(refId);
if(!optionalRefSeq.isPresent()){
String nucleotideSequenceIdSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("nucleotide sequence ID")) {
nucleotideSequenceIdSt = propertyElem.getAttributeValue("value");
}
}
refSeq = graph.addVertex(graph.RefSeq());
refSeq.set(graph.RefSeq().id, refId);
refSeq.set(graph.RefSeq().nucleotideSequenceId, nucleotideSequenceIdSt);
graph.raw().commit();
}else{
refSeq = optionalRefSeq.get();
}
protein.addOutEdge(graph.ProteinRefSeq(), refSeq);
break;
case "Reactome":
Element propertyElem = dbReferenceElem.getChild("property");
String pathwayName = "";
if (propertyElem.getAttributeValue("type").equals("pathway name")) {
pathwayName = propertyElem.getAttributeValue("value");
}
reactomeReferences.put(refId, pathwayName);
break;
case "EnsemblPlants":
ensemblPlantsReferences.add(refId);
break;
}
}
// proteinProperties.put(ProteinNode.ENSEMBL_PLANTS_REFERENCES_PROPERTY, convertToStringArray(ensemblPlantsReferences));
// TODO we need to decide how to store this
// //---------------gene-names-------------------
// Element geneElement = entryXMLElem.asJDomElement().getChild(GENE_TAG_NAME);
// ArrayList<String> geneNames = new ArrayList<>();
// if (geneElement != null) {
// List<Element> genesList = geneElement.getChildren(GENE_NAME_TAG_NAME);
// for (Element geneNameElem : genesList) {
// geneNames.add(geneNameElem.getText());
// }
// }
// //-----------------------------------------
//--------------reactome associations----------------
if (uniprotDataXML.getReactome()) {
for (String reactomeId : reactomeReferences.keySet()) {
ReactomeTerm<I,RV,RVT,RE,RET> reactomeTerm = null;
Optional<ReactomeTerm<I,RV,RVT,RE,RET>> optionalReactomeTerm = graph.reactomeTermIdIndex().getVertex(reactomeId);
if (!optionalReactomeTerm.isPresent()) {
reactomeTerm = graph.addVertex(graph.ReactomeTerm());
reactomeTerm.set(graph.ReactomeTerm().id, reactomeId);
reactomeTerm.set(graph.ReactomeTerm().pathwayName, reactomeReferences.get(reactomeId));
graph.raw().commit();
}else{
reactomeTerm = optionalReactomeTerm.get();
}
protein.addOutEdge(graph.ProteinReactomeTerm(), reactomeTerm);
}
}
//-------------------------------------------------------
//-----comments import---
if (uniprotDataXML.getComments()) {
importProteinComments(entryXMLElem, graph, protein, sequenceSt, uniprotDataXML);
}
//-----features import----
if (uniprotDataXML.getFeatures()) {
importProteinFeatures(entryXMLElem, graph, protein);
}
//--------------------------------datasets--------------------------------------------------
String proteinDataSetSt = entryXMLElem.asJDomElement().getAttributeValue(ENTRY_DATASET_ATTRIBUTE);
Dataset<I,RV,RVT,RE,RET> dataset = null;
Optional<Dataset<I,RV,RVT,RE,RET>> optionalDataset = graph.datasetNameIndex().getVertex(proteinDataSetSt);
if (!optionalDataset.isPresent()) {
dataset = graph.addVertex(graph.Dataset());
dataset.set(graph.Dataset().name, proteinDataSetSt);
graph.raw().commit();
}else{
dataset = optionalDataset.get();
}
protein.addOutEdge(graph.ProteinDataset(), dataset);
//---------------------------------------------------------------------------------------------
if (uniprotDataXML.getCitations()) {
importProteinCitations(entryXMLElem,
graph,
protein,
uniprotDataXML);
}
//-------------------------------keywords------------------------------------------------------
if (uniprotDataXML.getKeywords()) {
List<Element> keywordsList = entryXMLElem.asJDomElement().getChildren(KEYWORD_TAG_NAME);
for (Element keywordElem : keywordsList) {
String keywordId = keywordElem.getAttributeValue(KEYWORD_ID_ATTRIBUTE);
String keywordName = keywordElem.getText();
Keyword<I,RV,RVT,RE,RET> keyword = null;
Optional<Keyword<I,RV,RVT,RE,RET> > optionalKeyword = graph.keywordIdIndex().getVertex(keywordId);
if (!optionalKeyword.isPresent()) {
keyword = graph.addVertex(graph.Keyword());
keyword.set(graph.Keyword().id, keywordId);
keyword.set(graph.Keyword().name, keywordName);
graph.raw().commit();
}else{
keyword = optionalKeyword.get();
}
protein.addOutEdge(graph.ProteinKeyword(), keyword);
}
}
//---------------------------------------------------------------------------------------
for (Element dbReferenceElem : dbReferenceList) {
//-------------------------------INTERPRO------------------------------------------------------
if (dbReferenceElem.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals(INTERPRO_DB_REFERENCE_TYPE)) {
if (uniprotDataXML.getInterpro()) {
String interproId = dbReferenceElem.getAttributeValue(DB_REFERENCE_ID_ATTRIBUTE);
Interpro<I,RV,RVT,RE,RET> interpro = null;
Optional<Interpro<I,RV,RVT,RE,RET>> optionalInterpro = graph.interproIdIndex().getVertex(interproId);
if (!optionalInterpro.isPresent()) {
String interproEntryNameSt = "";
List<Element> properties = dbReferenceElem.getChildren(DB_REFERENCE_PROPERTY_TAG_NAME);
for (Element prop : properties) {
if (prop.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals(INTERPRO_ENTRY_NAME)) {
interproEntryNameSt = prop.getAttributeValue(DB_REFERENCE_VALUE_ATTRIBUTE);
break;
}
}
interpro = graph.addVertex(graph.Interpro());
interpro.set(graph.Interpro().id, interproId);
interpro.set(graph.Interpro().name, interproEntryNameSt);
graph.raw().commit();
}else{
interpro = optionalInterpro.get();
}
protein.addOutEdge(graph.ProteinInterpro(), interpro);
}
} //-------------------------------PFAM------------------------------------------------------
else if (dbReferenceElem.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals("Pfam")) {
if (uniprotDataXML.getPfam()) {
String pfamId = dbReferenceElem.getAttributeValue(DB_REFERENCE_ID_ATTRIBUTE);
Pfam<I,RV,RVT,RE,RET> pfam = null;
Optional<Pfam<I,RV,RVT,RE,RET>> optionalPfam = graph.pfamIdIndex().getVertex(pfamId);
if (!optionalPfam.isPresent()) {
String pfamEntryNameSt = "";
List<Element> properties = dbReferenceElem.getChildren(DB_REFERENCE_PROPERTY_TAG_NAME);
for (Element prop : properties) {
if (prop.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals("entry name")) {
pfamEntryNameSt = prop.getAttributeValue(DB_REFERENCE_VALUE_ATTRIBUTE);
break;
}
}
pfam = graph.addVertex(graph.Pfam());
pfam.set(graph.Pfam().id, pfamId);
pfam.set(graph.Pfam().name, pfamEntryNameSt);
graph.raw().commit();
}else{
pfam = optionalPfam.get();
}
protein.addOutEdge(graph.ProteinPfam(), pfam);
}
}
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//--------------------------------geneLocation-------------------------------------------
List<Element> geneLocationElements = entryXMLElem.asJDomElement().getChildren(GENE_LOCATION_TAG_NAME);
for (Element geneLocationElem : geneLocationElements){
String geneLocationTypeSt = geneLocationElem.getAttributeValue("type");
String geneLocationNameSt = geneLocationElem.getChildText("name");
if(geneLocationNameSt == null){
geneLocationNameSt = "";
}
Optional<GeneLocation<I,RV,RVT,RE,RET>> optionalGeneLocation = graph.geneLocationNameIndex().getVertex(geneLocationTypeSt);
GeneLocation<I,RV,RVT,RE,RET> geneLocation = null;
if(optionalGeneLocation.isPresent()){
geneLocation = optionalGeneLocation.get();
}else{
geneLocation = graph.addVertex(graph.GeneLocation());
geneLocation.set(graph.GeneLocation().name, geneLocationTypeSt);
graph.raw().commit();
}
ProteinGeneLocation<I,RV,RVT,RE,RET> proteinGeneLocation = protein.addOutEdge(graph.ProteinGeneLocation(), geneLocation);
proteinGeneLocation.set(graph.ProteinGeneLocation().name, geneLocationNameSt);
}
//---------------------------------------------------------------------------------------
//--------------------------------organism-----------------------------------------------
String scName, commName, synName;
scName = "";
commName = "";
synName = "";
Element organismElem = entryXMLElem.asJDomElement().getChild(ORGANISM_TAG_NAME);
List<Element> organismNames = organismElem.getChildren(ORGANISM_NAME_TAG_NAME);
for (Element element : organismNames) {
String type = element.getAttributeValue(ORGANISM_NAME_TYPE_ATTRIBUTE);
switch (type) {
case ORGANISM_SCIENTIFIC_NAME_TYPE:
scName = element.getText();
break;
case ORGANISM_COMMON_NAME_TYPE:
commName = element.getText();
break;
case ORGANISM_SYNONYM_NAME_TYPE:
synName = element.getText();
break;
}
}
Organism<I,RV,RVT,RE,RET> organism = null;
Optional<Organism<I,RV,RVT,RE,RET>> organismOptional = graph.organismScientificNameIndex().getVertex(scName);
if (!organismOptional.isPresent()) {
organism = graph.addVertex(graph.Organism());
organism.set(graph.Organism().scientificName, scName);
organism.set(graph.Organism().commonName, commName);
organism.set(graph.Organism().synonymName, synName);
graph.raw().commit();
/* TODO see what to do with the NCBI taxonomy ID, just link to the NCBI tax node or also store
the id as an attribute
*/
// List<Element> organismDbRefElems = organismElem.getChildren(DB_REFERENCE_TAG_NAME);
// boolean ncbiIdFound = false;
// if (organismDbRefElems != null) {
// for (Element dbRefElem : organismDbRefElems) {
// String t = dbRefElem.getAttributeValue("type");
// if (t.equals("NCBI Taxonomy")) {
// organismProperties.put(OrganismNode.NCBI_TAXONOMY_ID_PROPERTY, dbRefElem.getAttributeValue("id"));
// ncbiIdFound = true;
// break;
// }
// }
// }
// if (!ncbiIdFound) {
// organismProperties.put(OrganismNode.NCBI_TAXONOMY_ID_PROPERTY, "");
// }
Element lineage = entryXMLElem.asJDomElement().getChild("organism").getChild("lineage");
List<Element> taxons = lineage.getChildren("taxon");
Element firstTaxonElem = taxons.get(0);
Taxon<I,RV,RVT,RE,RET> firstTaxon = null;
Optional<Taxon<I,RV,RVT,RE,RET>> firstTaxonOptional = graph.taxonNameIndex().getVertex(firstTaxonElem.getText());
if (!firstTaxonOptional.isPresent()) {
String firstTaxonName = firstTaxonElem.getText();
firstTaxon = graph.addVertex(graph.Taxon());
firstTaxon.set(graph.Taxon().name, firstTaxonName);
graph.raw().commit();
}else{
firstTaxon = firstTaxonOptional.get();
}
Taxon<I,RV,RVT,RE,RET> lastTaxon = firstTaxon;
for (int i = 1; i < taxons.size(); i++) {
String taxonName = taxons.get(i).getText();
Taxon<I,RV,RVT,RE,RET> currentTaxon = null;
Optional<Taxon<I,RV,RVT,RE,RET>> currentTaxonOptional = graph.taxonNameIndex().getVertex(taxonName);
if (!currentTaxonOptional.isPresent()) {
currentTaxon = graph.addVertex(graph.Taxon());
currentTaxon.set(graph.Taxon().name, taxonName);
graph.raw().commit();
lastTaxon.addOutEdge(graph.TaxonParent(), currentTaxon);
}else{
currentTaxon = currentTaxonOptional.get();
}
lastTaxon = currentTaxon;
}
organism.addOutEdge(graph.OrganismTaxon(), lastTaxon);
}else{
organism = organismOptional.get();
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
protein.addOutEdge(graph.ProteinOrganism(), organism);
proteinCounter++;
if ((proteinCounter % limitForPrintingOut) == 0) {
String countProteinsSt = proteinCounter + " proteins inserted!!";
logger.log(Level.INFO, countProteinsSt);
}
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, ("Exception retrieving protein " + currentAccessionId));
logger.log(Level.SEVERE, e.getMessage());
StackTraceElement[] trace = e.getStackTrace();
for (StackTraceElement stackTraceElement : trace) {
logger.log(Level.SEVERE, stackTraceElement.toString());
}
} finally {
try {
// shutdown, makes sure all changes are written to disk
graph.raw().shutdown();
// closing logger file handler
fh.close();
//-----------------writing stats file---------------------
long elapsedTime = System.nanoTime() - initTime;
long elapsedSeconds = Math.round((elapsedTime / 1000000000.0));
long hours = elapsedSeconds / 3600;
long minutes = (elapsedSeconds % 3600) / 60;
long seconds = (elapsedSeconds % 3600) % 60;
statsBuff.write("Statistics for program ImportUniprot:\nInput file: " + inFile.getName()
+ "\nThere were " + proteinCounter + " proteins inserted.\n"
+ "The elapsed time was: " + hours + "h " + minutes + "m " + seconds + "s\n");
//---closing stats writer---
statsBuff.close();
} catch (IOException ex) {
Logger.getLogger(ImportUniprot.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private void importProteinFeatures(XMLElement entryXMLElem,
UniprotGraph<I,RV,RVT,RE,RET> graph,
Protein<I,RV,RVT,RE,RET> protein) {
//--------------------------------features----------------------------------------------------
List<Element> featuresList = entryXMLElem.asJDomElement().getChildren(FEATURE_TAG_NAME);
for (Element featureElem : featuresList) {
String featureTypeSt = featureElem.getAttributeValue(FEATURE_TYPE_ATTRIBUTE);
FeatureType<I,RV,RVT,RE,RET> feature = null;
Optional<FeatureType<I,RV,RVT,RE,RET>> optionalFeature = graph.featureTypeNameIndex().getVertex(featureTypeSt);
if (!optionalFeature.isPresent()) {
feature = graph.addVertex(graph.FeatureType());
feature.set(graph.FeatureType().name, featureTypeSt);
graph.raw().commit();
}else{
feature = optionalFeature.get();
}
String featureDescSt = featureElem.getAttributeValue(FEATURE_DESCRIPTION_ATTRIBUTE);
if (featureDescSt == null) {
featureDescSt = "";
}
String featureIdSt = featureElem.getAttributeValue(FEATURE_ID_ATTRIBUTE);
if (featureIdSt == null) {
featureIdSt = "";
}
String featureStatusSt = featureElem.getAttributeValue(STATUS_ATTRIBUTE);
if (featureStatusSt == null) {
featureStatusSt = "";
}
String featureEvidenceSt = featureElem.getAttributeValue(EVIDENCE_ATTRIBUTE);
if (featureEvidenceSt == null) {
featureEvidenceSt = "";
}
Element locationElem = featureElem.getChild(FEATURE_LOCATION_TAG_NAME);
Element positionElem = locationElem.getChild(FEATURE_POSITION_TAG_NAME);
Integer beginFeature = null;
Integer endFeature = null;
if (positionElem != null) {
String tempValue = positionElem.getAttributeValue(FEATURE_POSITION_POSITION_ATTRIBUTE);
if (tempValue == null) {
beginFeature = -1;
}else{
beginFeature = Integer.parseInt(tempValue);
}
endFeature = beginFeature;
} else {
String tempValue = locationElem.getChild(FEATURE_LOCATION_BEGIN_TAG_NAME).getAttributeValue(FEATURE_LOCATION_POSITION_ATTRIBUTE);
if(tempValue == null){
beginFeature = null;
}else{
beginFeature = Integer.parseInt(tempValue);
}
tempValue = locationElem.getChild(FEATURE_LOCATION_END_TAG_NAME).getAttributeValue(FEATURE_LOCATION_POSITION_ATTRIBUTE);
if(tempValue == null){
endFeature = null;
}else{
endFeature = Integer.parseInt(tempValue);
}
}
if (beginFeature == null) {
beginFeature = -1;
}
if (endFeature == null) {
endFeature = -1;
}
String originalSt = featureElem.getChildText(FEATURE_ORIGINAL_TAG_NAME);
String variationSt = featureElem.getChildText(FEATURE_VARIATION_TAG_NAME);
if (originalSt == null) {
originalSt = "";
}
if (variationSt == null) {
variationSt = "";
}
String featureRefSt = featureElem.getAttributeValue(FEATURE_REF_ATTRIBUTE);
if (featureRefSt == null) {
featureRefSt = "";
}
ProteinFeature<I,RV,RVT,RE,RET> proteinFeature = protein.addOutEdge(graph.ProteinFeature(), feature);
addPropertiesToProteinFeatureRelationship(graph, proteinFeature, featureIdSt, featureDescSt, featureEvidenceSt,
featureStatusSt, beginFeature, endFeature, originalSt, variationSt, featureRefSt);
}
}
private void importProteinComments(XMLElement entryXMLElem,
UniprotGraph<I,RV,RVT,RE,RET> graph,
Protein<I,RV,RVT,RE,RET> protein,
String proteinSequence,
UniprotDataXML uniprotDataXML) {
List<Element> comments = entryXMLElem.asJDomElement().getChildren(COMMENT_TAG_NAME);
for (Element commentElem : comments) {
String commentTypeSt = commentElem.getAttributeValue(COMMENT_TYPE_ATTRIBUTE);
Element textElem = commentElem.getChild("text");
String commentTextSt = "";
String commentStatusSt = "";
String commentEvidenceSt = "";
if (textElem != null) {
commentTextSt = textElem.getText();
commentStatusSt = textElem.getAttributeValue("status");
if (commentStatusSt == null) {
commentStatusSt = "";
}
commentEvidenceSt = textElem.getAttributeValue("evidence");
if (commentEvidenceSt == null) {
commentEvidenceSt = "";
}
}
//-----------------COMMENT TYPE NODE RETRIEVING/CREATION----------------------
Optional<CommentType<I,RV,RVT,RE,RET>> commentOptional = graph.commentTypeNameIndex().getVertex(commentTypeSt);
CommentType<I,RV,RVT,RE,RET> comment = null;
if(!commentOptional.isPresent()){
comment = graph.addVertex(graph.CommentType());
comment.set(graph.CommentType().name, commentTypeSt);
graph.raw().commit();
}else{
comment = commentOptional.get();
}
boolean createStandardProteinComment = false;
switch (commentTypeSt) {
case COMMENT_TYPE_FUNCTION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_COFACTOR:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_CATALYTIC_ACTIVITY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_ENZYME_REGULATION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_DISEASE:
Element diseaseElement = commentElem.getChild("disease");
if(diseaseElement != null){
String diseaseId = diseaseElement.getAttributeValue("id");
String diseaseName = diseaseElement.getChildText("name");
String diseaseDescription = diseaseElement.getChildText("description");
String diseaseAcronym = diseaseElement.getChildText("acronym");
if(diseaseId != null){
Disease<I,RV,RVT,RE,RET> disease = null;
Optional<Disease<I,RV,RVT,RE,RET>> diseaseOptional = graph.diseaseIdIndex().getVertex(diseaseId);
if(!diseaseOptional.isPresent()){
disease = graph.addVertex(graph.Disease());
disease.set(graph.Disease().name, diseaseName);
disease.set(graph.Disease().id, diseaseId);
disease.set(graph.Disease().acronym, diseaseAcronym);
disease.set(graph.Disease().description, diseaseDescription);
graph.raw().commit();
}else{
disease = diseaseOptional.get();
}
ProteinDisease<I,RV,RVT,RE,RET> proteinDisease = protein.addOutEdge(graph.ProteinDisease(), disease);
proteinDisease.set(graph.ProteinDisease().text, commentTextSt);
proteinDisease.set(graph.ProteinDisease().status, commentStatusSt);
proteinDisease.set(graph.ProteinDisease().evidence, commentEvidenceSt);
}
}
break;
case COMMENT_TYPE_TISSUE_SPECIFICITY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_TOXIC_DOSE:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_BIOTECHNOLOGY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_SUBUNIT:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_POLYMORPHISM:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_DOMAIN:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_POST_TRANSLATIONAL_MODIFICATION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_DISRUPTION_PHENOTYPE:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_BIOPHYSICOCHEMICAL_PROPERTIES:
String phDependenceSt = commentElem.getChildText("phDependence");
String temperatureDependenceSt = commentElem.getChildText("temperatureDependence");
if (phDependenceSt == null) {
phDependenceSt = "";
}
if (temperatureDependenceSt == null) {
temperatureDependenceSt = "";
}
String absorptionMaxSt = "";
String absorptionTextSt = "";
Element absorptionElem = commentElem.getChild("absorption");
if (absorptionElem != null) {
absorptionMaxSt = absorptionElem.getChildText("max");
absorptionTextSt = absorptionElem.getChildText("text");
if (absorptionMaxSt == null) {
absorptionMaxSt = "";
}
if (absorptionTextSt == null) {
absorptionTextSt = "";
}
}
String kineticsSt = "";
Element kineticsElem = commentElem.getChild("kinetics");
if (kineticsElem != null) {
kineticsSt = new XMLElement(kineticsElem).toString();
}
String redoxPotentialSt = "";
String redoxPotentialEvidenceSt = "";
Element redoxPotentialElem = commentElem.getChild("redoxPotential");
if (redoxPotentialElem != null) {
redoxPotentialSt = redoxPotentialElem.getText();
redoxPotentialEvidenceSt = redoxPotentialElem.getAttributeValue("evidence");
if (redoxPotentialSt == null) {
redoxPotentialSt = "";
}
if (redoxPotentialEvidenceSt == null) {
redoxPotentialEvidenceSt = "";
}
}
ProteinComment<I,RV,RVT,RE,RET> proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
proteinComment.set(graph.ProteinComment().temperatureDependence, temperatureDependenceSt);
proteinComment.set(graph.ProteinComment().phDependence, phDependenceSt);
proteinComment.set(graph.ProteinComment().kineticsXML, kineticsSt);
proteinComment.set(graph.ProteinComment().absorptionMax, absorptionMaxSt);
proteinComment.set(graph.ProteinComment().absorptionText, absorptionTextSt);
proteinComment.set(graph.ProteinComment().redoxPotentialEvidence, redoxPotentialEvidenceSt);
proteinComment.set(graph.ProteinComment().redoxPotential, redoxPotentialSt);
break;
case COMMENT_TYPE_ALLERGEN:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_PATHWAY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_INDUCTION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_SUBCELLULAR_LOCATION:
if (uniprotDataXML.getSubcellularLocations()) {
List<Element> subcLocations = commentElem.getChildren(SUBCELLULAR_LOCATION_TAG_NAME);
for (Element subcLocation : subcLocations) {
List<Element> locations = subcLocation.getChildren(LOCATION_TAG_NAME);
Element firstLocationElem = locations.get(0);
String firstLocationSt = firstLocationElem.getTextTrim();
SubcellularLocation<I,RV,RVT,RE,RET> lastLocation = null;
Optional<SubcellularLocation<I,RV,RVT,RE,RET>> lastLocationOptional = graph.subcellularLocationNameIndex().getVertex(firstLocationSt);
if(!lastLocationOptional.isPresent()){
lastLocation = graph.addVertex(graph.SubcellularLocation());
lastLocation.set(graph.SubcellularLocation().name, firstLocationSt);
graph.raw().commit();
}else{
lastLocation = lastLocationOptional.get();
}
for (int i = 1; i < locations.size(); i++) {
SubcellularLocation<I,RV,RVT,RE,RET> tempLocation = null;
String tempLocationSt = locations.get(i).getTextTrim();
Optional<SubcellularLocation<I,RV,RVT,RE,RET>> tempLocationOptional = graph.subcellularLocationNameIndex().getVertex(tempLocationSt);
if(!tempLocationOptional.isPresent()){
tempLocation = graph.addVertex(graph.SubcellularLocation());
tempLocation.set(graph.SubcellularLocation().name, tempLocationSt);
graph.raw().commit();
}else{
tempLocation = tempLocationOptional.get();
}
tempLocation.addOutEdge(graph.SubcellularLocationParent(), lastLocation);
lastLocation = tempLocation;
}
Element lastLocationElem = locations.get(locations.size() - 1);
String evidenceSt = lastLocationElem.getAttributeValue(EVIDENCE_ATTRIBUTE);
String statusSt = lastLocationElem.getAttributeValue(STATUS_ATTRIBUTE);
String topologyStatusSt = "";
String topologySt = "";
Element topologyElem = subcLocation.getChild("topology");
if (topologyElem != null) {
topologySt = topologyElem.getText();
topologyStatusSt = topologyElem.getAttributeValue("status");
}
if (topologyStatusSt == null) {
topologyStatusSt = "";
}
if (topologySt == null) {
topologySt = "";
}
if (evidenceSt == null) {
evidenceSt = "";
}
if (statusSt == null) {
statusSt = "";
}
ProteinSubcellularLocation<I,RV,RVT,RE,RET> proteinSubcellularLocation = protein.addOutEdge(graph.ProteinSubcellularLocation(), lastLocation);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().evidence, evidenceSt);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().status, statusSt);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().topology, topologySt);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().topologyStatus, topologyStatusSt);
}
}
break;
case COMMENT_ALTERNATIVE_PRODUCTS_TYPE:
if (uniprotDataXML.getIsoforms()) {
List<Element> eventList = commentElem.getChildren("event");
List<Element> isoformList = commentElem.getChildren("isoform");
for (Element isoformElem : isoformList) {
String isoformIdSt = isoformElem.getChildText("id");
String isoformNoteSt = isoformElem.getChildText("note");
String isoformNameSt = isoformElem.getChildText("name");
String isoformSeqSt = "";
Element isoSeqElem = isoformElem.getChild("sequence");
if (isoSeqElem != null) {
String isoSeqTypeSt = isoSeqElem.getAttributeValue("type");
if (isoSeqTypeSt.equals("displayed")) {
isoformSeqSt = proteinSequence;
}
}
if (isoformNoteSt == null) {
isoformNoteSt = "";
}
if (isoformNameSt == null) {
isoformNameSt = "";
}
Optional<Isoform<I,RV,RVT,RE,RET>> isoformOptional = graph.isoformIdIndex().getVertex(isoformIdSt);
Isoform<I,RV,RVT,RE,RET> isoform;
if(!isoformOptional.isPresent()){
isoform = graph.addVertex(graph.Isoform());
isoform.set(graph.Isoform().name, isoformNameSt);
isoform.set(graph.Isoform().note, isoformNoteSt);
isoform.set(graph.Isoform().sequence, isoformSeqSt);
isoform.set(graph.Isoform().id, isoformIdSt);
graph.raw().commit();
//Adding edge from Protein to Isoform
protein.addOutEdge(graph.ProteinIsoform(), isoform);
}else{
isoform = isoformOptional.get();
}
graph.raw().commit();
for (Element eventElem : eventList) {
String eventTypeSt = eventElem.getAttributeValue("type");
Optional<AlternativeProduct<I,RV,RVT,RE,RET>> alternativeProductOptional = graph.alternativeProductNameIndex().getVertex(eventTypeSt);
AlternativeProduct<I,RV,RVT,RE,RET> alternativeProduct;
if(alternativeProductOptional.isPresent()){
alternativeProduct = alternativeProductOptional.get();
}else{
alternativeProduct = graph.addVertex(graph.AlternativeProduct());
alternativeProduct.set(graph.AlternativeProduct().name, eventTypeSt);
graph.raw().commit();
}
isoform.addOutEdge(graph.IsoformEventGenerator(), alternativeProduct);
}
}
}
break;
case COMMENT_SEQUENCE_CAUTION_TYPE:
Element conflictElem = commentElem.getChild("conflict");
if (conflictElem != null) {
String conflictTypeSt = conflictElem.getAttributeValue("type");
String resourceSt = "";
String idSt = "";
String versionSt = "";
ArrayList<String> positionsList = new ArrayList<>();
Element sequenceElem = conflictElem.getChild("sequence");
if (sequenceElem != null) {
resourceSt = sequenceElem.getAttributeValue("resource");
if (resourceSt == null) {
resourceSt = "";
}
idSt = sequenceElem.getAttributeValue("id");
if (idSt == null) {
idSt = "";
}
versionSt = sequenceElem.getAttributeValue("version");
if (versionSt == null) {
versionSt = "";
}
}
Element locationElem = commentElem.getChild("location");
if (locationElem != null) {
Element positionElem = locationElem.getChild("position");
if (positionElem != null) {
String tempPos = positionElem.getAttributeValue("position");
if (tempPos != null) {
positionsList.add(tempPos);
}
}
}
// System.out.println("conflictTypeSt = " + conflictTypeSt);
// System.out.println("sequenceCautionNameIndex = " + graph.sequenceCautionNameIndex());
Optional<SequenceCaution<I,RV,RVT,RE,RET>> sequenceCautionOptional = graph.sequenceCautionNameIndex().getVertex(conflictTypeSt);
SequenceCaution<I,RV,RVT,RE,RET> sequenceCaution;
if(!sequenceCautionOptional.isPresent()){
sequenceCaution = graph.addVertex(graph.SequenceCaution());
sequenceCaution.set(graph.SequenceCaution().name, conflictTypeSt);
graph.raw().commit();
}else{
sequenceCaution = sequenceCautionOptional.get();
}
if (positionsList.size() > 0) {
for (String tempPosition : positionsList) {
ProteinSequenceCaution<I,RV,RVT,RE,RET> proteinSequenceCaution = protein.addOutEdge(graph.ProteinSequenceCaution(), sequenceCaution);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().evidence, commentEvidenceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().status, commentStatusSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().text, commentTextSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().id, idSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().resource, resourceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().version, versionSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().position, tempPosition);
}
} else {
ProteinSequenceCaution<I,RV,RVT,RE,RET> proteinSequenceCaution = protein.addOutEdge(graph.ProteinSequenceCaution(), sequenceCaution);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().evidence, commentEvidenceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().status, commentStatusSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().text, commentTextSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().id, idSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().resource, resourceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().version, versionSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().position, "");
}
}
break;
case COMMENT_TYPE_DEVELOPMENTAL_STAGE:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_MISCELLANEOUS:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_SIMILARITY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_RNA_EDITING:
List<Element> locationsList = commentElem.getChildren("location");
for (Element tempLoc : locationsList) {
String positionSt = tempLoc.getChild("position").getAttributeValue("position");
proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
proteinComment.set(graph.ProteinComment().position, positionSt);
}
break;
case COMMENT_TYPE_PHARMACEUTICAL:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_MASS_SPECTROMETRY:
String methodSt = commentElem.getAttributeValue("method");
String massSt = commentElem.getAttributeValue("mass");
if (methodSt == null) {
methodSt = "";
}
if (massSt == null) {
massSt = "";
}
locationsList = commentElem.getChildren("location");
for (Element tempLoc : locationsList) {
String positionSt = "";
Element positionElem = tempLoc.getChild("position");
if(positionElem != null){
positionSt = positionElem.getAttributeValue("position");
if(positionSt == null){
positionSt = "";
}
}
String beginSt = "";
String endSt = "";
if (tempLoc != null) {
Element beginElem = tempLoc.getChild("begin");
Element endElem = tempLoc.getChild("end");
if (beginElem != null) {
beginSt = beginElem.getAttributeValue("position");
}
if (endElem != null) {
endSt = endElem.getAttributeValue("position");
}
if(endSt == null || endSt.isEmpty()){
endSt = "-1";
}
if(beginSt == null || beginSt.isEmpty()){
beginSt = "-1";
}
}
proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
proteinComment.set(graph.ProteinComment().position, positionSt);
proteinComment.set(graph.ProteinComment().end, Integer.parseInt(endSt));
proteinComment.set(graph.ProteinComment().begin, Integer.parseInt(beginSt));
proteinComment.set(graph.ProteinComment().method, methodSt);
proteinComment.set(graph.ProteinComment().mass, massSt);
}
break;
}
if(createStandardProteinComment){
ProteinComment<I,RV,RVT,RE,RET> proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
}
}
}
private void addPropertiesToProteinFeatureRelationship(UniprotGraph<I,RV,RVT,RE,RET> graph, ProteinFeature<I,RV,RVT,RE,RET> proteinFeature,
String id, String description, String evidence, String status, int begin, int end,
String original, String variation, String ref){
proteinFeature.set(graph.ProteinFeature().description, description);
proteinFeature.set(graph.ProteinFeature().id, id);
proteinFeature.set(graph.ProteinFeature().evidence, evidence);
proteinFeature.set(graph.ProteinFeature().status, status);
proteinFeature.set(graph.ProteinFeature().begin, begin);
proteinFeature.set(graph.ProteinFeature().end, end);
proteinFeature.set(graph.ProteinFeature().original, original);
proteinFeature.set(graph.ProteinFeature().variation, variation);
proteinFeature.set(graph.ProteinFeature().ref, ref);
}
private static String getProteinFullName(Element proteinElement) {
if (proteinElement == null) {
return "";
} else {
Element recElem = proteinElement.getChild(PROTEIN_RECOMMENDED_NAME_TAG_NAME);
if (recElem == null) {
return "";
} else {
return recElem.getChildText(PROTEIN_FULL_NAME_TAG_NAME);
}
}
}
private static String getProteinShortName(Element proteinElement) {
if (proteinElement == null) {
return "";
} else {
Element recElem = proteinElement.getChild(PROTEIN_RECOMMENDED_NAME_TAG_NAME);
if (recElem == null) {
return "";
} else {
return recElem.getChildText(PROTEIN_SHORT_NAME_TAG_NAME);
}
}
}
private void importProteinCitations(XMLElement entryXMLElem,
UniprotGraph<I,RV,RVT,RE,RET> graph,
Protein<I,RV,RVT,RE,RET> protein,
UniprotDataXML uniprotDataXML) {
List<Element> referenceList = entryXMLElem.asJDomElement().getChildren(REFERENCE_TAG_NAME);
for (Element referenceElement : referenceList) {
List<Element> citationsList = referenceElement.getChildren(CITATION_TAG_NAME);
for (Element citation : citationsList) {
String citationType = citation.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE);
List<Person<I,RV,RVT,RE,RET>> authorsPerson = new ArrayList<>();
List<Consortium<I,RV,RVT,RE,RET>> authorsConsortium = new ArrayList<>();
List<Element> authorPersonElems = citation.getChild("authorList").getChildren("person");
List<Element> authorConsortiumElems = citation.getChild("authorList").getChildren("consortium");
for (Element personElement : authorPersonElems) {
Person<I,RV,RVT,RE,RET> person = null;
String personName = personElement.getAttributeValue("name");
Optional<Person<I,RV,RVT,RE,RET>> optionalPerson = graph.personNameIndex().getVertex(personName);
if(!optionalPerson.isPresent()){
person = graph.addVertex(graph.Person());
person.set(graph.Person().name, personName);
graph.raw().commit();
}else{
person = optionalPerson.get();
}
}
for (Element consortiumElement : authorConsortiumElems) {
Consortium<I,RV,RVT,RE,RET> consortium = null;
String consortiumName = consortiumElement.getAttributeValue("name");
Optional<Consortium<I,RV,RVT,RE,RET>> optionalConsortium = graph.consortiumNameIndex().getVertex(consortiumName);
if(!optionalConsortium.isPresent()){
consortium = graph.addVertex(graph.Consortium());
consortium.set(graph.Consortium().name, consortiumName);
graph.raw().commit();
}else{
consortium = optionalConsortium.get();
}
}
//----------------------------------------------------------------------------
//-----------------------------THESIS-----------------------------------------
switch (citationType) {
case THESIS_CITATION_TYPE:
if (uniprotDataXML.getThesis()) {
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}else{
Thesis<I,RV,RVT,RE,RET> thesis = null;
Optional<Thesis<I,RV,RVT,RE,RET>> optionalThesis = graph.thesisTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalThesis.isPresent()){
thesis = graph.addVertex(graph.Thesis());
thesis.set(graph.Thesis().title, titleSt);
//-----------institute-----------------------------
String instituteSt = citation.getAttributeValue("institute");
String countrySt = citation.getAttributeValue("country");
reference = graph.addVertex(graph.Reference());
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceThesis(), thesis);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
if (instituteSt != null) {
Institute<I,RV,RVT,RE,RET> institute = null;
Optional<Institute<I,RV,RVT,RE,RET>> optionalInstitute = graph.instituteNameIndex().getVertex(instituteSt);
if(!optionalInstitute.isPresent()){
institute = graph.addVertex(graph.Institute());
institute.set(graph.Institute().name, instituteSt);
graph.raw().commit();
}else{
institute = optionalInstitute.get();
}
if (countrySt != null) {
Country<I,RV,RVT,RE,RET> country = null;
Optional<Country<I,RV,RVT,RE,RET>> optionalCountry = graph.countryNameIndex().getVertex(countrySt);
if(!optionalCountry.isPresent()){
country = graph.addVertex(graph.Country());
country.set(graph.Country().name, countrySt);
graph.raw().commit();
}else{
country = optionalCountry.get();
}
institute.addOutEdge(graph.InstituteCountry(), country);
}
thesis.addOutEdge(graph.ThesisInstitute(), institute);
}
}else{
thesis = optionalThesis.get();
reference = thesis.referenceThesis_inV();
}
//--protein reference citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------PATENT-----------------------------------------
break;
case PATENT_CITATION_TYPE:
if (uniprotDataXML.getPatents()) {
String numberSt = citation.getAttributeValue("number");
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}
if (numberSt == null) {
numberSt = "";
}
if (!numberSt.equals("")) {
Patent<I,RV,RVT,RE,RET> patent = null;
Optional<Patent<I,RV,RVT,RE,RET>> optionalPatent = graph.patentNumberIndex().getVertex(numberSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalPatent.isPresent()){
patent = graph.addVertex(graph.Patent());
patent.set(graph.Patent().number, numberSt);
patent.set(graph.Patent().title, titleSt);
graph.raw().commit();
reference = graph.addVertex(graph.Reference());
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferencePatent(), patent);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
}else{
patent = optionalPatent.get();
reference = patent.referencePatent_inV();
}
//--protein citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------SUBMISSION-----------------------------------------
break;
case SUBMISSION_CITATION_TYPE:
if (uniprotDataXML.getSubmissions()) {
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
String dbSt = citation.getAttributeValue("db");
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}else{
Submission<I,RV,RVT,RE,RET> submission = null;
Optional<Submission<I,RV,RVT,RE,RET>> optionalSubmission = graph.submissionTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalSubmission.isPresent()){
submission = graph.addVertex(graph.Submission());
submission.set(graph.Submission().title, titleSt);
graph.raw().commit();
reference = graph.addVertex(graph.Reference());
reference.set(graph.Reference().date, dateSt);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
for(Consortium<I,RV,RVT,RE,RET> consortium : authorsConsortium){
reference.addOutEdge(graph.ReferenceAuthorConsortium(), consortium);
}
if (dbSt != null) {
DB<I,RV,RVT,RE,RET> db = null;
Optional<DB<I,RV,RVT,RE,RET>> optionalDB = graph.dbNameIndex().getVertex(dbSt);
if(!optionalDB.isPresent()){
db = graph.DB().from(graph.raw().addVertex(null));
db.set(graph.DB().name, dbSt);
graph.raw().commit();
}else{
db = optionalDB.get();
}
//-----submission db relationship-----
submission.addOutEdge(graph.SubmissionDB(), db);
}
reference.addOutEdge(graph.ReferenceSubmission(), submission);
}else{
submission = optionalSubmission.get();
reference = submission.referenceSubmission_inV();
}
//--protein citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------BOOK-----------------------------------------
break;
case BOOK_CITATION_TYPE:
if (uniprotDataXML.getBooks()) {
String nameSt = citation.getAttributeValue("name");
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
String publisherSt = citation.getAttributeValue("publisher");
String firstSt = citation.getAttributeValue("first");
String lastSt = citation.getAttributeValue("last");
String citySt = citation.getAttributeValue("city");
String volumeSt = citation.getAttributeValue("volume");
if (nameSt == null) {
nameSt = "";
}
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}
if (publisherSt == null) {
publisherSt = "";
}
if (firstSt == null) {
firstSt = "";
}
if (lastSt == null) {
lastSt = "";
}
if (citySt == null) {
citySt = "";
}
if (volumeSt == null) {
volumeSt = "";
}
Book<I,RV,RVT,RE,RET> book = null;
Optional<Book<I,RV,RVT,RE,RET>> optionalBook = graph.bookNameIndex().getVertex(nameSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalBook.isPresent()){
book = graph.addVertex(graph.Book());
book.set(graph.Book().name, nameSt);
graph.raw().commit();
reference = graph.addVertex(graph.Reference());
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceBook(), book);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//---editor association-----
Element editorListElem = citation.getChild("editorList");
if (editorListElem != null) {
List<Element> editorsElems = editorListElem.getChildren("person");
for (Element personElement : editorsElems) {
Person<I,RV,RVT,RE,RET> editor = null;
String personName = personElement.getAttributeValue("name");
Optional<Person<I,RV,RVT,RE,RET>> optionalPerson = graph.personNameIndex().getVertex(personName);
if(!optionalPerson.isPresent()){
editor = graph.addVertex(graph.Person());
editor.set(graph.Person().name, personName);
graph.raw().commit();
}else{
editor = optionalPerson.get();
}
book.addOutEdge(graph.BookEditor(), editor);
}
}
//----publisher--
if (!publisherSt.equals("")) {
Publisher<I,RV,RVT,RE,RET> publisher = null;
Optional<Publisher<I,RV,RVT,RE,RET>> optionalPublisher = graph.publisherNameIndex().getVertex(publisherSt);
if(!optionalPublisher.isPresent()){
publisher = graph.addVertex(graph.Publisher());
publisher.set(graph.Publisher().name, publisherSt);
graph.raw().commit();
}else{
publisher = optionalPublisher.get();
}
book.addOutEdge(graph.BookPublisher(), publisher);
}
//-----city-----
if (!citySt.equals("")) {
City<I,RV,RVT,RE,RET> city = null;
Optional<City<I,RV,RVT,RE,RET>> optionalCity = graph.cityNameIndex().getVertex(citySt);
if(!optionalCity.isPresent()){
city = graph.addVertex(graph.City());
city.set(graph.City().name, citySt);
graph.raw().commit();
}else{
city = optionalCity.get();
}
book.addOutEdge(graph.BookCity(), city);
}
}else{
book = optionalBook.get();
reference = book.referenceBook_inV();
}
//--protein citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
// TODO see if these fields can somehow be included
// bookProteinCitationProperties.put(BookProteinCitationRel.FIRST_PROPERTY, firstSt);
// bookProteinCitationProperties.put(BookProteinCitationRel.LAST_PROPERTY, lastSt);
// bookProteinCitationProperties.put(BookProteinCitationRel.VOLUME_PROPERTY, volumeSt);
// bookProteinCitationProperties.put(BookProteinCitationRel.TITLE_PROPERTY, titleSt);
}
//----------------------------------------------------------------------------
//-----------------------------ONLINE ARTICLE-----------------------------------------
break;
case ONLINE_ARTICLE_CITATION_TYPE:
if (uniprotDataXML.getOnlineArticles()) {
String locatorSt = citation.getChildText("locator");
String nameSt = citation.getAttributeValue("name");
String titleSt = citation.getChildText("title");
String dateSt = citation.getAttributeValue("date");
if (titleSt == null) {
titleSt = "";
}
if (nameSt == null) {
nameSt = "";
}
if (locatorSt == null) {
locatorSt = "";
}
if (dateSt == null) {
dateSt = "";
}
if (!titleSt.equals("")) {
OnlineArticle<I,RV,RVT,RE,RET> onlineArticle = null;
Optional<OnlineArticle<I,RV,RVT,RE,RET>> optionalOnlineArticle = graph.onlineArticleTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalOnlineArticle.isPresent()){
onlineArticle = graph.addVertex(graph.OnlineArticle());
onlineArticle.set(graph.OnlineArticle().title, titleSt);
graph.raw().commit();
reference = graph.addVertex(graph.Reference());
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceOnlineArticle(), onlineArticle);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//---consortiums association----
for(Consortium<I,RV,RVT,RE,RET> consortium : authorsConsortium){
reference.addOutEdge(graph.ReferenceAuthorConsortium(), consortium);
}
//------online journal-----------
if (!nameSt.equals("")) {
OnlineJournal<I,RV,RVT,RE,RET> onlineJournal = null;
Optional<OnlineJournal<I,RV,RVT,RE,RET>> optionalOnlineJournal = graph.onlineJournalNameIndex().getVertex(nameSt);
if(!optionalOnlineJournal.isPresent()){
onlineJournal = graph.addVertex(graph.OnlineJournal());
onlineJournal.set(graph.OnlineJournal().name, nameSt);
graph.raw().commit();
}else{
onlineJournal = optionalOnlineJournal.get();
}
OnlineArticleOnlineJournal<I,RV,RVT,RE,RET> onlineArticleOnlineJournal = onlineArticle.addOutEdge(graph.OnlineArticleOnlineJournal(), onlineJournal);
onlineArticleOnlineJournal.set(graph.OnlineArticleOnlineJournal().locator, locatorSt);
}
//----------------------------
}else{
onlineArticle = optionalOnlineArticle.get();
reference = onlineArticle.referenceOnlineArticle_inV();
}
//protein citation
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------ARTICLE-----------------------------------------
break;
case ARTICLE_CITATION_TYPE:
if (uniprotDataXML.getArticles()) {
String journalNameSt = citation.getAttributeValue("name");
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
String firstSt = citation.getAttributeValue("first");
String lastSt = citation.getAttributeValue("last");
String volumeSt = citation.getAttributeValue("volume");
String doiSt = "";
String medlineSt = "";
String pubmedId = "";
if (journalNameSt == null) {
journalNameSt = "";
}
if (dateSt == null) {
dateSt = "";
}
if (firstSt == null) {
firstSt = "";
}
if (lastSt == null) {
lastSt = "";
}
if (volumeSt == null) {
volumeSt = "";
}
if (titleSt == null) {
titleSt = "";
}
List<Element> dbReferences = citation.getChildren("dbReference");
for (Element tempDbRef : dbReferences) {
switch (tempDbRef.getAttributeValue("type")) {
case "DOI":
doiSt = tempDbRef.getAttributeValue("id");
break;
case "MEDLINE":
medlineSt = tempDbRef.getAttributeValue("id");
break;
case "PubMed":
pubmedId = tempDbRef.getAttributeValue("id");
break;
}
}
if (titleSt != "") {
Article<I,RV,RVT,RE,RET> article = null;
Optional<Article<I,RV,RVT,RE,RET>> optionalArticle = graph.articleTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalArticle.isPresent()){
article = graph.addVertex(graph.Article());
article.set(graph.Article().title, titleSt);
article.set(graph.Article().doId, doiSt);
graph.raw().commit();
if(pubmedId != ""){
Pubmed<I,RV,RVT,RE,RET> pubmed = null;
Optional<Pubmed<I,RV,RVT,RE,RET>> optionalPubmed = graph.pubmedIdIndex().getVertex(pubmedId);
if(!optionalPubmed.isPresent()){
pubmed = graph.addVertex(graph.Pubmed());
pubmed.set(graph.Pubmed().id, pubmedId);
graph.raw().commit();
}else{
pubmed = optionalPubmed.get();
}
article.addOutEdge(graph.ArticlePubmed(), pubmed);
}
reference = graph.addVertex(graph.Reference());
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceArticle(), article);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//---consortiums association----
for(Consortium<I,RV,RVT,RE,RET> consortium : authorsConsortium){
reference.addOutEdge(graph.ReferenceAuthorConsortium(), consortium);
}
//------journal-----------
if (!journalNameSt.equals("")) {
Journal<I,RV,RVT,RE,RET> journal = null;
Optional<Journal<I,RV,RVT,RE,RET>> optionalJournal = graph.journalNameIndex().getVertex(journalNameSt);
if(!optionalJournal.isPresent()){
journal = graph.addVertex(graph.Journal());
journal.set(graph.Journal().name, journalNameSt);
graph.raw().commit();
}else{
journal = optionalJournal.get();
}
ArticleJournal<I,RV,RVT,RE,RET> articleJournal = article.addOutEdge(graph.ArticleJournal(), journal);
articleJournal.set(graph.ArticleJournal().volume, volumeSt);
articleJournal.set(graph.ArticleJournal().first, firstSt);
articleJournal.set(graph.ArticleJournal().last, lastSt);
}
//----------------------------
}else{
article = optionalArticle.get();
reference = article.referenceArticle_inV();
}
//protein citation
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//----------------------UNPUBLISHED OBSERVATIONS-----------------------------------------
break;
case UNPUBLISHED_OBSERVATION_CITATION_TYPE:
if (uniprotDataXML.getUnpublishedObservations()) {
String dateSt = citation.getAttributeValue("date");
String scopeSt = referenceElement.getChildText("scope");
if (dateSt == null) {
dateSt = "";
}
if (scopeSt == null){
scopeSt = "";
}
UnpublishedObservation<I,RV,RVT,RE,RET> unpublishedObservation = graph.addVertex(graph.UnpublishedObservation());
unpublishedObservation.set(graph.UnpublishedObservation().scope, scopeSt);
Reference<I,RV,RVT,RE,RET> reference = graph.addVertex(graph.Reference());
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceUnpublishedObservation(), unpublishedObservation);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//protein citation
protein.addOutEdge(graph.ProteinReference(), reference);
}
break;
}
}
}
}
protected Date parseDate(String date) throws ParseException {
return dateFormat.parse(date);
}
}
| src/main/java/com/bio4j/model/uniprot/programs/ImportUniprot.java | package com.bio4j.model.uniprot.programs;
import com.bio4j.model.uniprot.UniprotGraph;
import com.bio4j.model.uniprot.vertices.*;
import com.bio4j.model.uniprot.edges.*;
import com.bio4j.angulillos.UntypedGraph;
import com.ohnosequences.xml.api.model.XMLElement;
import com.ohnosequences.xml.model.bio4j.UniprotDataXML;
import org.jdom2.Element;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* @author <a href="mailto:[email protected]">Pablo Pareja Tobes</a>
*/
public abstract class ImportUniprot<I extends UntypedGraph<RV,RVT,RE,RET>,RV,RVT,RE,RET> {
private static final Logger logger = Logger.getLogger("ImportUniprot");
private static FileHandler fh;
public static final String ENTRY_TAG_NAME = "entry";
public static final String ENTRY_ACCESSION_TAG_NAME = "accession";
public static final String ENTRY_NAME_TAG_NAME = "name";
public static final String ENTRY_MODIFIED_DATE_ATTRIBUTE = "modified";
public static final String ENTRY_CREATED_DATE_ATTRIBUTE = "created";
public static final String ENTRY_VERSION_ATTRIBUTE = "version";
public static final String ENTRY_DATASET_ATTRIBUTE = "dataset";
public static final String ENTRY_SEQUENCE_TAG_NAME = "sequence";
public static final String KEYWORD_TAG_NAME = "keyword";
public static final String KEYWORD_ID_ATTRIBUTE = "id";
public static final String REFERENCE_TAG_NAME = "reference";
public static final String CITATION_TAG_NAME = "citation";
public static final String GENE_LOCATION_TAG_NAME = "geneLocation";
public static final String ORGANISM_TAG_NAME = "organism";
public static final String ORGANISM_NAME_TAG_NAME = "name";
public static final String ORGANISM_NAME_TYPE_ATTRIBUTE = "type";
public static final String ORGANISM_SCIENTIFIC_NAME_TYPE = "scientific";
public static final String ORGANISM_COMMON_NAME_TYPE = "common";
public static final String ORGANISM_SYNONYM_NAME_TYPE = "synonym";
public static final String DB_REFERENCE_TAG_NAME = "dbReference";
public static final String DB_REFERENCE_TYPE_ATTRIBUTE = "type";
public static final String DB_REFERENCE_ID_ATTRIBUTE = "id";
public static final String DB_REFERENCE_VALUE_ATTRIBUTE = "value";
public static final String DB_REFERENCE_PROPERTY_TAG_NAME = "property";
public static final String INTERPRO_DB_REFERENCE_TYPE = "InterPro";
public static final String INTERPRO_ENTRY_NAME = "entry name";
public static final String GO_DB_REFERENCE_TYPE = "GO";
public static final String EVIDENCE_TYPE_ATTRIBUTE = "evidence";
public static final String SEQUENCE_MASS_ATTRIBUTE = "mass";
public static final String SEQUENCE_LENGTH_ATTRIBUTE = "length";
public static final String PROTEIN_TAG_NAME = "protein";
public static final String PROTEIN_RECOMMENDED_NAME_TAG_NAME = "recommendedName";
public static final String PROTEIN_FULL_NAME_TAG_NAME = "fullName";
public static final String PROTEIN_SHORT_NAME_TAG_NAME = "shortName";
public static final String GENE_TAG_NAME = "gene";
public static final String GENE_NAME_TAG_NAME = "name";
public static final String COMMENT_TAG_NAME = "comment";
public static final String COMMENT_TYPE_ATTRIBUTE = "type";
public static final String COMMENT_ALTERNATIVE_PRODUCTS_TYPE = "alternative products";
public static final String COMMENT_SEQUENCE_CAUTION_TYPE = "sequence caution";
public static final String SUBCELLULAR_LOCATION_TAG_NAME = "subcellularLocation";
public static final String LOCATION_TAG_NAME = "location";
public static final String COMMENT_TEXT_TAG_NAME = "text";
public static final String FEATURE_TAG_NAME = "feature";
public static final String FEATURE_TYPE_ATTRIBUTE = "type";
public static final String FEATURE_DESCRIPTION_ATTRIBUTE = "description";
public static final String STATUS_ATTRIBUTE = "status";
public static final String FEATURE_REF_ATTRIBUTE = "ref";
public static final String FEATURE_ID_ATTRIBUTE = "id";
public static final String EVIDENCE_ATTRIBUTE = "evidence";
public static final String FEATURE_LOCATION_TAG_NAME = "location";
public static final String FEATURE_ORIGINAL_TAG_NAME = "original";
public static final String FEATURE_VARIATION_TAG_NAME = "variation";
public static final String FEATURE_POSITION_TAG_NAME = "position";
public static final String FEATURE_LOCATION_BEGIN_TAG_NAME = "begin";
public static final String FEATURE_LOCATION_END_TAG_NAME = "end";
public static final String FEATURE_LOCATION_POSITION_ATTRIBUTE = "position";
public static final String FEATURE_POSITION_POSITION_ATTRIBUTE = "position";
public static final String THESIS_CITATION_TYPE = "thesis";
public static final String PATENT_CITATION_TYPE = "patent";
public static final String SUBMISSION_CITATION_TYPE = "submission";
public static final String ARTICLE_CITATION_TYPE = "journal article";
public static final String ONLINE_ARTICLE_CITATION_TYPE = "online journal article";
public static final String BOOK_CITATION_TYPE = "book";
public static final String UNPUBLISHED_OBSERVATION_CITATION_TYPE = "unpublished observations";
public static final String COMMENT_TYPE_DISEASE = "disease";
public static final String COMMENT_TYPE_FUNCTION = "function";
public static final String COMMENT_TYPE_COFACTOR = "cofactor";
public static final String COMMENT_TYPE_CATALYTIC_ACTIVITY = "catalytic activity";
public static final String COMMENT_TYPE_ENZYME_REGULATION = "enzyme regulation";
public static final String COMMENT_TYPE_BIOPHYSICOCHEMICAL_PROPERTIES = "biophysicochemical properties";
public static final String COMMENT_TYPE_SUBUNIT = "subunit";
public static final String COMMENT_TYPE_PATHWAY = "pathway";
public static final String COMMENT_TYPE_SUBCELLULAR_LOCATION = "subcellular location";
public static final String COMMENT_TYPE_TISSUE_SPECIFICITY = "tissue specificity";
public static final String COMMENT_TYPE_DEVELOPMENTAL_STAGE = "developmental stage";
public static final String COMMENT_TYPE_INDUCTION = "induction";
public static final String COMMENT_TYPE_DOMAIN = "domain";
public static final String COMMENT_TYPE_POST_TRANSLATIONAL_MODIFICATION = "PTM";
public static final String COMMENT_TYPE_RNA_EDITING = "RNA editing";
public static final String COMMENT_TYPE_MASS_SPECTROMETRY = "mass spectrometry";
public static final String COMMENT_TYPE_POLYMORPHISM = "polymorphism";
public static final String COMMENT_TYPE_DISRUPTION_PHENOTYPE = "disruption phenotype";
public static final String COMMENT_TYPE_ALLERGEN = "allergen";
public static final String COMMENT_TYPE_TOXIC_DOSE = "toxic dose";
public static final String COMMENT_TYPE_BIOTECHNOLOGY = "biotechnology";
public static final String COMMENT_TYPE_PHARMACEUTICAL = "pharmaceutical";
public static final String COMMENT_TYPE_MISCELLANEOUS = "miscellaneous";
public static final String COMMENT_TYPE_SIMILARITY = "similarity";
protected SimpleDateFormat dateFormat;
protected abstract UniprotGraph<I,RV,RVT,RE,RET> config(String dbFolder);
protected void importUniprot(String[] args) {
if (args.length != 3) {
System.out.println("This program expects the following parameters: \n"
+ "1. Uniprot xml filename \n"
+ "2. Bio4j DB folder \n"
+ "3. Config XML file");
} else {
long initTime = System.nanoTime();
File inFile = new File(args[0]);
File configFile = new File(args[2]);
String dbFolder = args[1];
String currentAccessionId = "";
//-------creating graph handlers---------------------
UniprotGraph<I,RV,RVT,RE,RET> graph = config(dbFolder);
BufferedWriter enzymeIdsNotFoundBuff = null;
BufferedWriter statsBuff = null;
int proteinCounter = 0;
int limitForPrintingOut = 10000;
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
// This block configures the logger with handler and formatter
fh = new FileHandler("ImportUniprot" + args[0].split("\\.")[0].replaceAll("/", "_") + ".log", false);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
System.out.println("Reading conf file...");
BufferedReader reader = new BufferedReader(new FileReader(configFile));
String line;
StringBuilder stBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stBuilder.append(line);
}
reader.close();
UniprotDataXML uniprotDataXML = new UniprotDataXML(stBuilder.toString());
//---creating writer for stats file-----
statsBuff = new BufferedWriter(new FileWriter(new File("ImportUniprotStats_" + inFile.getName().split("\\.")[0] + ".txt")));
reader = new BufferedReader(new FileReader(inFile));
StringBuilder entryStBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
if (line.trim().startsWith("<" + ENTRY_TAG_NAME)) {
while (!line.trim().startsWith("</" + ENTRY_TAG_NAME + ">")) {
entryStBuilder.append(line);
line = reader.readLine();
}
//linea final del organism
entryStBuilder.append(line);
//System.out.println("organismStBuilder.toString() = " + organismStBuilder.toString());
XMLElement entryXMLElem = new XMLElement(entryStBuilder.toString());
entryStBuilder.delete(0, entryStBuilder.length());
String modifiedDateSt = entryXMLElem.asJDomElement().getAttributeValue(ENTRY_MODIFIED_DATE_ATTRIBUTE);
String createdDateSt = entryXMLElem.asJDomElement().getAttributeValue(ENTRY_CREATED_DATE_ATTRIBUTE);
Integer version = Integer.parseInt(entryXMLElem.asJDomElement().getAttributeValue(ENTRY_VERSION_ATTRIBUTE));
String accessionSt = entryXMLElem.asJDomElement().getChildText(ENTRY_ACCESSION_TAG_NAME);
String nameSt = entryXMLElem.asJDomElement().getChildText(ENTRY_NAME_TAG_NAME);
String fullNameSt = getProteinFullName(entryXMLElem.asJDomElement().getChild(PROTEIN_TAG_NAME));
String shortNameSt = getProteinShortName(entryXMLElem.asJDomElement().getChild(PROTEIN_TAG_NAME));
if (shortNameSt == null) {
shortNameSt = "";
}
if (fullNameSt == null) {
fullNameSt = "";
}
currentAccessionId = accessionSt;
Element sequenceElem = entryXMLElem.asJDomElement().getChild(ENTRY_SEQUENCE_TAG_NAME);
String sequenceSt = sequenceElem.getText();
int seqLength = Integer.parseInt(sequenceElem.getAttributeValue(SEQUENCE_LENGTH_ATTRIBUTE));
float seqMass = Float.parseFloat(sequenceElem.getAttributeValue(SEQUENCE_MASS_ATTRIBUTE));
Protein<I,RV,RVT,RE,RET> protein = graph.addVertex(graph.Protein());
protein.set(graph.Protein().modifiedDate, parseDate(modifiedDateSt));
protein.set(graph.Protein().createdDate, parseDate(createdDateSt));
protein.set(graph.Protein().accession, accessionSt);
protein.set(graph.Protein().name, nameSt);
protein.set(graph.Protein().fullName, fullNameSt);
protein.set(graph.Protein().shortName, shortNameSt);
protein.set(graph.Protein().sequence, sequenceSt);
protein.set(graph.Protein().length, seqLength);
protein.set(graph.Protein().mass, String.valueOf(seqMass));
protein.set(graph.Protein().version, version);
//-----db references-------------
List<Element> dbReferenceList = entryXMLElem.asJDomElement().getChildren(DB_REFERENCE_TAG_NAME);
ArrayList<String> ensemblPlantsReferences = new ArrayList<>();
HashMap<String, String> reactomeReferences = new HashMap<>();
for (Element dbReferenceElem : dbReferenceList) {
String refId = dbReferenceElem.getAttributeValue("id");
switch (dbReferenceElem.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE)) {
case "Ensembl":
//looking for Ensembl node
Ensembl<I,RV,RVT,RE,RET> ensembl = null;
Optional<Ensembl<I,RV,RVT,RE,RET>> ensemblOptional = graph.ensemblIdIndex().getVertex(refId);
if(!ensemblOptional.isPresent()){
String moleculeIdSt = "";
String proteinSequenceIdSt = "";
String geneIdSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("protein sequence ID")) {
proteinSequenceIdSt = propertyElem.getAttributeValue("value");
}
if (propertyElem.getAttributeValue("type").equals("gene ID")) {
geneIdSt = propertyElem.getAttributeValue("value");
}
}
Element moleculeTag = dbReferenceElem.getChild("molecule");
if(moleculeTag != null){
moleculeIdSt = moleculeTag.getAttributeValue("id");
if(moleculeIdSt == null){
moleculeTag.getText();
if(moleculeIdSt == null){
moleculeIdSt = "";
}
}
}
ensembl = graph.addVertex(graph.Ensembl());
ensembl.set(graph.Ensembl().id, refId);
ensembl.set(graph.Ensembl().proteinSequenceId, proteinSequenceIdSt);
ensembl.set(graph.Ensembl().moleculeId, moleculeIdSt);
ensembl.set(graph.Ensembl().geneId, geneIdSt);
graph.raw().commit();
}else{
ensembl = ensemblOptional.get();
}
protein.addOutEdge(graph.ProteinEnsembl(), ensembl);
break;
case "PIR":
//looking for PIR node
PIR<I,RV,RVT,RE,RET> pIR = null;
Optional<PIR<I,RV,RVT,RE,RET>> optionalPIR = graph.pIRIdIndex().getVertex(refId);
if(!optionalPIR.isPresent()){
String entryNameSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("entry name")) {
entryNameSt = propertyElem.getAttributeValue("value");
}
}
pIR = graph.addVertex(graph.PIR());
pIR.set(graph.PIR().entryName, entryNameSt);
pIR.set(graph.PIR().id, refId);
graph.raw().commit();
}else{
pIR = optionalPIR.get();
}
protein.addOutEdge(graph.ProteinPIR(), pIR);
break;
case "UniGene":
//looking for UniGene node
UniGene<I,RV,RVT,RE,RET> uniGene = null;
Optional<UniGene<I,RV,RVT,RE,RET>> uniGeneOptional = graph.uniGeneIdIndex().getVertex(refId);
if(!uniGeneOptional.isPresent()){
uniGene = graph.addVertex(graph.UniGene());
uniGene.set(graph.UniGene().id, refId);
graph.raw().commit();
}else{
uniGene = uniGeneOptional.get();
}
protein.addOutEdge(graph.ProteinUniGene(), uniGene);
break;
case "KEGG":
//looking for Kegg node
Kegg<I,RV,RVT,RE,RET> kegg = null;
Optional<Kegg<I,RV,RVT,RE,RET>> optionalKegg = graph.keggIdIndex().getVertex(refId);
if(!optionalKegg.isPresent()){
kegg = graph.addVertex(graph.Kegg());
kegg.set(graph.Kegg().id, refId);
graph.raw().commit();
}else{
kegg = optionalKegg.get();
}
protein.addOutEdge(graph.ProteinKegg(), kegg);
break;
case "EMBL":
//looking for EMBL node
EMBL<I,RV,RVT,RE,RET> embl = null;
Optional<EMBL<I,RV,RVT,RE,RET>> optionalEMBL = graph.eMBLIdIndex().getVertex(refId);
if(!optionalEMBL.isPresent()){
String moleculeTypeSt = "";
String proteinSequenceIdSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("protein sequence ID")) {
proteinSequenceIdSt = propertyElem.getAttributeValue("value");
}
if (propertyElem.getAttributeValue("type").equals("molecule type")) {
moleculeTypeSt = propertyElem.getAttributeValue("value");
}
}
embl = graph.addVertex(graph.EMBL());
embl.set(graph.EMBL().id, refId);
embl.set(graph.EMBL().proteinSequenceId, proteinSequenceIdSt);
embl.set(graph.EMBL().moleculeType, moleculeTypeSt);
graph.raw().commit();
}else{
embl = optionalEMBL.get();
}
protein.addOutEdge(graph.ProteinEMBL(), embl);
break;
case "RefSeq":
//looking for RefSeq node
RefSeq<I,RV,RVT,RE,RET> refSeq = null;
Optional<RefSeq<I,RV,RVT,RE,RET>> optionalRefSeq = graph.refSeqIdIndex().getVertex(refId);
if(!optionalRefSeq.isPresent()){
String nucleotideSequenceIdSt = "";
List<Element> children = dbReferenceElem.getChildren("property");
for (Element propertyElem : children) {
if (propertyElem.getAttributeValue("type").equals("nucleotide sequence ID")) {
nucleotideSequenceIdSt = propertyElem.getAttributeValue("value");
}
}
refSeq = graph.addVertex(graph.RefSeq());
refSeq.set(graph.RefSeq().id, refId);
refSeq.set(graph.RefSeq().nucleotideSequenceId, nucleotideSequenceIdSt);
graph.raw().commit();
}else{
refSeq = optionalRefSeq.get();
}
protein.addOutEdge(graph.ProteinRefSeq(), refSeq);
break;
case "Reactome":
Element propertyElem = dbReferenceElem.getChild("property");
String pathwayName = "";
if (propertyElem.getAttributeValue("type").equals("pathway name")) {
pathwayName = propertyElem.getAttributeValue("value");
}
reactomeReferences.put(refId, pathwayName);
break;
case "EnsemblPlants":
ensemblPlantsReferences.add(refId);
break;
}
}
// proteinProperties.put(ProteinNode.ENSEMBL_PLANTS_REFERENCES_PROPERTY, convertToStringArray(ensemblPlantsReferences));
// TODO we need to decide how to store this
// //---------------gene-names-------------------
// Element geneElement = entryXMLElem.asJDomElement().getChild(GENE_TAG_NAME);
// ArrayList<String> geneNames = new ArrayList<>();
// if (geneElement != null) {
// List<Element> genesList = geneElement.getChildren(GENE_NAME_TAG_NAME);
// for (Element geneNameElem : genesList) {
// geneNames.add(geneNameElem.getText());
// }
// }
// //-----------------------------------------
//--------------reactome associations----------------
if (uniprotDataXML.getReactome()) {
for (String reactomeId : reactomeReferences.keySet()) {
ReactomeTerm<I,RV,RVT,RE,RET> reactomeTerm = null;
Optional<ReactomeTerm<I,RV,RVT,RE,RET>> optionalReactomeTerm = graph.reactomeTermIdIndex().getVertex(reactomeId);
if (!optionalReactomeTerm.isPresent()) {
reactomeTerm = graph.addVertex(graph.ReactomeTerm());
reactomeTerm.set(graph.ReactomeTerm().id, reactomeId);
reactomeTerm.set(graph.ReactomeTerm().pathwayName, reactomeReferences.get(reactomeId));
graph.raw().commit();
}else{
reactomeTerm = optionalReactomeTerm.get();
}
protein.addOutEdge(graph.ProteinReactomeTerm(), reactomeTerm);
}
}
//-------------------------------------------------------
//-----comments import---
if (uniprotDataXML.getComments()) {
importProteinComments(entryXMLElem, graph, protein, sequenceSt, uniprotDataXML);
}
//-----features import----
if (uniprotDataXML.getFeatures()) {
importProteinFeatures(entryXMLElem, graph, protein);
}
//--------------------------------datasets--------------------------------------------------
String proteinDataSetSt = entryXMLElem.asJDomElement().getAttributeValue(ENTRY_DATASET_ATTRIBUTE);
Dataset<I,RV,RVT,RE,RET> dataset = null;
Optional<Dataset<I,RV,RVT,RE,RET>> optionalDataset = graph.datasetNameIndex().getVertex(proteinDataSetSt);
if (!optionalDataset.isPresent()) {
dataset = graph.addVertex(graph.Dataset());
dataset.set(graph.Dataset().name, proteinDataSetSt);
graph.raw().commit();
}else{
dataset = optionalDataset.get();
}
protein.addOutEdge(graph.ProteinDataset(), dataset);
//---------------------------------------------------------------------------------------------
if (uniprotDataXML.getCitations()) {
importProteinCitations(entryXMLElem,
graph,
protein,
uniprotDataXML);
}
//-------------------------------keywords------------------------------------------------------
if (uniprotDataXML.getKeywords()) {
List<Element> keywordsList = entryXMLElem.asJDomElement().getChildren(KEYWORD_TAG_NAME);
for (Element keywordElem : keywordsList) {
String keywordId = keywordElem.getAttributeValue(KEYWORD_ID_ATTRIBUTE);
String keywordName = keywordElem.getText();
Keyword<I,RV,RVT,RE,RET> keyword = null;
Optional<Keyword<I,RV,RVT,RE,RET> > optionalKeyword = graph.keywordIdIndex().getVertex(keywordId);
if (!optionalKeyword.isPresent()) {
keyword = graph.addVertex(graph.Keyword());
keyword.set(graph.Keyword().id, keywordId);
keyword.set(graph.Keyword().name, keywordName);
graph.raw().commit();
}else{
keyword = optionalKeyword.get();
}
protein.addOutEdge(graph.ProteinKeyword(), keyword);
}
}
//---------------------------------------------------------------------------------------
for (Element dbReferenceElem : dbReferenceList) {
//-------------------------------INTERPRO------------------------------------------------------
if (dbReferenceElem.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals(INTERPRO_DB_REFERENCE_TYPE)) {
if (uniprotDataXML.getInterpro()) {
String interproId = dbReferenceElem.getAttributeValue(DB_REFERENCE_ID_ATTRIBUTE);
Interpro<I,RV,RVT,RE,RET> interpro = null;
Optional<Interpro<I,RV,RVT,RE,RET>> optionalInterpro = graph.interproIdIndex().getVertex(interproId);
if (!optionalInterpro.isPresent()) {
String interproEntryNameSt = "";
List<Element> properties = dbReferenceElem.getChildren(DB_REFERENCE_PROPERTY_TAG_NAME);
for (Element prop : properties) {
if (prop.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals(INTERPRO_ENTRY_NAME)) {
interproEntryNameSt = prop.getAttributeValue(DB_REFERENCE_VALUE_ATTRIBUTE);
break;
}
}
interpro = graph.addVertex(graph.Interpro());
interpro.set(graph.Interpro().id, interproId);
interpro.set(graph.Interpro().name, interproEntryNameSt);
graph.raw().commit();
}else{
interpro = optionalInterpro.get();
}
protein.addOutEdge(graph.ProteinInterpro(), interpro);
}
} //-------------------------------PFAM------------------------------------------------------
else if (dbReferenceElem.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals("Pfam")) {
if (uniprotDataXML.getPfam()) {
String pfamId = dbReferenceElem.getAttributeValue(DB_REFERENCE_ID_ATTRIBUTE);
Pfam<I,RV,RVT,RE,RET> pfam = null;
Optional<Pfam<I,RV,RVT,RE,RET>> optionalPfam = graph.pfamIdIndex().getVertex(pfamId);
if (!optionalPfam.isPresent()) {
String pfamEntryNameSt = "";
List<Element> properties = dbReferenceElem.getChildren(DB_REFERENCE_PROPERTY_TAG_NAME);
for (Element prop : properties) {
if (prop.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE).equals("entry name")) {
pfamEntryNameSt = prop.getAttributeValue(DB_REFERENCE_VALUE_ATTRIBUTE);
break;
}
}
pfam = graph.addVertex(graph.Pfam());
pfam.set(graph.Pfam().id, pfamId);
pfam.set(graph.Pfam().name, pfamEntryNameSt);
graph.raw().commit();
}else{
pfam = optionalPfam.get();
}
protein.addOutEdge(graph.ProteinPfam(), pfam);
}
}
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//--------------------------------geneLocation-------------------------------------------
List<Element> geneLocationElements = entryXMLElem.asJDomElement().getChildren(GENE_LOCATION_TAG_NAME);
for (Element geneLocationElem : geneLocationElements){
String geneLocationTypeSt = geneLocationElem.getAttributeValue("type");
String geneLocationNameSt = geneLocationElem.getChildText("name");
if(geneLocationNameSt == null){
geneLocationNameSt = "";
}
Optional<GeneLocation<I,RV,RVT,RE,RET>> optionalGeneLocation = graph.geneLocationNameIndex().getVertex(geneLocationTypeSt);
GeneLocation<I,RV,RVT,RE,RET> geneLocation = null;
if(optionalGeneLocation.isPresent()){
geneLocation = optionalGeneLocation.get();
}else{
geneLocation = graph.addVertex(graph.GeneLocation());
geneLocation.set(graph.GeneLocation().name, geneLocationTypeSt);
graph.raw().commit();
}
ProteinGeneLocation<I,RV,RVT,RE,RET> proteinGeneLocation = protein.addOutEdge(graph.ProteinGeneLocation(), geneLocation);
proteinGeneLocation.set(graph.ProteinGeneLocation().name, geneLocationNameSt);
}
//---------------------------------------------------------------------------------------
//--------------------------------organism-----------------------------------------------
String scName, commName, synName;
scName = "";
commName = "";
synName = "";
Element organismElem = entryXMLElem.asJDomElement().getChild(ORGANISM_TAG_NAME);
List<Element> organismNames = organismElem.getChildren(ORGANISM_NAME_TAG_NAME);
for (Element element : organismNames) {
String type = element.getAttributeValue(ORGANISM_NAME_TYPE_ATTRIBUTE);
switch (type) {
case ORGANISM_SCIENTIFIC_NAME_TYPE:
scName = element.getText();
break;
case ORGANISM_COMMON_NAME_TYPE:
commName = element.getText();
break;
case ORGANISM_SYNONYM_NAME_TYPE:
synName = element.getText();
break;
}
}
Organism<I,RV,RVT,RE,RET> organism = null;
Optional<Organism<I,RV,RVT,RE,RET>> organismOptional = graph.organismScientificNameIndex().getVertex(scName);
if (!organismOptional.isPresent()) {
organism = graph.addVertex(graph.Organism());
organism.set(graph.Organism().scientificName, scName);
organism.set(graph.Organism().commonName, commName);
organism.set(graph.Organism().synonymName, synName);
graph.raw().commit();
/* TODO see what to do with the NCBI taxonomy ID, just link to the NCBI tax node or also store
the id as an attribute
*/
// List<Element> organismDbRefElems = organismElem.getChildren(DB_REFERENCE_TAG_NAME);
// boolean ncbiIdFound = false;
// if (organismDbRefElems != null) {
// for (Element dbRefElem : organismDbRefElems) {
// String t = dbRefElem.getAttributeValue("type");
// if (t.equals("NCBI Taxonomy")) {
// organismProperties.put(OrganismNode.NCBI_TAXONOMY_ID_PROPERTY, dbRefElem.getAttributeValue("id"));
// ncbiIdFound = true;
// break;
// }
// }
// }
// if (!ncbiIdFound) {
// organismProperties.put(OrganismNode.NCBI_TAXONOMY_ID_PROPERTY, "");
// }
Element lineage = entryXMLElem.asJDomElement().getChild("organism").getChild("lineage");
List<Element> taxons = lineage.getChildren("taxon");
Element firstTaxonElem = taxons.get(0);
Taxon<I,RV,RVT,RE,RET> firstTaxon = null;
Optional<Taxon<I,RV,RVT,RE,RET>> firstTaxonOptional = graph.taxonNameIndex().getVertex(firstTaxonElem.getText());
if (!firstTaxonOptional.isPresent()) {
String firstTaxonName = firstTaxonElem.getText();
firstTaxon = graph.addVertex(graph.Taxon());
firstTaxon.set(graph.Taxon().name, firstTaxonName);
graph.raw().commit();
}else{
firstTaxon = firstTaxonOptional.get();
}
Taxon<I,RV,RVT,RE,RET> lastTaxon = firstTaxon;
for (int i = 1; i < taxons.size(); i++) {
String taxonName = taxons.get(i).getText();
Taxon<I,RV,RVT,RE,RET> currentTaxon = null;
Optional<Taxon<I,RV,RVT,RE,RET>> currentTaxonOptional = graph.taxonNameIndex().getVertex(taxonName);
if (!currentTaxonOptional.isPresent()) {
currentTaxon = graph.addVertex(graph.Taxon());
currentTaxon.set(graph.Taxon().name, taxonName);
graph.raw().commit();
lastTaxon.addOutEdge(graph.TaxonParent(), currentTaxon);
}else{
currentTaxon = currentTaxonOptional.get();
}
lastTaxon = currentTaxon;
}
organism.addOutEdge(graph.OrganismTaxon(), lastTaxon);
}else{
organism = organismOptional.get();
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
protein.addOutEdge(graph.ProteinOrganism(), organism);
proteinCounter++;
if ((proteinCounter % limitForPrintingOut) == 0) {
String countProteinsSt = proteinCounter + " proteins inserted!!";
logger.log(Level.INFO, countProteinsSt);
}
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, ("Exception retrieving protein " + currentAccessionId));
logger.log(Level.SEVERE, e.getMessage());
StackTraceElement[] trace = e.getStackTrace();
for (StackTraceElement stackTraceElement : trace) {
logger.log(Level.SEVERE, stackTraceElement.toString());
}
} finally {
try {
// shutdown, makes sure all changes are written to disk
graph.raw().shutdown();
// closing logger file handler
fh.close();
//-----------------writing stats file---------------------
long elapsedTime = System.nanoTime() - initTime;
long elapsedSeconds = Math.round((elapsedTime / 1000000000.0));
long hours = elapsedSeconds / 3600;
long minutes = (elapsedSeconds % 3600) / 60;
long seconds = (elapsedSeconds % 3600) % 60;
statsBuff.write("Statistics for program ImportUniprot:\nInput file: " + inFile.getName()
+ "\nThere were " + proteinCounter + " proteins inserted.\n"
+ "The elapsed time was: " + hours + "h " + minutes + "m " + seconds + "s\n");
//---closing stats writer---
statsBuff.close();
} catch (IOException ex) {
Logger.getLogger(ImportUniprot.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private void importProteinFeatures(XMLElement entryXMLElem,
UniprotGraph<I,RV,RVT,RE,RET> graph,
Protein<I,RV,RVT,RE,RET> protein) {
//--------------------------------features----------------------------------------------------
List<Element> featuresList = entryXMLElem.asJDomElement().getChildren(FEATURE_TAG_NAME);
for (Element featureElem : featuresList) {
String featureTypeSt = featureElem.getAttributeValue(FEATURE_TYPE_ATTRIBUTE);
FeatureType<I,RV,RVT,RE,RET> feature = null;
Optional<FeatureType<I,RV,RVT,RE,RET>> optionalFeature = graph.featureTypeNameIndex().getVertex(featureTypeSt);
if (!optionalFeature.isPresent()) {
feature = graph.addVertex(graph.FeatureType());
feature.set(graph.FeatureType().name, featureTypeSt);
graph.raw().commit();
}else{
feature = optionalFeature.get();
}
String featureDescSt = featureElem.getAttributeValue(FEATURE_DESCRIPTION_ATTRIBUTE);
if (featureDescSt == null) {
featureDescSt = "";
}
String featureIdSt = featureElem.getAttributeValue(FEATURE_ID_ATTRIBUTE);
if (featureIdSt == null) {
featureIdSt = "";
}
String featureStatusSt = featureElem.getAttributeValue(STATUS_ATTRIBUTE);
if (featureStatusSt == null) {
featureStatusSt = "";
}
String featureEvidenceSt = featureElem.getAttributeValue(EVIDENCE_ATTRIBUTE);
if (featureEvidenceSt == null) {
featureEvidenceSt = "";
}
Element locationElem = featureElem.getChild(FEATURE_LOCATION_TAG_NAME);
Element positionElem = locationElem.getChild(FEATURE_POSITION_TAG_NAME);
Integer beginFeature = null;
Integer endFeature = null;
if (positionElem != null) {
String tempValue = positionElem.getAttributeValue(FEATURE_POSITION_POSITION_ATTRIBUTE);
if (tempValue == null) {
beginFeature = -1;
}else{
beginFeature = Integer.parseInt(tempValue);
}
endFeature = beginFeature;
} else {
String tempValue = locationElem.getChild(FEATURE_LOCATION_BEGIN_TAG_NAME).getAttributeValue(FEATURE_LOCATION_POSITION_ATTRIBUTE);
if(tempValue == null){
beginFeature = null;
}else{
beginFeature = Integer.parseInt(tempValue);
}
tempValue = locationElem.getChild(FEATURE_LOCATION_END_TAG_NAME).getAttributeValue(FEATURE_LOCATION_POSITION_ATTRIBUTE);
if(tempValue == null){
endFeature = null;
}else{
endFeature = Integer.parseInt(tempValue);
}
}
if (beginFeature == null) {
beginFeature = -1;
}
if (endFeature == null) {
endFeature = -1;
}
String originalSt = featureElem.getChildText(FEATURE_ORIGINAL_TAG_NAME);
String variationSt = featureElem.getChildText(FEATURE_VARIATION_TAG_NAME);
if (originalSt == null) {
originalSt = "";
}
if (variationSt == null) {
variationSt = "";
}
String featureRefSt = featureElem.getAttributeValue(FEATURE_REF_ATTRIBUTE);
if (featureRefSt == null) {
featureRefSt = "";
}
ProteinFeature<I,RV,RVT,RE,RET> proteinFeature = protein.addOutEdge(graph.ProteinFeature(), feature);
addPropertiesToProteinFeatureRelationship(graph, proteinFeature, featureIdSt, featureDescSt, featureEvidenceSt,
featureStatusSt, beginFeature, endFeature, originalSt, variationSt, featureRefSt);
}
}
private void importProteinComments(XMLElement entryXMLElem,
UniprotGraph<I,RV,RVT,RE,RET> graph,
Protein<I,RV,RVT,RE,RET> protein,
String proteinSequence,
UniprotDataXML uniprotDataXML) {
List<Element> comments = entryXMLElem.asJDomElement().getChildren(COMMENT_TAG_NAME);
for (Element commentElem : comments) {
String commentTypeSt = commentElem.getAttributeValue(COMMENT_TYPE_ATTRIBUTE);
Element textElem = commentElem.getChild("text");
String commentTextSt = "";
String commentStatusSt = "";
String commentEvidenceSt = "";
if (textElem != null) {
commentTextSt = textElem.getText();
commentStatusSt = textElem.getAttributeValue("status");
if (commentStatusSt == null) {
commentStatusSt = "";
}
commentEvidenceSt = textElem.getAttributeValue("evidence");
if (commentEvidenceSt == null) {
commentEvidenceSt = "";
}
}
//-----------------COMMENT TYPE NODE RETRIEVING/CREATION----------------------
Optional<CommentType<I,RV,RVT,RE,RET>> commentOptional = graph.commentTypeNameIndex().getVertex(commentTypeSt);
CommentType<I,RV,RVT,RE,RET> comment = null;
if(!commentOptional.isPresent()){
comment = graph.addVertex(graph.CommentType());
comment.set(graph.CommentType().name, commentTypeSt);
graph.raw().commit();
}else{
comment = commentOptional.get();
}
boolean createStandardProteinComment = false;
switch (commentTypeSt) {
case COMMENT_TYPE_FUNCTION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_COFACTOR:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_CATALYTIC_ACTIVITY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_ENZYME_REGULATION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_DISEASE:
Element diseaseElement = commentElem.getChild("disease");
if(diseaseElement != null){
String diseaseId = diseaseElement.getAttributeValue("id");
String diseaseName = diseaseElement.getChildText("name");
String diseaseDescription = diseaseElement.getChildText("description");
String diseaseAcronym = diseaseElement.getChildText("acronym");
if(diseaseId != null){
Disease<I,RV,RVT,RE,RET> disease = null;
Optional<Disease<I,RV,RVT,RE,RET>> diseaseOptional = graph.diseaseIdIndex().getVertex(diseaseId);
if(!diseaseOptional.isPresent()){
disease = graph.Disease().from(graph.raw().addVertex(null));
disease.set(graph.Disease().name, diseaseName);
disease.set(graph.Disease().id, diseaseId);
disease.set(graph.Disease().acronym, diseaseAcronym);
disease.set(graph.Disease().description, diseaseDescription);
graph.raw().commit();
}else{
disease = diseaseOptional.get();
}
ProteinDisease<I,RV,RVT,RE,RET> proteinDisease = protein.addOutEdge(graph.ProteinDisease(), disease);
proteinDisease.set(graph.ProteinDisease().text, commentTextSt);
proteinDisease.set(graph.ProteinDisease().status, commentStatusSt);
proteinDisease.set(graph.ProteinDisease().evidence, commentEvidenceSt);
}
}
break;
case COMMENT_TYPE_TISSUE_SPECIFICITY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_TOXIC_DOSE:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_BIOTECHNOLOGY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_SUBUNIT:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_POLYMORPHISM:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_DOMAIN:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_POST_TRANSLATIONAL_MODIFICATION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_DISRUPTION_PHENOTYPE:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_BIOPHYSICOCHEMICAL_PROPERTIES:
String phDependenceSt = commentElem.getChildText("phDependence");
String temperatureDependenceSt = commentElem.getChildText("temperatureDependence");
if (phDependenceSt == null) {
phDependenceSt = "";
}
if (temperatureDependenceSt == null) {
temperatureDependenceSt = "";
}
String absorptionMaxSt = "";
String absorptionTextSt = "";
Element absorptionElem = commentElem.getChild("absorption");
if (absorptionElem != null) {
absorptionMaxSt = absorptionElem.getChildText("max");
absorptionTextSt = absorptionElem.getChildText("text");
if (absorptionMaxSt == null) {
absorptionMaxSt = "";
}
if (absorptionTextSt == null) {
absorptionTextSt = "";
}
}
String kineticsSt = "";
Element kineticsElem = commentElem.getChild("kinetics");
if (kineticsElem != null) {
kineticsSt = new XMLElement(kineticsElem).toString();
}
String redoxPotentialSt = "";
String redoxPotentialEvidenceSt = "";
Element redoxPotentialElem = commentElem.getChild("redoxPotential");
if (redoxPotentialElem != null) {
redoxPotentialSt = redoxPotentialElem.getText();
redoxPotentialEvidenceSt = redoxPotentialElem.getAttributeValue("evidence");
if (redoxPotentialSt == null) {
redoxPotentialSt = "";
}
if (redoxPotentialEvidenceSt == null) {
redoxPotentialEvidenceSt = "";
}
}
ProteinComment<I,RV,RVT,RE,RET> proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
proteinComment.set(graph.ProteinComment().temperatureDependence, temperatureDependenceSt);
proteinComment.set(graph.ProteinComment().phDependence, phDependenceSt);
proteinComment.set(graph.ProteinComment().kineticsXML, kineticsSt);
proteinComment.set(graph.ProteinComment().absorptionMax, absorptionMaxSt);
proteinComment.set(graph.ProteinComment().absorptionText, absorptionTextSt);
proteinComment.set(graph.ProteinComment().redoxPotentialEvidence, redoxPotentialEvidenceSt);
proteinComment.set(graph.ProteinComment().redoxPotential, redoxPotentialSt);
break;
case COMMENT_TYPE_ALLERGEN:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_PATHWAY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_INDUCTION:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_SUBCELLULAR_LOCATION:
if (uniprotDataXML.getSubcellularLocations()) {
List<Element> subcLocations = commentElem.getChildren(SUBCELLULAR_LOCATION_TAG_NAME);
for (Element subcLocation : subcLocations) {
List<Element> locations = subcLocation.getChildren(LOCATION_TAG_NAME);
Element firstLocationElem = locations.get(0);
String firstLocationSt = firstLocationElem.getTextTrim();
SubcellularLocation<I,RV,RVT,RE,RET> lastLocation = null;
Optional<SubcellularLocation<I,RV,RVT,RE,RET>> lastLocationOptional = graph.subcellularLocationNameIndex().getVertex(firstLocationSt);
if(!lastLocationOptional.isPresent()){
lastLocation = graph.SubcellularLocation().from(graph.raw().addVertex(null));
lastLocation.set(graph.SubcellularLocation().name, firstLocationSt);
graph.raw().commit();
}else{
lastLocation = lastLocationOptional.get();
}
for (int i = 1; i < locations.size(); i++) {
SubcellularLocation<I,RV,RVT,RE,RET> tempLocation = null;
String tempLocationSt = locations.get(i).getTextTrim();
Optional<SubcellularLocation<I,RV,RVT,RE,RET>> tempLocationOptional = graph.subcellularLocationNameIndex().getVertex(tempLocationSt);
if(!tempLocationOptional.isPresent()){
tempLocation = graph.SubcellularLocation().from(graph.raw().addVertex(null));
tempLocation.set(graph.SubcellularLocation().name, tempLocationSt);
graph.raw().commit();
}else{
tempLocation = tempLocationOptional.get();
}
tempLocation.addOutEdge(graph.SubcellularLocationParent(), lastLocation);
lastLocation = tempLocation;
}
Element lastLocationElem = locations.get(locations.size() - 1);
String evidenceSt = lastLocationElem.getAttributeValue(EVIDENCE_ATTRIBUTE);
String statusSt = lastLocationElem.getAttributeValue(STATUS_ATTRIBUTE);
String topologyStatusSt = "";
String topologySt = "";
Element topologyElem = subcLocation.getChild("topology");
if (topologyElem != null) {
topologySt = topologyElem.getText();
topologyStatusSt = topologyElem.getAttributeValue("status");
}
if (topologyStatusSt == null) {
topologyStatusSt = "";
}
if (topologySt == null) {
topologySt = "";
}
if (evidenceSt == null) {
evidenceSt = "";
}
if (statusSt == null) {
statusSt = "";
}
ProteinSubcellularLocation<I,RV,RVT,RE,RET> proteinSubcellularLocation = protein.addOutEdge(graph.ProteinSubcellularLocation(), lastLocation);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().evidence, evidenceSt);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().status, statusSt);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().topology, topologySt);
proteinSubcellularLocation.set(graph.ProteinSubcellularLocation().topologyStatus, topologyStatusSt);
}
}
break;
case COMMENT_ALTERNATIVE_PRODUCTS_TYPE:
if (uniprotDataXML.getIsoforms()) {
List<Element> eventList = commentElem.getChildren("event");
List<Element> isoformList = commentElem.getChildren("isoform");
for (Element isoformElem : isoformList) {
String isoformIdSt = isoformElem.getChildText("id");
String isoformNoteSt = isoformElem.getChildText("note");
String isoformNameSt = isoformElem.getChildText("name");
String isoformSeqSt = "";
Element isoSeqElem = isoformElem.getChild("sequence");
if (isoSeqElem != null) {
String isoSeqTypeSt = isoSeqElem.getAttributeValue("type");
if (isoSeqTypeSt.equals("displayed")) {
isoformSeqSt = proteinSequence;
}
}
if (isoformNoteSt == null) {
isoformNoteSt = "";
}
if (isoformNameSt == null) {
isoformNameSt = "";
}
Optional<Isoform<I,RV,RVT,RE,RET>> isoformOptional = graph.isoformIdIndex().getVertex(isoformIdSt);
Isoform<I,RV,RVT,RE,RET> isoform;
if(!isoformOptional.isPresent()){
isoform = graph.Isoform().from(graph.raw().addVertex(null));
isoform.set(graph.Isoform().name, isoformNameSt);
isoform.set(graph.Isoform().note, isoformNoteSt);
isoform.set(graph.Isoform().sequence, isoformSeqSt);
isoform.set(graph.Isoform().id, isoformIdSt);
graph.raw().commit();
//Adding edge from Protein to Isoform
protein.addOutEdge(graph.ProteinIsoform(), isoform);
}else{
isoform = isoformOptional.get();
}
graph.raw().commit();
for (Element eventElem : eventList) {
String eventTypeSt = eventElem.getAttributeValue("type");
Optional<AlternativeProduct<I,RV,RVT,RE,RET>> alternativeProductOptional = graph.alternativeProductNameIndex().getVertex(eventTypeSt);
AlternativeProduct<I,RV,RVT,RE,RET> alternativeProduct;
if(alternativeProductOptional.isPresent()){
alternativeProduct = alternativeProductOptional.get();
}else{
alternativeProduct = graph.AlternativeProduct().from(graph.raw().addVertex(null));
alternativeProduct.set(graph.AlternativeProduct().name, eventTypeSt);
graph.raw().commit();
}
isoform.addOutEdge(graph.IsoformEventGenerator(), alternativeProduct);
}
}
}
break;
case COMMENT_SEQUENCE_CAUTION_TYPE:
Element conflictElem = commentElem.getChild("conflict");
if (conflictElem != null) {
String conflictTypeSt = conflictElem.getAttributeValue("type");
String resourceSt = "";
String idSt = "";
String versionSt = "";
ArrayList<String> positionsList = new ArrayList<>();
Element sequenceElem = conflictElem.getChild("sequence");
if (sequenceElem != null) {
resourceSt = sequenceElem.getAttributeValue("resource");
if (resourceSt == null) {
resourceSt = "";
}
idSt = sequenceElem.getAttributeValue("id");
if (idSt == null) {
idSt = "";
}
versionSt = sequenceElem.getAttributeValue("version");
if (versionSt == null) {
versionSt = "";
}
}
Element locationElem = commentElem.getChild("location");
if (locationElem != null) {
Element positionElem = locationElem.getChild("position");
if (positionElem != null) {
String tempPos = positionElem.getAttributeValue("position");
if (tempPos != null) {
positionsList.add(tempPos);
}
}
}
// System.out.println("conflictTypeSt = " + conflictTypeSt);
// System.out.println("sequenceCautionNameIndex = " + graph.sequenceCautionNameIndex());
Optional<SequenceCaution<I,RV,RVT,RE,RET>> sequenceCautionOptional = graph.sequenceCautionNameIndex().getVertex(conflictTypeSt);
SequenceCaution<I,RV,RVT,RE,RET> sequenceCaution;
if(!sequenceCautionOptional.isPresent()){
sequenceCaution = graph.SequenceCaution().from(graph.raw().addVertex(null));
sequenceCaution.set(graph.SequenceCaution().name, conflictTypeSt);
graph.raw().commit();
}else{
sequenceCaution = sequenceCautionOptional.get();
}
if (positionsList.size() > 0) {
for (String tempPosition : positionsList) {
ProteinSequenceCaution<I,RV,RVT,RE,RET> proteinSequenceCaution = protein.addOutEdge(graph.ProteinSequenceCaution(), sequenceCaution);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().evidence, commentEvidenceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().status, commentStatusSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().text, commentTextSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().id, idSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().resource, resourceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().version, versionSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().position, tempPosition);
}
} else {
ProteinSequenceCaution<I,RV,RVT,RE,RET> proteinSequenceCaution = protein.addOutEdge(graph.ProteinSequenceCaution(), sequenceCaution);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().evidence, commentEvidenceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().status, commentStatusSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().text, commentTextSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().id, idSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().resource, resourceSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().version, versionSt);
proteinSequenceCaution.set(graph.ProteinSequenceCaution().position, "");
}
}
break;
case COMMENT_TYPE_DEVELOPMENTAL_STAGE:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_MISCELLANEOUS:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_SIMILARITY:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_RNA_EDITING:
List<Element> locationsList = commentElem.getChildren("location");
for (Element tempLoc : locationsList) {
String positionSt = tempLoc.getChild("position").getAttributeValue("position");
proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
proteinComment.set(graph.ProteinComment().position, positionSt);
}
break;
case COMMENT_TYPE_PHARMACEUTICAL:
createStandardProteinComment = true;
break;
case COMMENT_TYPE_MASS_SPECTROMETRY:
String methodSt = commentElem.getAttributeValue("method");
String massSt = commentElem.getAttributeValue("mass");
if (methodSt == null) {
methodSt = "";
}
if (massSt == null) {
massSt = "";
}
locationsList = commentElem.getChildren("location");
for (Element tempLoc : locationsList) {
String positionSt = "";
Element positionElem = tempLoc.getChild("position");
if(positionElem != null){
positionSt = positionElem.getAttributeValue("position");
if(positionSt == null){
positionSt = "";
}
}
String beginSt = "";
String endSt = "";
if (tempLoc != null) {
Element beginElem = tempLoc.getChild("begin");
Element endElem = tempLoc.getChild("end");
if (beginElem != null) {
beginSt = beginElem.getAttributeValue("position");
}
if (endElem != null) {
endSt = endElem.getAttributeValue("position");
}
if(endSt == null || endSt.isEmpty()){
endSt = "-1";
}
if(beginSt == null || beginSt.isEmpty()){
beginSt = "-1";
}
}
proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
proteinComment.set(graph.ProteinComment().position, positionSt);
proteinComment.set(graph.ProteinComment().end, Integer.parseInt(endSt));
proteinComment.set(graph.ProteinComment().begin, Integer.parseInt(beginSt));
proteinComment.set(graph.ProteinComment().method, methodSt);
proteinComment.set(graph.ProteinComment().mass, massSt);
}
break;
}
if(createStandardProteinComment){
ProteinComment<I,RV,RVT,RE,RET> proteinComment = protein.addOutEdge(graph.ProteinComment(), comment);
proteinComment.set(graph.ProteinComment().text, commentTextSt);
proteinComment.set(graph.ProteinComment().status, commentStatusSt);
proteinComment.set(graph.ProteinComment().evidence, commentEvidenceSt);
}
}
}
private void addPropertiesToProteinFeatureRelationship(UniprotGraph<I,RV,RVT,RE,RET> graph, ProteinFeature<I,RV,RVT,RE,RET> proteinFeature,
String id, String description, String evidence, String status, int begin, int end,
String original, String variation, String ref){
proteinFeature.set(graph.ProteinFeature().description, description);
proteinFeature.set(graph.ProteinFeature().id, id);
proteinFeature.set(graph.ProteinFeature().evidence, evidence);
proteinFeature.set(graph.ProteinFeature().status, status);
proteinFeature.set(graph.ProteinFeature().begin, begin);
proteinFeature.set(graph.ProteinFeature().end, end);
proteinFeature.set(graph.ProteinFeature().original, original);
proteinFeature.set(graph.ProteinFeature().variation, variation);
proteinFeature.set(graph.ProteinFeature().ref, ref);
}
private static String getProteinFullName(Element proteinElement) {
if (proteinElement == null) {
return "";
} else {
Element recElem = proteinElement.getChild(PROTEIN_RECOMMENDED_NAME_TAG_NAME);
if (recElem == null) {
return "";
} else {
return recElem.getChildText(PROTEIN_FULL_NAME_TAG_NAME);
}
}
}
private static String getProteinShortName(Element proteinElement) {
if (proteinElement == null) {
return "";
} else {
Element recElem = proteinElement.getChild(PROTEIN_RECOMMENDED_NAME_TAG_NAME);
if (recElem == null) {
return "";
} else {
return recElem.getChildText(PROTEIN_SHORT_NAME_TAG_NAME);
}
}
}
private void importProteinCitations(XMLElement entryXMLElem,
UniprotGraph<I,RV,RVT,RE,RET> graph,
Protein<I,RV,RVT,RE,RET> protein,
UniprotDataXML uniprotDataXML) {
List<Element> referenceList = entryXMLElem.asJDomElement().getChildren(REFERENCE_TAG_NAME);
for (Element referenceElement : referenceList) {
List<Element> citationsList = referenceElement.getChildren(CITATION_TAG_NAME);
for (Element citation : citationsList) {
String citationType = citation.getAttributeValue(DB_REFERENCE_TYPE_ATTRIBUTE);
List<Person<I,RV,RVT,RE,RET>> authorsPerson = new ArrayList<>();
List<Consortium<I,RV,RVT,RE,RET>> authorsConsortium = new ArrayList<>();
List<Element> authorPersonElems = citation.getChild("authorList").getChildren("person");
List<Element> authorConsortiumElems = citation.getChild("authorList").getChildren("consortium");
for (Element personElement : authorPersonElems) {
Person<I,RV,RVT,RE,RET> person = null;
String personName = personElement.getAttributeValue("name");
Optional<Person<I,RV,RVT,RE,RET>> optionalPerson = graph.personNameIndex().getVertex(personName);
if(!optionalPerson.isPresent()){
person = graph.Person().from(graph.raw().addVertex(null));
person.set(graph.Person().name, personName);
graph.raw().commit();
}else{
person = optionalPerson.get();
}
}
for (Element consortiumElement : authorConsortiumElems) {
Consortium<I,RV,RVT,RE,RET> consortium = null;
String consortiumName = consortiumElement.getAttributeValue("name");
Optional<Consortium<I,RV,RVT,RE,RET>> optionalConsortium = graph.consortiumNameIndex().getVertex(consortiumName);
if(!optionalConsortium.isPresent()){
consortium = graph.Consortium().from(graph.raw().addVertex(null));
consortium.set(graph.Consortium().name, consortiumName);
graph.raw().commit();
}else{
consortium = optionalConsortium.get();
}
}
//----------------------------------------------------------------------------
//-----------------------------THESIS-----------------------------------------
switch (citationType) {
case THESIS_CITATION_TYPE:
if (uniprotDataXML.getThesis()) {
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}else{
Thesis<I,RV,RVT,RE,RET> thesis = null;
Optional<Thesis<I,RV,RVT,RE,RET>> optionalThesis = graph.thesisTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalThesis.isPresent()){
thesis = graph.Thesis().from(graph.raw().addVertex(null));
thesis.set(graph.Thesis().title, titleSt);
//-----------institute-----------------------------
String instituteSt = citation.getAttributeValue("institute");
String countrySt = citation.getAttributeValue("country");
reference = graph.Reference().from(graph.raw().addVertex(null));
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceThesis(), thesis);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
if (instituteSt != null) {
Institute<I,RV,RVT,RE,RET> institute = null;
Optional<Institute<I,RV,RVT,RE,RET>> optionalInstitute = graph.instituteNameIndex().getVertex(instituteSt);
if(!optionalInstitute.isPresent()){
institute = graph.Institute().from(graph.raw().addVertex(null));
institute.set(graph.Institute().name, instituteSt);
graph.raw().commit();
}else{
institute = optionalInstitute.get();
}
if (countrySt != null) {
Country<I,RV,RVT,RE,RET> country = null;
Optional<Country<I,RV,RVT,RE,RET>> optionalCountry = graph.countryNameIndex().getVertex(countrySt);
if(!optionalCountry.isPresent()){
country = graph.Country().from(graph.raw().addVertex(null));
country.set(graph.Country().name, countrySt);
graph.raw().commit();
}else{
country = optionalCountry.get();
}
institute.addOutEdge(graph.InstituteCountry(), country);
}
thesis.addOutEdge(graph.ThesisInstitute(), institute);
}
}else{
thesis = optionalThesis.get();
reference = thesis.referenceThesis_inV();
}
//--protein reference citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------PATENT-----------------------------------------
break;
case PATENT_CITATION_TYPE:
if (uniprotDataXML.getPatents()) {
String numberSt = citation.getAttributeValue("number");
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}
if (numberSt == null) {
numberSt = "";
}
if (!numberSt.equals("")) {
Patent<I,RV,RVT,RE,RET> patent = null;
Optional<Patent<I,RV,RVT,RE,RET>> optionalPatent = graph.patentNumberIndex().getVertex(numberSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalPatent.isPresent()){
patent = graph.Patent().from(graph.raw().addVertex(null));
patent.set(graph.Patent().number, numberSt);
patent.set(graph.Patent().title, titleSt);
graph.raw().commit();
reference = graph.Reference().from(graph.raw().addVertex(null));
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferencePatent(), patent);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
}else{
patent = optionalPatent.get();
reference = patent.referencePatent_inV();
}
//--protein citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------SUBMISSION-----------------------------------------
break;
case SUBMISSION_CITATION_TYPE:
if (uniprotDataXML.getSubmissions()) {
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
String dbSt = citation.getAttributeValue("db");
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}else{
Submission<I,RV,RVT,RE,RET> submission = null;
Optional<Submission<I,RV,RVT,RE,RET>> optionalSubmission = graph.submissionTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalSubmission.isPresent()){
submission = graph.Submission().from(graph.raw().addVertex(null));
submission.set(graph.Submission().title, titleSt);
graph.raw().commit();
reference = graph.Reference().from(graph.raw().addVertex(null));
reference.set(graph.Reference().date, dateSt);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
for(Consortium<I,RV,RVT,RE,RET> consortium : authorsConsortium){
reference.addOutEdge(graph.ReferenceAuthorConsortium(), consortium);
}
if (dbSt != null) {
DB<I,RV,RVT,RE,RET> db = null;
Optional<DB<I,RV,RVT,RE,RET>> optionalDB = graph.dbNameIndex().getVertex(dbSt);
if(!optionalDB.isPresent()){
db = graph.DB().from(graph.raw().addVertex(null));
db.set(graph.DB().name, dbSt);
graph.raw().commit();
}else{
db = optionalDB.get();
}
//-----submission db relationship-----
submission.addOutEdge(graph.SubmissionDB(), db);
}
reference.addOutEdge(graph.ReferenceSubmission(), submission);
}else{
submission = optionalSubmission.get();
reference = submission.referenceSubmission_inV();
}
//--protein citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------BOOK-----------------------------------------
break;
case BOOK_CITATION_TYPE:
if (uniprotDataXML.getBooks()) {
String nameSt = citation.getAttributeValue("name");
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
String publisherSt = citation.getAttributeValue("publisher");
String firstSt = citation.getAttributeValue("first");
String lastSt = citation.getAttributeValue("last");
String citySt = citation.getAttributeValue("city");
String volumeSt = citation.getAttributeValue("volume");
if (nameSt == null) {
nameSt = "";
}
if (dateSt == null) {
dateSt = "";
}
if (titleSt == null) {
titleSt = "";
}
if (publisherSt == null) {
publisherSt = "";
}
if (firstSt == null) {
firstSt = "";
}
if (lastSt == null) {
lastSt = "";
}
if (citySt == null) {
citySt = "";
}
if (volumeSt == null) {
volumeSt = "";
}
Book<I,RV,RVT,RE,RET> book = null;
Optional<Book<I,RV,RVT,RE,RET>> optionalBook = graph.bookNameIndex().getVertex(nameSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalBook.isPresent()){
book = graph.Book().from(graph.raw().addVertex(null));
book.set(graph.Book().name, nameSt);
graph.raw().commit();
reference = graph.Reference().from(graph.raw().addVertex(null));
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceBook(), book);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//---editor association-----
Element editorListElem = citation.getChild("editorList");
if (editorListElem != null) {
List<Element> editorsElems = editorListElem.getChildren("person");
for (Element personElement : editorsElems) {
Person<I,RV,RVT,RE,RET> editor = null;
String personName = personElement.getAttributeValue("name");
Optional<Person<I,RV,RVT,RE,RET>> optionalPerson = graph.personNameIndex().getVertex(personName);
if(!optionalPerson.isPresent()){
editor = graph.Person().from(graph.raw().addVertex(null));
editor.set(graph.Person().name, personName);
graph.raw().commit();
}else{
editor = optionalPerson.get();
}
book.addOutEdge(graph.BookEditor(), editor);
}
}
//----publisher--
if (!publisherSt.equals("")) {
Publisher<I,RV,RVT,RE,RET> publisher = null;
Optional<Publisher<I,RV,RVT,RE,RET>> optionalPublisher = graph.publisherNameIndex().getVertex(publisherSt);
if(!optionalPublisher.isPresent()){
publisher = graph.Publisher().from(graph.raw().addVertex(null));
publisher.set(graph.Publisher().name, publisherSt);
graph.raw().commit();
}else{
publisher = optionalPublisher.get();
}
book.addOutEdge(graph.BookPublisher(), publisher);
}
//-----city-----
if (!citySt.equals("")) {
City<I,RV,RVT,RE,RET> city = null;
Optional<City<I,RV,RVT,RE,RET>> optionalCity = graph.cityNameIndex().getVertex(citySt);
if(!optionalCity.isPresent()){
city = graph.City().from(graph.raw().addVertex(null));
city.set(graph.City().name, citySt);
graph.raw().commit();
}else{
city = optionalCity.get();
}
book.addOutEdge(graph.BookCity(), city);
}
}else{
book = optionalBook.get();
reference = book.referenceBook_inV();
}
//--protein citation relationship
protein.addOutEdge(graph.ProteinReference(), reference);
// TODO see if these fields can somehow be included
// bookProteinCitationProperties.put(BookProteinCitationRel.FIRST_PROPERTY, firstSt);
// bookProteinCitationProperties.put(BookProteinCitationRel.LAST_PROPERTY, lastSt);
// bookProteinCitationProperties.put(BookProteinCitationRel.VOLUME_PROPERTY, volumeSt);
// bookProteinCitationProperties.put(BookProteinCitationRel.TITLE_PROPERTY, titleSt);
}
//----------------------------------------------------------------------------
//-----------------------------ONLINE ARTICLE-----------------------------------------
break;
case ONLINE_ARTICLE_CITATION_TYPE:
if (uniprotDataXML.getOnlineArticles()) {
String locatorSt = citation.getChildText("locator");
String nameSt = citation.getAttributeValue("name");
String titleSt = citation.getChildText("title");
String dateSt = citation.getAttributeValue("date");
if (titleSt == null) {
titleSt = "";
}
if (nameSt == null) {
nameSt = "";
}
if (locatorSt == null) {
locatorSt = "";
}
if (dateSt == null) {
dateSt = "";
}
if (!titleSt.equals("")) {
OnlineArticle<I,RV,RVT,RE,RET> onlineArticle = null;
Optional<OnlineArticle<I,RV,RVT,RE,RET>> optionalOnlineArticle = graph.onlineArticleTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalOnlineArticle.isPresent()){
onlineArticle = graph.OnlineArticle().from(graph.raw().addVertex(null));
onlineArticle.set(graph.OnlineArticle().title, titleSt);
graph.raw().commit();
reference = graph.Reference().from(graph.raw().addVertex(null));
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceOnlineArticle(), onlineArticle);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//---consortiums association----
for(Consortium<I,RV,RVT,RE,RET> consortium : authorsConsortium){
reference.addOutEdge(graph.ReferenceAuthorConsortium(), consortium);
}
//------online journal-----------
if (!nameSt.equals("")) {
OnlineJournal<I,RV,RVT,RE,RET> onlineJournal = null;
Optional<OnlineJournal<I,RV,RVT,RE,RET>> optionalOnlineJournal = graph.onlineJournalNameIndex().getVertex(nameSt);
if(!optionalOnlineJournal.isPresent()){
onlineJournal = graph.OnlineJournal().from(graph.raw().addVertex(null));
onlineJournal.set(graph.OnlineJournal().name, nameSt);
graph.raw().commit();
}else{
onlineJournal = optionalOnlineJournal.get();
}
OnlineArticleOnlineJournal<I,RV,RVT,RE,RET> onlineArticleOnlineJournal = onlineArticle.addOutEdge(graph.OnlineArticleOnlineJournal(), onlineJournal);
onlineArticleOnlineJournal.set(graph.OnlineArticleOnlineJournal().locator, locatorSt);
}
//----------------------------
}else{
onlineArticle = optionalOnlineArticle.get();
reference = onlineArticle.referenceOnlineArticle_inV();
}
//protein citation
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//-----------------------------ARTICLE-----------------------------------------
break;
case ARTICLE_CITATION_TYPE:
if (uniprotDataXML.getArticles()) {
String journalNameSt = citation.getAttributeValue("name");
String dateSt = citation.getAttributeValue("date");
String titleSt = citation.getChildText("title");
String firstSt = citation.getAttributeValue("first");
String lastSt = citation.getAttributeValue("last");
String volumeSt = citation.getAttributeValue("volume");
String doiSt = "";
String medlineSt = "";
String pubmedId = "";
if (journalNameSt == null) {
journalNameSt = "";
}
if (dateSt == null) {
dateSt = "";
}
if (firstSt == null) {
firstSt = "";
}
if (lastSt == null) {
lastSt = "";
}
if (volumeSt == null) {
volumeSt = "";
}
if (titleSt == null) {
titleSt = "";
}
List<Element> dbReferences = citation.getChildren("dbReference");
for (Element tempDbRef : dbReferences) {
switch (tempDbRef.getAttributeValue("type")) {
case "DOI":
doiSt = tempDbRef.getAttributeValue("id");
break;
case "MEDLINE":
medlineSt = tempDbRef.getAttributeValue("id");
break;
case "PubMed":
pubmedId = tempDbRef.getAttributeValue("id");
break;
}
}
if (titleSt != "") {
Article<I,RV,RVT,RE,RET> article = null;
Optional<Article<I,RV,RVT,RE,RET>> optionalArticle = graph.articleTitleIndex().getVertex(titleSt);
Reference<I,RV,RVT,RE,RET> reference = null;
if(!optionalArticle.isPresent()){
article = graph.Article().from(graph.raw().addVertex(null));
article.set(graph.Article().title, titleSt);
article.set(graph.Article().doId, doiSt);
graph.raw().commit();
if(pubmedId != ""){
Pubmed<I,RV,RVT,RE,RET> pubmed = null;
Optional<Pubmed<I,RV,RVT,RE,RET>> optionalPubmed = graph.pubmedIdIndex().getVertex(pubmedId);
if(!optionalPubmed.isPresent()){
pubmed = graph.Pubmed().from(graph.raw().addVertex(null));
pubmed.set(graph.Pubmed().id, pubmedId);
graph.raw().commit();
}else{
pubmed = optionalPubmed.get();
}
article.addOutEdge(graph.ArticlePubmed(), pubmed);
}
reference = graph.Reference().from(graph.raw().addVertex(null));
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceArticle(), article);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//---consortiums association----
for(Consortium<I,RV,RVT,RE,RET> consortium : authorsConsortium){
reference.addOutEdge(graph.ReferenceAuthorConsortium(), consortium);
}
//------journal-----------
if (!journalNameSt.equals("")) {
Journal<I,RV,RVT,RE,RET> journal = null;
Optional<Journal<I,RV,RVT,RE,RET>> optionalJournal = graph.journalNameIndex().getVertex(journalNameSt);
if(!optionalJournal.isPresent()){
journal = graph.Journal().from(graph.raw().addVertex(null));
journal.set(graph.Journal().name, journalNameSt);
graph.raw().commit();
}else{
journal = optionalJournal.get();
}
ArticleJournal<I,RV,RVT,RE,RET> articleJournal = article.addOutEdge(graph.ArticleJournal(), journal);
articleJournal.set(graph.ArticleJournal().volume, volumeSt);
articleJournal.set(graph.ArticleJournal().first, firstSt);
articleJournal.set(graph.ArticleJournal().last, lastSt);
}
//----------------------------
}else{
article = optionalArticle.get();
reference = article.referenceArticle_inV();
}
//protein citation
protein.addOutEdge(graph.ProteinReference(), reference);
}
}
//----------------------------------------------------------------------------
//----------------------UNPUBLISHED OBSERVATIONS-----------------------------------------
break;
case UNPUBLISHED_OBSERVATION_CITATION_TYPE:
if (uniprotDataXML.getUnpublishedObservations()) {
String dateSt = citation.getAttributeValue("date");
String scopeSt = referenceElement.getChildText("scope");
if (dateSt == null) {
dateSt = "";
}
if (scopeSt == null){
scopeSt = "";
}
UnpublishedObservation<I,RV,RVT,RE,RET> unpublishedObservation = graph.UnpublishedObservation().from(graph.raw().addVertex(null));
unpublishedObservation.set(graph.UnpublishedObservation().scope, scopeSt);
Reference<I,RV,RVT,RE,RET> reference = graph.Reference().from(graph.raw().addVertex(null));
reference.set(graph.Reference().date, dateSt);
reference.addOutEdge(graph.ReferenceUnpublishedObservation(), unpublishedObservation);
//---authors association-----
for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
reference.addOutEdge(graph.ReferenceAuthorPerson(), person);
}
//protein citation
protein.addOutEdge(graph.ProteinReference(), reference);
}
break;
}
}
}
}
protected Date parseDate(String date) throws ParseException {
return dateFormat.parse(date);
}
}
| making some progress on the update/fix regarding how vertices are created
| src/main/java/com/bio4j/model/uniprot/programs/ImportUniprot.java | making some progress on the update/fix regarding how vertices are created | <ide><path>rc/main/java/com/bio4j/model/uniprot/programs/ImportUniprot.java
<ide>
<ide> if(!diseaseOptional.isPresent()){
<ide>
<del> disease = graph.Disease().from(graph.raw().addVertex(null));
<add> disease = graph.addVertex(graph.Disease());
<ide> disease.set(graph.Disease().name, diseaseName);
<ide> disease.set(graph.Disease().id, diseaseId);
<ide> disease.set(graph.Disease().acronym, diseaseAcronym);
<ide> Optional<SubcellularLocation<I,RV,RVT,RE,RET>> lastLocationOptional = graph.subcellularLocationNameIndex().getVertex(firstLocationSt);
<ide>
<ide> if(!lastLocationOptional.isPresent()){
<del> lastLocation = graph.SubcellularLocation().from(graph.raw().addVertex(null));
<add> lastLocation = graph.addVertex(graph.SubcellularLocation());
<ide> lastLocation.set(graph.SubcellularLocation().name, firstLocationSt);
<ide> graph.raw().commit();
<ide> }else{
<ide> Optional<SubcellularLocation<I,RV,RVT,RE,RET>> tempLocationOptional = graph.subcellularLocationNameIndex().getVertex(tempLocationSt);
<ide>
<ide> if(!tempLocationOptional.isPresent()){
<del> tempLocation = graph.SubcellularLocation().from(graph.raw().addVertex(null));
<add> tempLocation = graph.addVertex(graph.SubcellularLocation());
<ide> tempLocation.set(graph.SubcellularLocation().name, tempLocationSt);
<ide> graph.raw().commit();
<ide> }else{
<ide> Optional<Isoform<I,RV,RVT,RE,RET>> isoformOptional = graph.isoformIdIndex().getVertex(isoformIdSt);
<ide> Isoform<I,RV,RVT,RE,RET> isoform;
<ide> if(!isoformOptional.isPresent()){
<del> isoform = graph.Isoform().from(graph.raw().addVertex(null));
<add> isoform = graph.addVertex(graph.Isoform());
<ide> isoform.set(graph.Isoform().name, isoformNameSt);
<ide> isoform.set(graph.Isoform().note, isoformNoteSt);
<ide> isoform.set(graph.Isoform().sequence, isoformSeqSt);
<ide> if(alternativeProductOptional.isPresent()){
<ide> alternativeProduct = alternativeProductOptional.get();
<ide> }else{
<del> alternativeProduct = graph.AlternativeProduct().from(graph.raw().addVertex(null));
<add> alternativeProduct = graph.addVertex(graph.AlternativeProduct());
<ide> alternativeProduct.set(graph.AlternativeProduct().name, eventTypeSt);
<ide> graph.raw().commit();
<ide> }
<ide>
<ide> if(!sequenceCautionOptional.isPresent()){
<ide>
<del> sequenceCaution = graph.SequenceCaution().from(graph.raw().addVertex(null));
<add> sequenceCaution = graph.addVertex(graph.SequenceCaution());
<ide> sequenceCaution.set(graph.SequenceCaution().name, conflictTypeSt);
<ide> graph.raw().commit();
<ide>
<ide> String personName = personElement.getAttributeValue("name");
<ide> Optional<Person<I,RV,RVT,RE,RET>> optionalPerson = graph.personNameIndex().getVertex(personName);
<ide> if(!optionalPerson.isPresent()){
<del> person = graph.Person().from(graph.raw().addVertex(null));
<add> person = graph.addVertex(graph.Person());
<ide> person.set(graph.Person().name, personName);
<ide> graph.raw().commit();
<ide> }else{
<ide> String consortiumName = consortiumElement.getAttributeValue("name");
<ide> Optional<Consortium<I,RV,RVT,RE,RET>> optionalConsortium = graph.consortiumNameIndex().getVertex(consortiumName);
<ide> if(!optionalConsortium.isPresent()){
<del> consortium = graph.Consortium().from(graph.raw().addVertex(null));
<add> consortium = graph.addVertex(graph.Consortium());
<ide> consortium.set(graph.Consortium().name, consortiumName);
<ide> graph.raw().commit();
<ide> }else{
<ide>
<ide> if(!optionalThesis.isPresent()){
<ide>
<del> thesis = graph.Thesis().from(graph.raw().addVertex(null));
<add> thesis = graph.addVertex(graph.Thesis());
<ide> thesis.set(graph.Thesis().title, titleSt);
<ide>
<ide> //-----------institute-----------------------------
<ide> String instituteSt = citation.getAttributeValue("institute");
<ide> String countrySt = citation.getAttributeValue("country");
<ide>
<del> reference = graph.Reference().from(graph.raw().addVertex(null));
<add> reference = graph.addVertex(graph.Reference());
<ide> reference.set(graph.Reference().date, dateSt);
<ide> reference.addOutEdge(graph.ReferenceThesis(), thesis);
<ide>
<ide>
<ide> if(!optionalInstitute.isPresent()){
<ide>
<del> institute = graph.Institute().from(graph.raw().addVertex(null));
<add> institute = graph.addVertex(graph.Institute());
<ide> institute.set(graph.Institute().name, instituteSt);
<ide> graph.raw().commit();
<ide>
<ide> Country<I,RV,RVT,RE,RET> country = null;
<ide> Optional<Country<I,RV,RVT,RE,RET>> optionalCountry = graph.countryNameIndex().getVertex(countrySt);
<ide> if(!optionalCountry.isPresent()){
<del> country = graph.Country().from(graph.raw().addVertex(null));
<add> country = graph.addVertex(graph.Country());
<ide> country.set(graph.Country().name, countrySt);
<ide> graph.raw().commit();
<ide> }else{
<ide>
<ide> if(!optionalPatent.isPresent()){
<ide>
<del> patent = graph.Patent().from(graph.raw().addVertex(null));
<add> patent = graph.addVertex(graph.Patent());
<ide> patent.set(graph.Patent().number, numberSt);
<ide> patent.set(graph.Patent().title, titleSt);
<ide> graph.raw().commit();
<ide>
<del> reference = graph.Reference().from(graph.raw().addVertex(null));
<add> reference = graph.addVertex(graph.Reference());
<ide> reference.set(graph.Reference().date, dateSt);
<ide> reference.addOutEdge(graph.ReferencePatent(), patent);
<ide>
<ide>
<ide> if(!optionalSubmission.isPresent()){
<ide>
<del> submission = graph.Submission().from(graph.raw().addVertex(null));
<add> submission = graph.addVertex(graph.Submission());
<ide> submission.set(graph.Submission().title, titleSt);
<ide> graph.raw().commit();
<ide>
<del> reference = graph.Reference().from(graph.raw().addVertex(null));
<add> reference = graph.addVertex(graph.Reference());
<ide> reference.set(graph.Reference().date, dateSt);
<ide> //---authors association-----
<ide> for (Person<I,RV,RVT,RE,RET> person : authorsPerson) {
<ide>
<ide> if(!optionalBook.isPresent()){
<ide>
<del> book = graph.Book().from(graph.raw().addVertex(null));
<add> book = graph.addVertex(graph.Book());
<ide> book.set(graph.Book().name, nameSt);
<ide> graph.raw().commit();
<ide>
<del> reference = graph.Reference().from(graph.raw().addVertex(null));
<add> reference = graph.addVertex(graph.Reference());
<ide> reference.set(graph.Reference().date, dateSt);
<ide> reference.addOutEdge(graph.ReferenceBook(), book);
<ide>
<ide> Optional<Person<I,RV,RVT,RE,RET>> optionalPerson = graph.personNameIndex().getVertex(personName);
<ide>
<ide> if(!optionalPerson.isPresent()){
<del> editor = graph.Person().from(graph.raw().addVertex(null));
<add> editor = graph.addVertex(graph.Person());
<ide> editor.set(graph.Person().name, personName);
<ide> graph.raw().commit();
<ide> }else{
<ide>
<ide> if(!optionalPublisher.isPresent()){
<ide>
<del> publisher = graph.Publisher().from(graph.raw().addVertex(null));
<add> publisher = graph.addVertex(graph.Publisher());
<ide> publisher.set(graph.Publisher().name, publisherSt);
<ide> graph.raw().commit();
<ide>
<ide>
<ide> if(!optionalCity.isPresent()){
<ide>
<del> city = graph.City().from(graph.raw().addVertex(null));
<add> city = graph.addVertex(graph.City());
<ide> city.set(graph.City().name, citySt);
<ide> graph.raw().commit();
<ide>
<ide>
<ide> if(!optionalOnlineArticle.isPresent()){
<ide>
<del> onlineArticle = graph.OnlineArticle().from(graph.raw().addVertex(null));
<add> onlineArticle = graph.addVertex(graph.OnlineArticle());
<ide> onlineArticle.set(graph.OnlineArticle().title, titleSt);
<ide> graph.raw().commit();
<ide>
<del> reference = graph.Reference().from(graph.raw().addVertex(null));
<add> reference = graph.addVertex(graph.Reference());
<ide> reference.set(graph.Reference().date, dateSt);
<ide> reference.addOutEdge(graph.ReferenceOnlineArticle(), onlineArticle);
<ide>
<ide>
<ide> if(!optionalOnlineJournal.isPresent()){
<ide>
<del> onlineJournal = graph.OnlineJournal().from(graph.raw().addVertex(null));
<add> onlineJournal = graph.addVertex(graph.OnlineJournal());
<ide> onlineJournal.set(graph.OnlineJournal().name, nameSt);
<ide> graph.raw().commit();
<ide>
<ide>
<ide> if(!optionalArticle.isPresent()){
<ide>
<del> article = graph.Article().from(graph.raw().addVertex(null));
<add> article = graph.addVertex(graph.Article());
<ide> article.set(graph.Article().title, titleSt);
<ide> article.set(graph.Article().doId, doiSt);
<ide> graph.raw().commit();
<ide> Optional<Pubmed<I,RV,RVT,RE,RET>> optionalPubmed = graph.pubmedIdIndex().getVertex(pubmedId);
<ide>
<ide> if(!optionalPubmed.isPresent()){
<del> pubmed = graph.Pubmed().from(graph.raw().addVertex(null));
<add> pubmed = graph.addVertex(graph.Pubmed());
<ide> pubmed.set(graph.Pubmed().id, pubmedId);
<ide> graph.raw().commit();
<ide> }else{
<ide> article.addOutEdge(graph.ArticlePubmed(), pubmed);
<ide> }
<ide>
<del> reference = graph.Reference().from(graph.raw().addVertex(null));
<add> reference = graph.addVertex(graph.Reference());
<ide> reference.set(graph.Reference().date, dateSt);
<ide> reference.addOutEdge(graph.ReferenceArticle(), article);
<ide>
<ide> Optional<Journal<I,RV,RVT,RE,RET>> optionalJournal = graph.journalNameIndex().getVertex(journalNameSt);
<ide>
<ide> if(!optionalJournal.isPresent()){
<del> journal = graph.Journal().from(graph.raw().addVertex(null));
<add> journal = graph.addVertex(graph.Journal());
<ide> journal.set(graph.Journal().name, journalNameSt);
<ide> graph.raw().commit();
<ide> }else{
<ide> }
<ide>
<ide>
<del> UnpublishedObservation<I,RV,RVT,RE,RET> unpublishedObservation = graph.UnpublishedObservation().from(graph.raw().addVertex(null));
<add> UnpublishedObservation<I,RV,RVT,RE,RET> unpublishedObservation = graph.addVertex(graph.UnpublishedObservation());
<ide> unpublishedObservation.set(graph.UnpublishedObservation().scope, scopeSt);
<ide>
<del> Reference<I,RV,RVT,RE,RET> reference = graph.Reference().from(graph.raw().addVertex(null));
<add> Reference<I,RV,RVT,RE,RET> reference = graph.addVertex(graph.Reference());
<ide> reference.set(graph.Reference().date, dateSt);
<ide> reference.addOutEdge(graph.ReferenceUnpublishedObservation(), unpublishedObservation);
<ide> |
|
Java | mit | 4b458b83459238f43d1d036f15b58f352dfb2e6a | 0 | micheljung/faf-java-api,FAForever/faf-java-api,FAForever/faf-java-api,FAForever/faf-java-api,micheljung/faf-java-api | package com.faforever.api.data.listeners;
import com.faforever.api.data.domain.Game;
import com.faforever.api.game.GameService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import javax.persistence.PostLoad;
@Component
public class GameEnricher {
private static GameService gameService;
@Inject
public void init(GameService gameService) {
GameEnricher.gameService = gameService;
}
@PostLoad
public void enrich(Game game) {
game.setReplayUrl(gameService.getReplayDownloadUrl(game.getId()));
game.setName(StringEscapeUtils.unescapeHtml4(game.getName()));
}
}
| src/main/java/com/faforever/api/data/listeners/GameEnricher.java | package com.faforever.api.data.listeners;
import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Game;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import javax.persistence.PostLoad;
@Component
public class GameEnricher {
private static FafApiProperties fafApiProperties;
@Inject
public void init(FafApiProperties fafApiProperties) {
GameEnricher.fafApiProperties = fafApiProperties;
}
@PostLoad
public void enrich(Game game) {
game.setReplayUrl(String.format(fafApiProperties.getReplay().getDownloadUrlFormat(), game.getId()));
game.setName(StringEscapeUtils.unescapeHtml4(game.getName()));
}
}
| Fix broken replay url in game entity
| src/main/java/com/faforever/api/data/listeners/GameEnricher.java | Fix broken replay url in game entity | <ide><path>rc/main/java/com/faforever/api/data/listeners/GameEnricher.java
<ide> package com.faforever.api.data.listeners;
<ide>
<del>import com.faforever.api.config.FafApiProperties;
<ide> import com.faforever.api.data.domain.Game;
<add>import com.faforever.api.game.GameService;
<ide> import org.apache.commons.lang3.StringEscapeUtils;
<ide> import org.springframework.stereotype.Component;
<ide>
<ide> @Component
<ide> public class GameEnricher {
<ide>
<del> private static FafApiProperties fafApiProperties;
<add> private static GameService gameService;
<ide>
<ide> @Inject
<del> public void init(FafApiProperties fafApiProperties) {
<del> GameEnricher.fafApiProperties = fafApiProperties;
<add> public void init(GameService gameService) {
<add> GameEnricher.gameService = gameService;
<ide> }
<ide>
<ide> @PostLoad
<ide> public void enrich(Game game) {
<del> game.setReplayUrl(String.format(fafApiProperties.getReplay().getDownloadUrlFormat(), game.getId()));
<add> game.setReplayUrl(gameService.getReplayDownloadUrl(game.getId()));
<ide> game.setName(StringEscapeUtils.unescapeHtml4(game.getName()));
<ide> }
<ide> } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.