0

I am trying to update user metadata by using HttpURLConnection PATCH API. I had googled and found this useful link which I used.

[https://stackoverflow.com/questions/25163131/httpurlconnection-invalid-http-method-patch][1]

Following are my steps to update user metadata.

  1. Calling database to get user information which need to be updated, suppose database return 1000 users .

  2. Calling GET xxx/users/{userId} API 1000 times to check whether database user exists or not,

    Suppose GET xxx/users/{userId} API return 800 active users which needs to be updated afterwards

  3. Calling PATCH xxx/users/{userId} API 800 times to update user metadata.

My code working fine if record size is less than or equal to 200-250 but If size gets increase say 1000 then application throwing exception saying

Exception is java.net.ProtocolException: Invalid HTTP method: PATCH

Here is my code.

public static void main(String[] args) throws FileNotFoundException, IOException {

// Here calling DB to get user metadata
List<CEUser> ca = getUserMetada(prop);

// Calling GET users/{userId} API to check whether user exists or not
List<CEUser> activeUsers = getActiveUsers(ca, prop);

// Calling PATCH users/{userId} API to update user metadata
updateUsername(activeUsers, prop);    
}


public List<CEUser> getActiveUsers(List<CEUser> CEUsers, Properties prop) {
    try {
        List<CEUser> activeCEUsers = new ArrayList<>();
        for (CEUser ca : CEUsers) {
            URL url = new URL(prop.getCeBaseURL() + "users/" + ca.getUserId());
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Accept", "application/json");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == 200)
                activeCEUsers.add(ca);
            
            httpConnection.disconnect();

        }
        return activeCEUsers;
    } catch (Exception e) {
        System.out.println("Exception occurred in getActiveUsers() method ");
    }
}



private static void allowMethods(String... methods) {
    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        methodsField.setAccessible(true);

        String[] oldMethods = (String[]) methodsField.get(null);
        Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
        methodsSet.addAll(Arrays.asList(methods));
        String[] newMethods = methodsSet.toArray(new String[0]);

        methodsField.set(null/*static field*/, newMethods);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}


public List<CEUser> updateUsername(List<CEUser> ceUsers, Properties prop) {
    try {           
        allowMethods("PATCH");
        
        List<CEUser> updatedUsername = new ArrayList<>();

        for (CEUser ca : ceUsers) {
            
            // Construct username
            String username = "some static email";
            
            // Construct email into json format to set in body part 
            String json = constructJson("email", username);
    
            URL url = new URL(prop.getCeBaseURL() + "users/" + ca.getUserId());
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("PATCH");
            httpConnection.setDoOutput(true);
            httpConnection.setRequestProperty("Accept-Charset", "UTF-8");
            httpConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            try (OutputStream output = httpConnection.getOutputStream()) {
                output.write(json.getBytes("UTF-8"));
            }

            httpConnection.connect();

            if (httpConnection.getResponseCode() == 200) {
                ca.setUsername(username); // set updated username
                updatedUsername.add(ca);
            }
            httpConnection.disconnect();
        }           
        return updatedUsername;

    } catch (Exception e) {
        System.out.println("Exception occurred in updateUsername() method");
    }
}   

Any idea why same code working for 200-250 records but not for 1000 records.

Thanks

Nizamuddin
  • 149
  • 1
  • 2
  • 16
  • Can you post the exception stack trace – SKumar Aug 07 '20 at 16:15
  • @SKumar, `Exception is java.net.ProtocolException: Invalid HTTP method: PATCH` – Nizamuddin Aug 07 '20 at 16:17
  • Do not post only the error message, post the full stack trace. https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – PauMAVA Aug 07 '20 at 17:37

0 Answers0