I need to create TradeCaptureReport FIX messages. It was clear how to do this until I tried to create Parties:
...
<RptSide Ccy="USD" ... >
<Pty Src="D" ID="1111" R="11">
<Sub ID="AA" Typ="4010"/>
<Sub ID="AA" Typ="4013"/>
</Pty>
<Pty Src="D" ID="1360" R="1"/>
</RptSide>
RptSide/Pty - 453
RptSide/Pty/#ID - 448
RptSide/Pty/#Src - 447
RptSide/Pty/#R - 452
RptSide/Pty/Sub - 802
RptSide/Pty/Sub/#ID - 523
RptSide/Pty/Sub/#Typ - 803
final TradeCaptureReport tradeCaptureReport = new TradeCaptureReport();
...
final Instrument instrument = new Instrument();
tradeCaptureReport.set(instrument);
...
// (552) RptSide/*
TradeCaptureReport.NoSides rptSide = new TradeCaptureReport.NoSides();
tradeCaptureReport.addGroup(rptSide);
// (15) RptSide/#Ccy (Currency)
rptSide.set(new Currency("USD"));
...
// (453) RptSide/Pty/*:
Parties parties = new Parties();
rptSide.setGroups(parties);
// (802) RptSide/Pty/Sub/* (NoPartySubIDs)
NoPartySubIDs sub = new NoPartySubIDs();
// (523) RptSide/Pty/Sub/#ID (PartySubID)
PartySubID subID1 = new PartySubID("AA");
PartySubID subID2 = new PartySubID("AA");
// (803) RptSide/Pty/Sub/#Typ (PartySubIDType)
PartySubIDType subIdTyp1 = new PartySubIDType(4010);
PartySubIDType subIdTyp2 = new PartySubIDType(4013);
Can somebody give the Java code sample how to create and link them to RptSide (803)?
To create Parties:
...
<RptSide Ccy="USD" ... >
<Pty Src="D" ID="1111" R="11">
<Sub ID="AA" Typ="4010"/>
<Sub ID="AA" Typ="4013"/>
</Pty>
<Pty Src="D" ID="1360" R="1"/>
</RptSide>
it it's possible to code in Java:
final TradeCaptureReport tradeCaptureReport = new TradeCaptureReport();
...
final Instrument instrument = new Instrument();
tradeCaptureReport.set(instrument);
...
// (552) RptSide/*
TradeCaptureReport.NoSides rptSide = new TradeCaptureReport.NoSides();
// (15) RptSide/#Ccy (Currency)
rptSide.set(new Currency("USD"));
...
// (453) RptSide/Pty/*:
// 1-st Pty:
Parties.NoPartyIDs ptyGrp = new Parties.NoPartyIDs();
ptyGrp.set(new PartyID("1111"));
ptyGrp.set(new PartyIDSource('D'));
ptyGrp.set(new PartyRole(11));
Parties.NoPartyIDs.NoPartySubIDs subGrp = new Parties.NoPartyIDs.NoPartySubIDs();
subGrp.set(new PartySubID("AA"));
subGrp.set(new PartySubIDType(4010));
ptyGrp.addGroup(subGrp); // add <Sub ID="AA" Typ="4010"/>
subGrp = new Parties.NoPartyIDs.NoPartySubIDs();
subGrp.set(new PartySubID("AA"));
subGrp.set(new PartySubIDType(4013));
ptyGrp.addGroup(subGrp); //add <Sub ID="AA" Typ="4013"/>
rptSide.addGroup(ptyGrp); // add <Pty Src="D" ID="1111" R="11">... with 2 Sub-s (above)
// 2-nd Pty:
ptyGrp = new Parties.NoPartyIDs();
ptyGrp.set(new PartyID("1360"));
ptyGrp.set(new PartyIDSource('D'));
ptyGrp.set(new PartyRole(1));
rptSide.addGroup(ptyGrp); // add <Pty Src="D" ID="1360" R="1"/>
tradeCaptureReport.addGroup(rptSide); // add <RptSide Ccy="USD" ... > with nested Pty-s
I'm not confident that it's according to the rules, but at least it creates expected fix message. So the suggestion: "If you've already read it [doc], read it again" was helpful (many thanks to Grant Birchmeier).
Related
In android api 22 I can use only this function to create keys and certificate:
Calendar notBefore = Calendar.getInstance();
Calendar notAfter = Calendar.getInstance();
notAfter.add(Calendar.YEAR, 2);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getApplicationContext())
.setAlias(KEY_ALIAS_CSR)
.setKeySize(2048)
.setSubject(new X500Principal(
"CN=Your Company ," +
" O=Your Organization" +
" C=Your Coountry"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(notBefore.getTime())
.setEndDate(notAfter.getTime())
.build();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
generator.initialize(spec);
generator.generateKeyPair();
I there possibility to set Purpose_Sign of this certificate?
In Api > 23 is easy:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(
"key1",
KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.build());
Solved!
String principal = String.format(CN_PATTERN, cn);
ContentSigner signer = new JCESigner((PrivateKey) keyStore.getKey(KEY_ALIAS_TLS, null), DEFAULT_SIGNATURE_ALGORITHM);
PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
new X500Name(principal), keyStore.getCertificate(KEY_ALIAS_TLS).getPublicKey());
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
**extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(
true));
extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment
));
extensionsGenerator.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));**
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
extensionsGenerator.generate());
PKCS10CertificationRequest csr = csrBuilder.build(signer);
I am trying to upload a large file (90 MB for now) to S3 using Akka HTTP with Alpakka S3 connector. It is working fine for small files (25 MB) but when I try to upload large file (90 MB), I got the following error:
akka.http.scaladsl.model.ParsingException: Unexpected end of multipart entity
at akka.http.scaladsl.unmarshalling.MultipartUnmarshallers$$anonfun$1.applyOrElse(MultipartUnmarshallers.scala:108)
at akka.http.scaladsl.unmarshalling.MultipartUnmarshallers$$anonfun$1.applyOrElse(MultipartUnmarshallers.scala:103)
at akka.stream.impl.fusing.Collect$$anon$6.$anonfun$wrappedPf$1(Ops.scala:227)
at akka.stream.impl.fusing.SupervisedGraphStageLogic.withSupervision(Ops.scala:186)
at akka.stream.impl.fusing.Collect$$anon$6.onPush(Ops.scala:229)
at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:523)
at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:510)
at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:376)
at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:606)
at akka.stream.impl.fusing.GraphInterpreterShell$AsyncInput.execute(ActorGraphInterpreter.scala:485)
at akka.stream.impl.fusing.GraphInterpreterShell.processEvent(ActorGraphInterpreter.scala:581)
at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:749)
at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$shortCircuitBatch(ActorGraphInterpreter.scala:739)
at akka.stream.impl.fusing.ActorGraphInterpreter$$anonfun$receive$1.applyOrElse(ActorGraphInterpreter.scala:765)
at akka.actor.Actor.aroundReceive(Actor.scala:539)
at akka.actor.Actor.aroundReceive$(Actor.scala:537)
at akka.stream.impl.fusing.ActorGraphInterpreter.aroundReceive(ActorGraphInterpreter.scala:671)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:614)
at akka.actor.ActorCell.invoke(ActorCell.scala:583)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:268)
at akka.dispatch.Mailbox.run(Mailbox.scala:229)
at akka.dispatch.Mailbox.exec(Mailbox.scala:241)
at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Although, I get the success message at the end but file does not uploaded completely. It gets upload of 45-50 MB only.
I am using the below code:
S3Utility.scala
class S3Utility(implicit as: ActorSystem, m: Materializer) {
private val bucketName = "test"
def sink(fileInfo: FileInfo): Sink[ByteString, Future[MultipartUploadResult]] = {
val fileName = fileInfo.fileName
S3.multipartUpload(bucketName, fileName)
}
}
Routes:
def uploadLargeFile: Route =
post {
path("import" / "file") {
extractMaterializer { implicit materializer =>
withoutSizeLimit {
fileUpload("file") {
case (metadata, byteSource) =>
logger.info(s"Request received to import large file: ${metadata.fileName}")
val uploadFuture = byteSource.runWith(s3Utility.sink(metadata))
onComplete(uploadFuture) {
case Success(result) =>
logger.info(s"Successfully uploaded file")
complete(StatusCodes.OK)
case Failure(ex) =>
println(ex, "Error in uploading file")
complete(StatusCodes.FailedDependency, ex.getMessage)
}
}
}
}
}
}
Any help would be appraciated. Thanks
Strategy 1
Can you break the file into smaller chunks and retry, here is the sample code:
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("some-kind-of-endpoint"))
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("user", "pass")))
.disableChunkedEncoding()
.withPathStyleAccessEnabled(true)
.build();
// Create a list of UploadPartResponse objects. You get one of these
// for each part upload.
List<PartETag> partETags = new ArrayList<PartETag>();
// Step 1: Initialize.
InitiateMultipartUploadRequest initRequest = new
InitiateMultipartUploadRequest("bucket", "key");
InitiateMultipartUploadResult initResponse =
s3Client.initiateMultipartUpload(initRequest);
File file = new File("filepath");
long contentLength = file.length();
long partSize = 5242880; // Set part size to 5 MB.
try {
// Step 2: Upload parts.
long filePosition = 0;
for (int i = 1; filePosition < contentLength; i++) {
// Last part can be less than 5 MB. Adjust part size.
partSize = Math.min(partSize, (contentLength - filePosition));
// Create a request to upload a part.
UploadPartRequest uploadRequest = new UploadPartRequest()
.withBucketName("bucket").withKey("key")
.withUploadId(initResponse.getUploadId()).withPartNumber(i)
.withFileOffset(filePosition)
.withFile(file)
.withPartSize(partSize);
// Upload part and add response to our list.
partETags.add(
s3Client.uploadPart(uploadRequest).getPartETag());
filePosition += partSize;
}
// Step 3: Complete.
CompleteMultipartUploadRequest compRequest = new
CompleteMultipartUploadRequest(
"bucket",
"key",
initResponse.getUploadId(),
partETags);
s3Client.completeMultipartUpload(compRequest);
} catch (Exception e) {
s3Client.abortMultipartUpload(new AbortMultipartUploadRequest(
"bucket", "key", initResponse.getUploadId()));
}
Strategy 2
Increase the idle-timeout of the Akka HTTP server (just set it to infinite), like the following:
akka.http.server.idle-timeout=infinite
This would increase the time period for which the server expects to be idle. By default its value is 60 seconds. And if the server is not able to upload the file within that time period, it will close the connection and throw "Unexpected end of multipart entity" error.
i am trying to open a crystal report in my website but its giving an error
Here is the code i have tried
protected void report_view(object sender, EventArgs e)
{
ReportDocument cryRpt = new ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;
cryRpt.Load("C:\\Report1.rpt");
crConnectionInfo.ServerName = "local";
crConnectionInfo.DatabaseName = "MyEmployees";
crConnectionInfo.UserID = "MYLAPTOP\\HOME";
CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}
CrystalReportViewer1.ReportSource = cryRpt;
CrystalReportViewer1.RefreshReport();
}
and here is the error shown in CrystalReportViwer
Failed to open the connection. Failed to open the connection. Report1 {1222DD0B-C24E- 4E66-8EE1-7ED7F5F0D6B4}.rpt
i am using visual studio 2010 with Crystal Reports 11
It seems that you are missing a password when declaring the connection details. Try adding it:
crConnectionInfo.ServerName = "local";
crConnectionInfo.DatabaseName = "MyEmployees";
crConnectionInfo.UserID = "MYLAPTOP\\HOME";
crConnectionInfo.Password = "Password"; //Swap with real password of course
Ensure that all file paths and file names are also correct.
Alternatively you can look into the SetDataBaseLogon() method
I need to be able to send a certificate file (.pem, I think), with a get request using scala and dispatch.
How do you do that?
Based on the Java code in #sbridges sample, I came up with the following Scala code using dispatch. It creates a custom SSL context containing the certificates you provide (and only those; the default store of trusted root certificates is not used by this code when verifying the remote host).
class SslAuthenticatingHttp(certData: SslCertificateData) extends Http {
override val client = new AsyncHttpClient(
(new AsyncHttpClientConfig.Builder).setSSLContext(buildSslContext(certData)).build
)
private def buildSslContext(certData: SslCertificateData): SSLContext = {
import certData._
val clientCertStore = loadKeyStore(clientCertificateData, clientCertificatePassword)
val rootCertStore = loadKeyStore(rootCertificateData, rootCertificatePassword)
val keyManagerFactory = KeyManagerFactory.getInstance("SunX509")
keyManagerFactory.init(clientCertStore, clientCertificatePassword.toCharArray)
val keyManagers = keyManagerFactory.getKeyManagers()
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(rootCertStore)
val trustManagers = trustManagerFactory.getTrustManagers()
val context = SSLContext.getInstance("TLS")
context.init(keyManagers, trustManagers, null)
context
}
private def loadKeyStore(keyStoreData: Array[Byte], password: String): KeyStore = {
val store = KeyStore.getInstance(KeyStore.getDefaultType)
store.load(new ByteArrayInputStream(keyStoreData), password.toCharArray)
store
}
}
case class SslCertificateData (
clientCertificateData: Array[Byte],
clientCertificatePassword: String,
rootCertificateData: Array[Byte],
rootCertificatePassword: String)
which would be used as in:
val certificateData = SslCertificateData(/* bytes from .jks file for client cert here */, "secret!",
/* bytes from .jks file for root cert here */, "also secret!")
val http = new SslAuthenticatingHttp(certificateData)
val page = http(req OK as.String)
println(page())
Note that this keeps the certificate data in memory, which is not the most secure way to do it and consumes memory unnecessarily. It may in many cases be more suitable to store an InputStream or a filename in the SslCertificateData case class.
I am assuming you want to do https with client certificates. I think this needs to be set up at the jvm level, there is a good explanation here how to do it.
There seems to be a way to do this with ning directly, as explained here,
the code is copied below,
// read in PEM file and parse with commons-ssl PKCS8Key
// (ca.juliusdavies:not-yet-commons-ssl:0.3.11)
RandomAccessFile in = null;
byte[] b = new byte[(int) certFile.length()];
in = new RandomAccessFile( certFile, "r" );
in.readFully( b );
char[] password = hints.get( "password" ).toString().toCharArray();
PKCS8Key key = new PKCS8Key( b, password );
// create empty key store
store = KeyStore.getInstance( KeyStore.getDefaultType() );
store.load( null, password );
// cert chain is not important if you override the default KeyManager and/or
// TrustManager implementation, IIRC
store.setKeyEntry( alias, key.getPrivateKey(), password, new DefaultCertificate[0] );
// initialize key and trust managers -> default behavior
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( "SunX509" );
// password for key and store have to be the same IIRC
keyManagerFactory.init( store, password );
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
tmf.init( store );
TrustManager[] trustManagers = tmf.getTrustManagers();
// override key and trust managers with desired behavior - for example
// * 'trust everything the server gives us' -> TrustManager#checkServerTrusted
// * 'always return a preset alias to use for auth' -> X509ExtendedKeyManager#chooseClientAlias, X509ExtendedKeyManager#chooseEngineClientAlias
for ( int i = 0; i < keyManagers.length; i++ )
{
if ( keyManagers[i] instanceof X509ExtendedKeyManager )
{
AHCKeyManager ahcKeyManager = new AHCKeyManager( (X509ExtendedKeyManager) keyManagers[i] );
keyManagers[i] = ahcKeyManager;
}
}
for ( int i = 0; i < trustManagers.length; i++ )
{
if ( tm instanceof X509TrustManager )
{
AHCTrustManager ahcTrustManager = new AHCTrustManager( manager, (X509TrustManager) trustManagers[i] );
trustManagers[i] = ahcTrustManager;
}
}
// construct SSLContext and feed to AHC config
SSLContext context = SSLContext.getInstance( "TLS" );
context.init( keyManagers, trustManagers, null );
ahcCfgBuilder.setSSLContext(context);
This is the Login Info Method
private void SetLogonInfo()
{
try
{
LogInfo.ConnectionInfo.ServerName = "ServerName";
LogInfo.ConnectionInfo.UserID = "UserID";
LogInfo.ConnectionInfo.Password = "Password";
LogInfo.ConnectionInfo.DatabaseName = "DataBase";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To create report I used this code
crystalReportViewer1.ReportSource = null;
rptdoc = new ReportDocument();
rptdoc.Load("REPORTS\\TC.rpt");
crystalReportViewer1.SelectionFormula =selectionFormula;
crystalReportViewer1.ReportSource = rptdoc;
rptdoc.Database.Tables[0].ApplyLogOnInfo(LogInfo);
It works well in server system, but if I use this in client systems, it asks for username and password. I'm using Crystal Reports 10. Moreover sometimes it asks for Username password in server system also. How to resolve this?
You're doing things in the wrong order. You need to do the login programmatically BEFORE you load the report on the viewer.
Additionally, I cannot stress enough that you need to test your program on the server machine and a test client machine before you release it to users.
The reason for this error is wrong username, password.
Check username, password and use the code below:
ReportDocument cryRpt = new ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;
//This is for Access Database
crConnectionInfo.ServerName = "" + "" +Application.StartupPath + "\\Database.mdb"; //access Db Path
crConnectionInfo.DatabaseName = "" + "" + Application.StartupPath + "\\Database.mdb";//access Db Path
crConnectionInfo.UserID = "ADMIN";
crConnectionInfo.Password = Program.DBPassword; //access password
//This is for Sql Server
crConnectionInfo.UserID = Program.Severuser; //username
crConnectionInfo.Password = Program.Password;//password
crConnectionInfo.ServerName = Program.server;//servername
crConnectionInfo.DatabaseName = Program.database;//database
string path = "" + Application.StartupPath + "\\supportingfiles\\Invoice.rpt";
cryRpt.Load(path);
CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}
cryRpt.SetParameterValue("invoiceno", Program.billno);
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();