Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Need help in a java script

  1. #1
    Junior Member
    Join Date
    Mar 2022
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help in a java script

    I am a beginner in java scripting . Requirement is to create a ticket in dynamics 365.The data is available in a relational table and i am initially writing a java code where i can manually pass the values in the json input and create a ticket.
    After i pass the api and the client id ,client secret and tenant id it would generate a token and based on input of the body will create a ticket (not sure if my code is working on this functionality).
    import com.microsoft.aad.adal4j.AuthenticationContext;
    import com.microsoft.aad.adal4j.AuthenticationResult;
    import com.microsoft.aad.adal4j.ClientCredential;
    import okhttp3.*;
    import okhttp3.Response;
    import okhttp3.Call;
     
     
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.lang.String;
    import java.util.concurrent.Future;
     
     
     
    public class javacodedynamics365 {
        public static void main(String[] args) {
     
            String authority = "https://login.microsoftonline.com/";
            String resource = "https://lenovo-nitro-uat.crm.dynamics.com";
            String clientId = "";
            String clientSecret = "";
            String tenantID = "";
            ExecutorService service = Executors.newFixedThreadPool(1);
            AuthenticationResult result;
     
            try {
                AuthenticationContext context = new AuthenticationContext(authority + tenantID, true, service);
                Future<AuthenticationResult> future = context.acquireToken(resource, new ClientCredential(clientId, clientSecret), null);
     
                result = future.get();
                String accessToken = result.getAccessToken();
                System.out.println(accessToken);
     
                createWithDataReturned(accessToken);
            }
            catch (MalformedURLException e) { }
            catch (InterruptedException e) { }
            catch (ExecutionException e) { }
        }
     
        // TODO: 5
        // Retrieving customized responses on POST method:
        public static void createWithDataReturned(String accessToken) {
            try {
                OkHttpClient client = new OkHttpClient();
     
     
                MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
                System.out.println(mediaType);
                RequestBody body = RequestBody.create(mediaType, "{" +
                       "\"Account_Alias_Request\": \"Knot Technology Solutions LLC\"" +
                        "\"Partner_MDM_ID\": \"PA000000900211\"" +
                        "}");
                Request request = new Request.Builder()
                        .url("https://lenovo-nitro-uat.crm.dynamics.com/api/data/v9.1/lvo_DSRAccountReview")
                        .post(body)
                        .addHeader("OData-MaxVersion", "4.0")
                        .addHeader("OData-Version", "4.0")
                        .addHeader("Accept", "application/json")
                        .addHeader("Content-Type", "application/json; charset=utf-8")
                        .addHeader("Prefer", "odata.include-annotations=\"*\"")
                        .addHeader("Authorization", "Bearer " + accessToken)
                        .addHeader("cache-control", "no-cache")
                       // .addHeader("Postman-Token", "a3ca1261-85fe-4b57-84e0-034e0d582d46")
                        .build();
       		 System.out.println(request);
    Response response = client.newCall(request).execute();
    String dataReturnedFromCreate = response.body().string();
    System.out.println(dataReturnedFromCreate);
     
                System.out.println();
           }
           catch (Exception e) { }
       }
    }

    the above code is returning the token. But gives the error on
    Request{method=POST, url=https://lenovo-nitro-uat.crm.dynamics.com/api/data/v9.1/lvo_DSRAccountReview, tags={}}
    {"error":{"code":"0x0","message":"An error occurred while validating input parameters: System.ArgumentException: Stream was not readable.\r\n at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)\r\n at System.IO.StreamReader..ctor(Stream stream, Encoding encoding)\r\n at Microsoft.OData.JsonLight.ODataJsonLightInputConte xt.CreateTextReader(Stream messageStream, Encoding encoding)\r\n at Microsoft.OData.JsonLight.ODataJsonLightInputConte xt..ctor(ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings)\r\n at Microsoft.OData.Json.ODataJsonFormat.CreateInputCo ntext(ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings)\r\n at Microsoft.OData.ODataMessageReader.ReadFromInput[T](Func`2 readFunc, ODataPayloadKind[] payloadKinds)\r\n at Microsoft.Crm.Extensibility.ODataV4.CrmODataAction PayloadDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter .ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)"}}

    updated the below details in pom.xml file:
    <dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>adal4j</artifactId>
    <version>1.6.3</version>
    </dependency>
    <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.14.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
    </dependency>

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Need help in a java script

    Do you have any java coding questions?
    This problem appears to be with using some framework. Is there a forum for questions on how to use it?

    One problem I see in the code is the empty catch blocks. You should always call the printStackTrace method to show details on any exception.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 2
    Last Post: July 9th, 2018, 07:02 AM
  2. Replies: 1
    Last Post: September 21st, 2014, 04:15 AM
  3. codecademy Java Script
    By TyffaN in forum Other Programming Languages
    Replies: 1
    Last Post: September 2nd, 2014, 08:47 AM
  4. Java Script or HTML
    By ravi9999 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 1st, 2012, 09:44 AM
  5. java script/PHP/Jquery Help
    By lovelyxalice in forum Other Programming Languages
    Replies: 4
    Last Post: March 25th, 2012, 10:59 AM