Alternative for api RSAPublicKeyImpl - java-8

I would like to know is there any alternative for below api with same parameters format from java 8
public RSAPublicKeyImpl(BigInteger var1, BigInteger var2)
currently it is depreciated & throwing sun.security.rsa.RSAPublicKeyImpl is internal proprietary API and may be removed in a future release

Try this one:
import java.security.PublicKey
import java.security.KeyFactory
import java.security.spec.RSAPublicKeySpec
PublicKey pk = KeyFactory
.getInstance("RSA")
.generatePublic(new RSAPublicKeySpec(modulus, exponent))

Related

call DjangoRestFramework DetailAPIView() from another view

solution from #brian-destura below
The DRF test client does not work, but the django.test.client does. Odd (?) because it's a DRF APIView being called.
from django.test import Client
client = Client()
result = client.get('/api/place/6873947')
print(result.json)
I have a DRF DetailAPIView() that returns a complex serializer json response to external API queries, so in the browser, and via curl etc. http://localhost:8000/api/place/6873947/ returns a big JSON object. All good. The url entry in the 'api' app looks like this
path('place/<int:pk>/', views.PlaceDetailAPIView.as_view(), name='place-detail'),
I need to use that in another, function-based view, so first I tried using both django.test.Client and rest_framework.test.APIClient, e.g.
from rest_framework.test import APIClient
from django.urls import reverse
client = APIClient()
url = '/api/place/6873947/'
res = client.get(url)
That gets an empty result. With django Client:
from django.test import Client
c=Client()
Then
res = c.get('/api/place?pk=6873947')
and
res = c.get('/api/place/', {'pk': 6873947})
Both return "as_view() takes 1 positional argument but 2 were given"
I've tried other approaches in my IDE, picked up in StackOverflow, starting with
from api.views import PlaceDetailAPIView
pid = 6873947
from django.test import Client
from django.http import HttpRequest
from places.models import Place
request = HttpRequest()
request.method='GET'
request.GET = {"pk": pid}
Then
res = PlaceDetailAPIView.as_view({"pk": pid})
"as_view() takes 1 positional argument but 2 were given"
res = PlaceDetailAPIView.as_view()(request=request)
"Expected view PlaceDetailAPIView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly"
res = PlaceDetailAPIView.as_view()(request=request._request)
"HttpRequest' object has no attribute '_request"
I must be missing something basic, but hours of thrashing has gotten me nowhere - ideas?

How to generate SAS token using python legacy SDK(2.1) without account_key or connection_string

I am using python3.6 and azure-storage-blob(version = 1.5.0) and trying to use user assigned managed identity to connect to my azure storage blob from an Azure VM.The problem I am facing is I want to generate the SAS token to form a downloadable url.
I am using blob_service = BlockBlobService(account name,token credential) to authenticate. But I am not able to find any methods which let me generate SAS token without supplying the account key.
Also not seeing any way of using the user delegation key as is available in the new azure-storage-blob (versions>=12.0.0). Is there any workaround or I will need to upgrade the azure storage library at the end.
I tried to reproduce in my environment to generate SAS token without account key or connection string got result successfully.
Code:
import datetime as dt
import json
import os
from azure.identity import DefaultAzureCredential
from azure.storage.blob import (
BlobClient,
BlobSasPermissions,
BlobServiceClient,
generate_blob_sas,
)
credential = DefaultAzureCredential(exclude_shared_token_cache_credential=True)
storage_acct_name = "Accountname"
container_name = "containername"
blob_name = "Filename"
url = f"https://<Accountname>.blob.core.windows.net"
blob_service_client = BlobServiceClient(url, credential=credential)
udk = blob_service_client.get_user_delegation_key(
key_start_time=dt.datetime.utcnow() - dt.timedelta(hours=1),
key_expiry_time=dt.datetime.utcnow() + dt.timedelta(hours=1))
sas = generate_blob_sas(
account_name=storage_acct_name,
container_name=container_name,
blob_name=blob_name,
user_delegation_key=udk,
permission=BlobSasPermissions(read=True),
start = dt.datetime.utcnow() - dt.timedelta(minutes=15),
expiry = dt.datetime.utcnow() + dt.timedelta(hours=2),
)
sas_url = (
f'https://{storage_acct_name}.blob.core.windows.net/'
f'{container_name}/{blob_name}?{sas}'
)
print(sas_url)
Output:
Make sure you need to add storage blob data contributor role as below:

How can I use ImageAnnotatorClient with explicit authentication?

It is clear how to use Storageclient with explicit authentication. It is also clear how to use ImageAnnotatorClient with implicit authentication. But how to use explicit authentication for ImageAnnotatorClient? It does not accept credenticals as input for the create method. I work with C#. I need the library for OCR purposes.
If by "explicit" you mean loading your credentials file in code, here is how I did it in Scala (vision v1.20.0):
val visionClient = {
val credStream = getInputStream( "my-api-key.json" )
val credentials = GoogleCredentials.fromStream(credStream)
val imageAnnotatorSettings = ImageAnnotatorSettings.newBuilder()
.setCredentialsProvider( FixedCredentialsProvider.create( credentials ) )
.build();
ImageAnnotatorClient.create( imageAnnotatorSettings )
}
You should be able to do something similar in C#.

How to modify HAPI validation rules for phone numbers?

The following dependencies are being used from the maven central repository in this example:
<!-- provides HAPI library -->
<dependency>
<groupId>ca.uhn.hapi</groupId>
<artifactId>hapi-base</artifactId>
<version>2.2</version>
</dependency>
<!-- provides HAPI library message version -->
<dependency>
<groupId>ca.uhn.hapi</groupId>
<artifactId>hapi-structures-v22</artifactId>
<version>2.2</version>
</dependency>
<!-- provides ByteString -->
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.10</artifactId>
<version>2.3.3</version>
</dependency>
Here is an example of my parsing code, written in scala:
import akka.util.ByteString
import ca.uhn.hl7v2.model.Message
import ca.uhn.hl7v2.model.v22.datatype.{CM_PAT_ID, ST, TN, TSComponentOne}
import ca.uhn.hl7v2.model.v22.segment.{EVN, MRG, PID}
import ca.uhn.hl7v2.parser.CanonicalModelClassFactory
import ca.uhn.hl7v2.{DefaultHapiContext, ErrorCode, HL7Exception}
lazy val parser = {
val context = new DefaultHapiContext()
context.setModelClassFactory(new CanonicalModelClassFactory("2.2"))
context.getGenericParser
}
def parseHL7Message(message: ByteString) = Try[Message] {
val msg: String = message.utf8String.trim
parser.parse(msg)
}
This code can successfully parse the following HL7 message.
"MSH|^~\\&|XXXX|S|XXXXXX|S|201410280931||ADT^A31|123456|P|2.2\r" +
"EVN|A31|201410280930\r" +
"PID|||9999999^^^S^MR~88888888^^^^PI||xxxx^xxxxxxxxx||11111111||||||(123)456-7890\r" +
"PV1\r"
However, when a phone number with an extension is supplied in the message, the hapi parser fails to parse the message. Here is an example of the input message I am trying to parse with an extension in the phone number:
"MSH|^~\\&|XXXX|S|XXXXXX|S|201410280931||ADT^A31|123456|P|2.2\r" +
"EVN|A31|201410280930\r" +
"PID|||9999999^^^S^MR~88888888^^^^PI||xxxx^xxxxxxxxx||11111111||||||(123)456-7890 1\r" +
"PV1\r"
Trying to parse this message fails with the following error message:
ca.uhn.hl7v2.validation.ValidationException: Validation failed:
Primitive value '(123)456-7890 1' requires to be empty or a US phone
number at PID-13
I read everything I could find at http://hl7api.sourceforge.net/index.html to look for documentation on how to modify the validation rules but have not found anything useful.
An example would be most appreciated, but even pointing to the proper documentation, or a simple working example project will be sufficient.
How can the validation rules used by the HAPI parser be configured to allow a phone number extension to be included in a valid US phone number in the PID-13 field?
EDIT
With a little more searching, through this hapi developer mailing list thread, I figured out how to disable validation altogether. Here is an example:
lazy val parser = {
val context = new DefaultHapiContext()
context.setModelClassFactory(new CanonicalModelClassFactory("2.2"))
context.setValidationContext(new NoValidation)
context.getGenericParser
}
But if possible, I would like to continue validating the messages. If I have to disable validation I guess that will have to work, but I'd prefer to specify that validation remain turned on, but that phone numbers can include extensions.
I must work with 3rd party service, and this service send to me invalid phones. Unfortunatly, I can't understand, how to do it as 'best practice'. But I found one hack:
#PostConstruct
public void postConstruct() {
List<RuleBinding<PrimitiveTypeRule>> rules = ((ValidationContextImpl)applicationRouter.getParser().getHapiContext().getValidationContext()).getPrimitiveRuleBindings();
//initially was published with this line, but think it was mistake
//for(int i = rules.size() - 1; i > 0; i--) {
for(int i = rules.size() - 1; i >= 0; i--) {
RuleBinding<PrimitiveTypeRule> item = rules.get(i);
if("TN".equals(item.getScope())){
rules.remove(i);
}
}
}
If somebody will know more good way to resolve it, please write.
Phone numbers can include extensions. The problem is that you have the extension in the wrong format. See the HL7 Messaging Standard Version 2.2, section 2.8.10.9. Telephone numbers must be in the following format.
[NN] [(999)]999-9999[X99999][B99999][C any text]
Put the extension after the 'X'.

Server .codec(Http()) not working as specified in example code

I am attempting to try out Finagle for the first time. I am new to Scala, so this question may seem easy to many of you.
I pulled 6.10.1-SNAPSHOT from GitHub, and attempted to implement the Robust Server example shown in the docs. The imports were not entirely clear to me, and I got all of them working except one. Note in the code below that there is one import that has an error along with one call to Http() which also has an error.
import com.twitter.finagle.http.Http
def main(args: Array[String]) {
val handleExceptions = new HandleExceptions
val authorize = new Authorize
val respond = new Respond
val myService: Service[HttpRequest, HttpResponse]
= handleExceptions andThen authorize andThen respond
val server: Server = ServerBuilder()
.name("myService")
.codec(Http()) // Error on this call to Http()
.bindTo(new InetSocketAddress(8080))
.build(myService)
}
The guide that you're following (I'm assuming this one) is quite outdated. The new docs here http://twitter.github.io/scala_school/finagle.html should be better (although the examples still aren't great)
It looks like they moved the HTTP codec to com.twitter.finagle.Http
The example code is not up-to-date with 6.10.1-SNAPSHOT. The import issue can be resolved by referencing libraryDependencies in build.sbt which correspond to the version of Finagle which was used to build the example:
libraryDependencies ++= Seq(
"com.twitter" % "finagle-core" % "6.6.2",
"com.twitter" % "finagle-http" % "6.6.2",
"com.twitter" % "util-core" % "6.5.0")

Resources