Search in sources :

Example 61 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class SMSJAXRPCObjectImpl method registerNotificationURL.

// Methods to register notification URLs
public String registerNotificationURL(String url) throws RemoteException {
    initialize();
    // Default value if there are any issues with the registration process.
    String id = "0";
    try {
        // Check URL is not the local server
        if (!url.toLowerCase().startsWith(serverURL)) {
            synchronized (notificationURLs) {
                URL notificationUrl = new URL(url);
                // Don't add the URL again if we already have it registered
                boolean alreadyRegistered = false;
                for (Map.Entry<String, URL> entry : notificationURLs.entrySet()) {
                    if (notificationUrl.equals(entry.getValue())) {
                        // This allows us to return the existing entry ID to support clients being able to
                        // de-register the correct entry.
                        id = entry.getKey();
                        alreadyRegistered = true;
                        if (debug.messageEnabled()) {
                            debug.message("SMSJAXRPCObjectImpl:registerNotificationURL() - URL " + url + " already registered, returning existing ID " + id);
                        }
                        break;
                    }
                }
                // If we didn't find the url in our list, add it
                if (!alreadyRegistered) {
                    String serverID = "";
                    try {
                        serverID = WebtopNaming.getAMServerID();
                    } catch (ServerEntryNotFoundException e) {
                        if (debug.messageEnabled()) {
                            debug.message("SMSJAXRPCObjectImpl:registerNotificationURL - " + "had a problem getting our serverID ", e);
                        }
                    }
                    // Generate a unique value that includes the serverID to have a better chance of being unique
                    // in a cluster should a de-register request end up on the wrong server.
                    id = SMSUtils.getUniqueID() + "_" + serverID;
                    notificationURLs.put(id, notificationUrl);
                    if (debug.messageEnabled()) {
                        debug.message("SMSJAXRPCObjectImpl:registerNotificationURL - " + "registered notification URL: " + url + " with ID " + id);
                    }
                }
            }
        } else {
            // Cannot add this server for notifications
            if (debug.warningEnabled()) {
                debug.warning("SMSJAXRPCObjectImpl:registerNotificationURL " + "cannot add local server: " + url);
            }
        }
    } catch (MalformedURLException e) {
        if (debug.warningEnabled()) {
            debug.warning("SMSJAXRPCObjectImpl:registerNotificationURL " + " invalid URL: " + url, e);
        }
    }
    return id;
}
Also used : MalformedURLException(java.net.MalformedURLException) ServerEntryNotFoundException(com.iplanet.services.naming.ServerEntryNotFoundException) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) Map(java.util.Map) URL(java.net.URL)

Example 62 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class OpenSSOEntitlementListener method removeListener.

public boolean removeListener(Subject adminSubject, String url) throws EntitlementException {
    if (url == null) {
        throw new EntitlementException(436);
    }
    try {
        URL urlObj = new URL(url);
        boolean removed = false;
        List<EntitlementListener> listeners = getListeners();
        for (int i = listeners.size() - 1; i >= 0; --i) {
            EntitlementListener l = listeners.get(i);
            if (l.getUrl().equals(urlObj)) {
                listeners.remove(l);
                removed = true;
                break;
            }
        }
        storeListeners(listeners);
        return removed;
    } catch (MalformedURLException e) {
        throw new EntitlementException(435);
    }
}
Also used : EntitlementException(com.sun.identity.entitlement.EntitlementException) MalformedURLException(java.net.MalformedURLException) EntitlementListener(com.sun.identity.entitlement.EntitlementListener) URL(java.net.URL)

Example 63 with MalformedURLException

use of java.net.MalformedURLException in project Xponents by OpenSextant.

the class XlayerClientTest method main.

public static void main(String[] args) {
    URL url;
    try {
        url = new URL(args[0]);
        /*
             * Create client.
             */
        XlayerClient c = new XlayerClient(url);
        try {
            /* 
                 * Prepare request.  Text must be UTF-8 encoded.
                 * Note -- readFile() here assumes the file is unicode content
                 * 
                 */
            String text = FileUtility.readFile(args[1]);
            String docid = args[1];
            /*
                 * Process the text and print results to console.
                 * Result is an array of TextMatch objects.  For each particular
                 * TextMatch (Xponents Basic API), you have some common fields related to the 
                 * text found, and then class-specific fields and objects you need to evaluate yourself.
                 * 
                 * The XlayerClient process() method makes use of Transforms helper class to 
                 * digest JSON annotations into Java API TextMatch objects of various flavors.
                 */
            List<TextMatch> results = c.process(docid, text);
            for (TextMatch m : results) {
                System.out.println(String.format("Found %s %s @ (%d:%d)", m.getType(), m.getText(), m.start, m.end));
            }
        } catch (Exception parseErr) {
            parseErr.printStackTrace();
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ConfigException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) XlayerClient(org.opensextant.xlayer.XlayerClient) ConfigException(org.opensextant.ConfigException) TextMatch(org.opensextant.extraction.TextMatch) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) ConfigException(org.opensextant.ConfigException)

Example 64 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class OpenAMOpenIdConnectClientRegistrationService method createRegistration.

/**
     * {@inheritDoc}
     */
public JsonValue createRegistration(String accessToken, String deploymentUrl, OAuth2Request request) throws InvalidRedirectUri, InvalidClientMetadata, ServerException, UnsupportedResponseTypeException, AccessDeniedException, NotFoundException, InvalidPostLogoutRedirectUri {
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    if (!providerSettings.isOpenDynamicClientRegistrationAllowed()) {
        if (!tokenVerifier.verify(request).isValid()) {
            throw new AccessDeniedException("Access Token not valid");
        }
    }
    final JsonValue input = request.getBody();
    //check input to ensure it is valid
    Set<String> inputKeys = input.keys();
    for (String key : inputKeys) {
        OAuth2Constants.ShortClientAttributeNames keyName = fromString(key);
        if (keyName == null) {
            logger.warn("Unknown input given. Key: " + key);
        }
    }
    //create client given input
    ClientBuilder clientBuilder = new ClientBuilder();
    try {
        boolean jwks = false;
        if (input.get(JWKS.getType()).asString() != null) {
            jwks = true;
            try {
                JsonValueBuilder.toJsonValue(input.get(JWKS.getType()).asString());
            } catch (JsonException e) {
                throw new InvalidClientMetadata("jwks must be valid JSON.");
            }
            clientBuilder.setJwks(input.get(JWKS.getType()).asString());
            clientBuilder.setPublicKeySelector(Client.PublicKeySelector.JWKS.getType());
        }
        if (input.get(JWKS_URI.getType()).asString() != null) {
            if (jwks) {
                //allowed to set either jwks or jwks_uri but not both
                throw new InvalidClientMetadata("Must define either jwks or jwks_uri, not both.");
            }
            jwks = true;
            try {
                new URL(input.get(JWKS_URI.getType()).asString());
            } catch (MalformedURLException e) {
                throw new InvalidClientMetadata("jwks_uri must be a valid URL.");
            }
            clientBuilder.setJwksUri(input.get(JWKS_URI.getType()).asString());
            clientBuilder.setPublicKeySelector(Client.PublicKeySelector.JWKS_URI.getType());
        }
        //not spec-defined, this is OpenAM proprietary
        if (input.get(X509.getType()).asString() != null) {
            clientBuilder.setX509(input.get(X509.getType()).asString());
        }
        //drop to this if neither other are set
        if (!jwks) {
            clientBuilder.setPublicKeySelector(Client.PublicKeySelector.X509.getType());
        }
        if (input.get(TOKEN_ENDPOINT_AUTH_METHOD.getType()).asString() != null) {
            if (Client.TokenEndpointAuthMethod.fromString(input.get(TOKEN_ENDPOINT_AUTH_METHOD.getType()).asString()) == null) {
                logger.error("Invalid token_endpoint_auth_method requested.");
                throw new InvalidClientMetadata("Invalid token_endpoint_auth_method requested.");
            }
            clientBuilder.setTokenEndpointAuthMethod(input.get(TOKEN_ENDPOINT_AUTH_METHOD.getType()).asString());
        } else {
            clientBuilder.setTokenEndpointAuthMethod(Client.TokenEndpointAuthMethod.CLIENT_SECRET_BASIC.getType());
        }
        if (input.get(CLIENT_ID.getType()).asString() != null) {
            clientBuilder.setClientID(input.get(CLIENT_ID.getType()).asString());
        } else {
            clientBuilder.setClientID(UUID.randomUUID().toString());
        }
        if (input.get(CLIENT_SECRET.getType()).asString() != null) {
            clientBuilder.setClientSecret(input.get(CLIENT_SECRET.getType()).asString());
        } else {
            clientBuilder.setClientSecret(UUID.randomUUID().toString());
        }
        if (input.get(CLIENT_TYPE.getType()).asString() != null) {
            if (Client.ClientType.fromString(input.get(CLIENT_TYPE.getType()).asString()) != null) {
                clientBuilder.setClientType(input.get(CLIENT_TYPE.getType()).asString());
            } else {
                logger.error("Invalid client_type requested.");
                throw new InvalidClientMetadata("Invalid client_type requested");
            }
        } else {
            clientBuilder.setClientType(Client.ClientType.CONFIDENTIAL.getType());
        }
        if (input.get(DEFAULT_MAX_AGE.getType()).asLong() != null) {
            clientBuilder.setDefaultMaxAge(input.get(DEFAULT_MAX_AGE.getType()).asLong());
            clientBuilder.setDefaultMaxAgeEnabled(true);
        } else {
            clientBuilder.setDefaultMaxAge(Client.MIN_DEFAULT_MAX_AGE);
            clientBuilder.setDefaultMaxAgeEnabled(false);
        }
        List<String> redirectUris = new ArrayList<String>();
        if (input.get(REDIRECT_URIS.getType()).asList() != null) {
            redirectUris = input.get(REDIRECT_URIS.getType()).asList(String.class);
            boolean isValidUris = true;
            for (String redirectUri : redirectUris) {
                try {
                    urlValidator.validate(redirectUri);
                } catch (ValidationException e) {
                    isValidUris = false;
                    logger.error("The redirectUri: " + redirectUri + " is invalid.");
                }
            }
            if (!isValidUris) {
                throw new InvalidRedirectUri();
            }
            clientBuilder.setRedirectionURIs(redirectUris);
        }
        if (input.get(SECTOR_IDENTIFIER_URI.getType()).asString() != null) {
            try {
                URL sectorIdentifier = new URL(input.get(SECTOR_IDENTIFIER_URI.getType()).asString());
                List<String> response = mapper.readValue(sectorIdentifier, List.class);
                if (!response.containsAll(redirectUris)) {
                    logger.error("Request_uris not included in sector_identifier_uri.");
                    throw new InvalidClientMetadata();
                }
            } catch (Exception e) {
                logger.error("Invalid sector_identifier_uri requested.");
                throw new InvalidClientMetadata("Invalid sector_identifier_uri requested.");
            }
            clientBuilder.setSectorIdentifierUri(input.get(SECTOR_IDENTIFIER_URI.getType()).asString());
        }
        List<String> scopes = input.get(SCOPES.getType()).asList(String.class);
        if (scopes != null && !scopes.isEmpty()) {
            if (!containsAllCaseInsensitive(providerSettings.getSupportedScopes(), scopes)) {
                logger.error("Invalid scopes requested.");
                throw new InvalidClientMetadata("Invalid scopes requested");
            }
        } else {
            //if nothing requested, fall back to provider defaults
            scopes = new ArrayList<String>();
            scopes.addAll(providerSettings.getDefaultScopes());
        }
        //regardless, we add openid
        if (!scopes.contains(OPENID)) {
            scopes = new ArrayList<String>(scopes);
            scopes.add(OPENID);
        }
        clientBuilder.setAllowedGrantScopes(scopes);
        List<String> defaultScopes = input.get(DEFAULT_SCOPES.getType()).asList(String.class);
        if (defaultScopes != null) {
            if (containsAllCaseInsensitive(providerSettings.getSupportedScopes(), defaultScopes)) {
                clientBuilder.setDefaultGrantScopes(defaultScopes);
            } else {
                throw new InvalidClientMetadata("Invalid default scopes requested.");
            }
        }
        List<String> clientNames = new ArrayList<String>();
        Set<String> keys = input.keys();
        for (String key : keys) {
            if (key.equals(CLIENT_NAME.getType())) {
                clientNames.add(input.get(key).asString());
            } else if (key.startsWith(CLIENT_NAME.getType())) {
                try {
                    Locale locale = new Locale(key.substring(CLIENT_NAME.getType().length() + 1));
                    clientNames.add(locale.toString() + "|" + input.get(key).asString());
                } catch (Exception e) {
                    logger.error("Invalid locale for client_name.");
                    throw new InvalidClientMetadata("Invalid locale for client_name.");
                }
            }
        }
        if (clientNames != null) {
            clientBuilder.setClientName(clientNames);
        }
        if (input.get(CLIENT_DESCRIPTION.getType()).asList() != null) {
            clientBuilder.setDisplayDescription(input.get(CLIENT_DESCRIPTION.getType()).asList(String.class));
        }
        if (input.get(SUBJECT_TYPE.getType()).asString() != null) {
            if (providerSettings.getSupportedSubjectTypes().contains(input.get(SUBJECT_TYPE.getType()).asString())) {
                clientBuilder.setSubjectType(input.get(SUBJECT_TYPE.getType()).asString());
            } else {
                logger.error("Invalid subject_type requested.");
                throw new InvalidClientMetadata("Invalid subject_type requested");
            }
        } else {
            clientBuilder.setSubjectType(Client.SubjectType.PUBLIC.getType());
        }
        if (input.get(ID_TOKEN_SIGNED_RESPONSE_ALG.getType()).asString() != null) {
            if (containsCaseInsensitive(providerSettings.getSupportedIDTokenSigningAlgorithms(), input.get(ID_TOKEN_SIGNED_RESPONSE_ALG.getType()).asString())) {
                clientBuilder.setIdTokenSignedResponseAlgorithm(input.get(ID_TOKEN_SIGNED_RESPONSE_ALG.getType()).asString());
            } else {
                logger.error("Unsupported id_token_response_signed_alg requested.");
                throw new InvalidClientMetadata("Unsupported id_token_response_signed_alg requested.");
            }
        } else {
            clientBuilder.setIdTokenSignedResponseAlgorithm(ID_TOKEN_SIGNED_RESPONSE_ALG_DEFAULT);
        }
        if (input.get(POST_LOGOUT_REDIRECT_URIS.getType()).asList() != null) {
            List<String> logoutRedirectUris = input.get(POST_LOGOUT_REDIRECT_URIS.getType()).asList(String.class);
            boolean isValidUris = true;
            for (String logoutRedirectUri : logoutRedirectUris) {
                try {
                    urlValidator.validate(logoutRedirectUri);
                } catch (ValidationException e) {
                    isValidUris = false;
                    logger.error("The post_logout_redirect_uris: {} is invalid.", logoutRedirectUri);
                }
            }
            if (!isValidUris) {
                throw new InvalidPostLogoutRedirectUri();
            }
            clientBuilder.setPostLogoutRedirectionURIs(logoutRedirectUris);
        }
        if (input.get(REGISTRATION_ACCESS_TOKEN.getType()).asString() != null) {
            clientBuilder.setAccessToken(input.get(REGISTRATION_ACCESS_TOKEN.getType()).asString());
        } else {
            clientBuilder.setAccessToken(accessToken);
        }
        if (input.get(CLIENT_SESSION_URI.getType()).asString() != null) {
            clientBuilder.setClientSessionURI(input.get(CLIENT_SESSION_URI.getType()).asString());
        }
        if (input.get(APPLICATION_TYPE.getType()).asString() != null) {
            if (Client.ApplicationType.fromString(input.get(APPLICATION_TYPE.getType()).asString()) != null) {
                clientBuilder.setApplicationType(Client.ApplicationType.WEB.getType());
            } else {
                logger.error("Invalid application_type requested.");
                throw new InvalidClientMetadata("Invalid application_type requested.");
            }
        } else {
            clientBuilder.setApplicationType(DEFAULT_APPLICATION_TYPE);
        }
        if (input.get(DISPLAY_NAME.getType()).asList() != null) {
            clientBuilder.setDisplayName(input.get(DISPLAY_NAME.getType()).asList(String.class));
        }
        if (input.get(RESPONSE_TYPES.getType()).asList() != null) {
            final List<String> clientResponseTypeList = input.get(RESPONSE_TYPES.getType()).asList(String.class);
            final List<String> typeList = new ArrayList<String>();
            for (String responseType : clientResponseTypeList) {
                typeList.addAll(Arrays.asList(responseType.split(" ")));
            }
            if (containsAllCaseInsensitive(providerSettings.getAllowedResponseTypes().keySet(), typeList)) {
                clientBuilder.setResponseTypes(clientResponseTypeList);
            } else {
                logger.error("Invalid response_types requested.");
                throw new InvalidClientMetadata("Invalid response_types requested.");
            }
        } else {
            List<String> defaultResponseTypes = new ArrayList<String>();
            defaultResponseTypes.add("code");
            clientBuilder.setResponseTypes(defaultResponseTypes);
        }
        if (input.get(AUTHORIZATION_CODE_LIFE_TIME.getType()).asLong() != null) {
            clientBuilder.setAuthorizationCodeLifeTime(input.get(AUTHORIZATION_CODE_LIFE_TIME.getType()).asLong());
        } else {
            clientBuilder.setAuthorizationCodeLifeTime(0L);
        }
        if (input.get(ACCESS_TOKEN_LIFE_TIME.getType()).asLong() != null) {
            clientBuilder.setAccessTokenLifeTime(input.get(ACCESS_TOKEN_LIFE_TIME.getType()).asLong());
        } else {
            clientBuilder.setAccessTokenLifeTime(0L);
        }
        if (input.get(REFRESH_TOKEN_LIFE_TIME.getType()).asLong() != null) {
            clientBuilder.setRefreshTokenLifeTime(input.get(REFRESH_TOKEN_LIFE_TIME.getType()).asLong());
        } else {
            clientBuilder.setRefreshTokenLifeTime(0L);
        }
        if (input.get(JWT_TOKEN_LIFE_TIME.getType()).asLong() != null) {
            clientBuilder.setJwtTokenLifeTime(input.get(JWT_TOKEN_LIFE_TIME.getType()).asLong());
        } else {
            clientBuilder.setJwtTokenLifeTime(0L);
        }
        if (input.get(CONTACTS.getType()).asList() != null) {
            clientBuilder.setContacts(input.get(CONTACTS.getType()).asList(String.class));
        }
    } catch (JsonValueException e) {
        logger.error("Unable to build client.", e);
        throw new InvalidClientMetadata();
    }
    Client client = clientBuilder.createClient();
    // See OPENAM-3604 and http://openid.net/specs/openid-connect-registration-1_0.html#ClientRegistration
    if (providerSettings.isRegistrationAccessTokenGenerationEnabled() && !client.hasAccessToken()) {
        client.setAccessToken(createRegistrationAccessToken(client, request));
    }
    clientDAO.create(client, request);
    // have some visibility on who is registering clients.
    if (logger.isInfoEnabled()) {
        logger.info("Registered OpenID Connect client: " + client.getClientID() + ", name=" + client.getClientName() + ", type=" + client.getClientType());
    }
    Map<String, Object> response = client.asMap();
    response = convertClientReadResponseFormat(response);
    response.put(REGISTRATION_CLIENT_URI, deploymentUrl + "/oauth2/connect/register?client_id=" + client.getClientID());
    response.put(EXPIRES_AT, 0);
    return new JsonValue(response);
}
Also used : JsonException(org.forgerock.json.JsonException) Locale(java.util.Locale) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) MalformedURLException(java.net.MalformedURLException) ValidationException(com.sun.identity.shared.validation.ValidationException) ArrayList(java.util.ArrayList) URL(java.net.URL) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) Client(org.forgerock.openidconnect.Client) InvalidRedirectUri(org.forgerock.openidconnect.exceptions.InvalidRedirectUri) JsonValueException(org.forgerock.json.JsonValueException) ClientBuilder(org.forgerock.openidconnect.ClientBuilder) ShortClientAttributeNames(org.forgerock.oauth2.core.OAuth2Constants.ShortClientAttributeNames) JsonValue(org.forgerock.json.JsonValue) ValidationException(com.sun.identity.shared.validation.ValidationException) MalformedURLException(java.net.MalformedURLException) InvalidTokenException(org.forgerock.oauth2.core.exceptions.InvalidTokenException) JsonException(org.forgerock.json.JsonException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) JsonValueException(org.forgerock.json.JsonValueException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) UnsupportedResponseTypeException(org.forgerock.oauth2.core.exceptions.UnsupportedResponseTypeException) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) InvalidPostLogoutRedirectUri(org.forgerock.openidconnect.exceptions.InvalidPostLogoutRedirectUri) OAuth2Constants(org.forgerock.oauth2.core.OAuth2Constants) InvalidClientMetadata(org.forgerock.openidconnect.exceptions.InvalidClientMetadata)

Example 65 with MalformedURLException

use of java.net.MalformedURLException in project Rashr by DsLNeXuS.

the class RecoverySystemFragment method onCreateView.

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mActivity = (RashrActivity) getActivity();
    final ScrollView root = (ScrollView) inflater.inflate(R.layout.fragment_recovery_system, container, false);
    mContext = root.getContext();
    final AppCompatTextView tvTitle = (AppCompatTextView) root.findViewById(R.id.tvSysName);
    tvTitle.setText(mTitle.toUpperCase());
    final AppCompatTextView tvDesc = (AppCompatTextView) root.findViewById(R.id.tvRecSysDesc);
    tvDesc.setText(mDesc);
    final AppCompatSpinner spVersions = (AppCompatSpinner) root.findViewById(R.id.spVersions);
    ArrayList<String> formatedVersions = new ArrayList<>();
    for (String versionLinks : mVersions) {
        formatedVersions.add(formatName(versionLinks, mTitle));
    }
    final ArrayAdapter<String> adapter = new ArrayAdapter<>(root.getContext(), android.R.layout.simple_list_item_1, formatedVersions);
    spVersions.setAdapter(adapter);
    spVersions.setSelection(0);
    final AppCompatTextView tvDev = (AppCompatTextView) root.findViewById(R.id.tvDevName);
    tvDev.setText(mDev);
    final AppCompatImageView imLogo = (AppCompatImageView) root.findViewById(R.id.ivRecLogo);
    if (mLogo == 0) {
        root.removeView(imLogo);
    } else {
        imLogo.setImageResource(mLogo);
    }
    final AppCompatButton bFlash = (AppCompatButton) root.findViewById(R.id.bFlashRecovery);
    bFlash.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            flashSupportedRecovery(mTitle, mVersions.get(spVersions.getSelectedItemPosition()));
        }
    });
    final LinearLayout ScreenshotLayout = (LinearLayout) root.findViewById(R.id.ScreenshotLayout);
    if (mScreenshotURL == null) {
        ((ViewGroup) ScreenshotLayout.getParent()).removeView(ScreenshotLayout);
    } else {
        try {
            Downloader jsonDownloader = new Downloader(new URL(mScreenshotURL + "/getScreenshots.php"), new File(mContext.getExternalCacheDir(), "screenhots.json"));
            jsonDownloader.setOverrideFile(true);
            jsonDownloader.setOnDownloadListener(new Downloader.OnDownloadListener() {

                @Override
                public void onSuccess(File file) {
                    try {
                        JSONArray arr = new JSONArray(Common.fileContent(file));
                        for (int i = 0; i < arr.length(); i++) {
                            final String name = arr.get(i).toString();
                            if (name.equals(".") || name.equals("..") || name.equals("getScreenshots.php"))
                                continue;
                            Downloader imageDownloader = new Downloader(new URL(mScreenshotURL + "/" + name), new File(file.getParentFile(), name));
                            //Do not redownload predownloaded images
                            imageDownloader.setOverrideFile(false);
                            imageDownloader.setOnDownloadListener(new Downloader.OnDownloadListener() {

                                @Override
                                public void onSuccess(File file) {
                                    AppCompatImageView iv = (AppCompatImageView) inflater.inflate(R.layout.recovery_screenshot, null);
                                    try {
                                        final BitmapFactory.Options options = new BitmapFactory.Options();
                                        options.inSampleSize = 8;
                                        Bitmap screenshot = BitmapFactory.decodeFile(file.toString());
                                        iv.setImageBitmap(screenshot);
                                        ScreenshotLayout.addView(iv);
                                    } catch (OutOfMemoryError e) {
                                        App.ERRORS.add("Screenshot " + file.toString() + " could not be decoded " + e.toString());
                                    }
                                }

                                @Override
                                public void onFail(Exception e) {
                                }
                            });
                            imageDownloader.download();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        onFail(e);
                    }
                }

                @Override
                public void onFail(Exception e) {
                    e.printStackTrace();
                }
            });
            jsonDownloader.download();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    return root;
}
Also used : MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) Downloader(de.mkrtchyan.utils.Downloader) URL(java.net.URL) Bitmap(android.graphics.Bitmap) BitmapFactory(android.graphics.BitmapFactory) ViewGroup(android.view.ViewGroup) AppCompatTextView(android.support.v7.widget.AppCompatTextView) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) AppCompatImageView(android.support.v7.widget.AppCompatImageView) View(android.view.View) AppCompatImageView(android.support.v7.widget.AppCompatImageView) AppCompatTextView(android.support.v7.widget.AppCompatTextView) ScrollView(android.widget.ScrollView) AppCompatSpinner(android.support.v7.widget.AppCompatSpinner) JSONException(org.json.JSONException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) AppCompatButton(android.support.v7.widget.AppCompatButton) ScrollView(android.widget.ScrollView) File(java.io.File) ArrayAdapter(android.widget.ArrayAdapter) LinearLayout(android.widget.LinearLayout)

Aggregations

MalformedURLException (java.net.MalformedURLException)3838 URL (java.net.URL)2885 IOException (java.io.IOException)1194 File (java.io.File)910 ArrayList (java.util.ArrayList)372 InputStream (java.io.InputStream)367 HttpURLConnection (java.net.HttpURLConnection)295 URISyntaxException (java.net.URISyntaxException)270 URI (java.net.URI)239 InputStreamReader (java.io.InputStreamReader)226 BufferedReader (java.io.BufferedReader)208 HashMap (java.util.HashMap)200 URLClassLoader (java.net.URLClassLoader)168 Map (java.util.Map)166 URLConnection (java.net.URLConnection)148 FileNotFoundException (java.io.FileNotFoundException)137 Matcher (java.util.regex.Matcher)132 Test (org.junit.Test)129 UnsupportedEncodingException (java.io.UnsupportedEncodingException)119 Pattern (java.util.regex.Pattern)113