Example usage for java.io IOException getClass

List of usage examples for java.io IOException getClass

Introduction

In this page you can find the example usage for java.io IOException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.zaproxy.zap.extension.ascanrules.TestPathTraversal.java

/**
 * scans all GET and POST parameters for Path Traversal vulnerabilities
 *
 * @param msg//from w ww  .  ja  v  a2s .c  om
 * @param param
 * @param value
 */
@Override
public void scan(HttpMessage msg, String param, String value) {

    try {
        // figure out how aggressively we should test
        int nixCount = 0;
        int winCount = 0;
        int dirCount = 0;
        int localTraversalLength = 0;

        // DEBUG only
        if (log.isDebugEnabled()) {
            log.debug("Attacking at Attack Strength: " + this.getAttackStrength());
        }

        switch (this.getAttackStrength()) {
        case LOW:
            // This works out as a total of 2+2+2+0*4+1 = 7 reqs / param
            nixCount = 2;
            winCount = 2;
            dirCount = 2;
            localTraversalLength = 0;
            break;

        case MEDIUM:
            // This works out as a total of 2+4+4+1*4+1 = 15 reqs / param
            nixCount = 2;
            winCount = 4;
            dirCount = 4;
            localTraversalLength = 1;
            break;

        case HIGH:
            // This works out as a total of 4+8+7+2*4+1 = 28 reqs / param
            nixCount = 4;
            winCount = 8;
            dirCount = 7;
            localTraversalLength = 2;
            break;

        case INSANE:
            // This works out as a total of 6+18+19+4*4+1 = 60 reqs / param
            nixCount = NIX_LOCAL_FILE_TARGETS.length;
            winCount = WIN_LOCAL_FILE_TARGETS.length;
            dirCount = LOCAL_DIR_TARGETS.length;
            localTraversalLength = 4;
            break;

        default:
            // Default to off
        }

        if (log.isDebugEnabled()) {
            log.debug("Checking [" + getBaseMsg().getRequestHeader().getMethod() + "] ["
                    + getBaseMsg().getRequestHeader().getURI() + "], parameter [" + param
                    + "] for Path Traversal to local files");
        }

        // Check 1: Start detection for Windows patterns
        // note that depending on the AttackLevel, the number of prefixes that we will try
        // changes.
        if (inScope(Tech.Windows)) {

            for (int h = 0; h < winCount; h++) {

                // Check if a there was a finding or the scan has been stopped
                // if yes dispose resources and exit
                if (sendAndCheckPayload(param, WIN_LOCAL_FILE_TARGETS[h], WIN_PATTERN) || isStop()) {
                    // Dispose all resources
                    // Exit the plugin
                    return;
                }
            }
        }

        // Check 2: Start detection for *NIX patterns
        // note that depending on the AttackLevel, the number of prefixes that we will try
        // changes.
        if (inScope(Tech.Linux) || inScope(Tech.MacOS)) {

            for (int h = 0; h < nixCount; h++) {

                // Check if a there was a finding or the scan has been stopped
                // if yes dispose resources and exit
                if (sendAndCheckPayload(param, NIX_LOCAL_FILE_TARGETS[h], NIX_PATTERN) || isStop()) {
                    // Dispose all resources
                    // Exit the plugin
                    return;
                }
            }
        }

        // Check 3: Detect if this page is a directory browsing component
        // example: https://www.buggedsite.org/log/index.php?dir=C:\
        // note that depending on the AttackLevel, the number of prefixes that we will try
        // changes.
        for (int h = 0; h < dirCount; h++) {

            // Check if a there was a finding or the scan has been stopped
            // if yes dispose resources and exit
            if (sendAndCheckPayload(param, LOCAL_DIR_TARGETS[h], DIR_PATTERN) || isStop()) {
                // Dispose all resources
                // Exit the plugin
                return;
            }
        }

        // Check 4: Start detection for internal well known files
        // try variants based on increasing ../ ..\ prefixes and the presence of the / and \
        // trailer
        // e.g. WEB-INF/web.xml, /WEB-INF/web.xml, ../WEB-INF/web.xml, /../WEB-INF/web.xml, ecc.
        // Both slashed and backslashed variants are checked
        // -------------------------------
        // Currently we've always checked only for J2EE known files
        // and this remains also for this version
        //
        // Web.config for .NET in the future?
        // -------------------------------
        String sslashPattern = "WEB-INF/web.xml";
        // The backslashed version of the same check
        String bslashPattern = sslashPattern.replace('/', '\\');

        if (inScope(Tech.Tomcat)) {

            for (int idx = 0; idx < localTraversalLength; idx++) {

                // Check if a there was a finding or the scan has been stopped
                // if yes dispose resources and exit
                if (sendAndCheckPayload(param, sslashPattern, WAR_PATTERN)
                        || sendAndCheckPayload(param, bslashPattern, WAR_PATTERN)
                        || sendAndCheckPayload(param, '/' + sslashPattern, WAR_PATTERN)
                        || sendAndCheckPayload(param, '\\' + bslashPattern, WAR_PATTERN) || isStop()) {

                    // Dispose all resources
                    // Exit the plugin
                    return;
                }

                sslashPattern = "../" + sslashPattern;
                bslashPattern = "..\\" + bslashPattern;
            }
        }

        // Check 5: try a local file Path Traversal on the file name of the URL (which obviously
        // will not be in the target list above).
        // first send a query for a random parameter value, and see if we get a 200 back
        // if 200 is returned, abort this check (on the url filename itself), because it would
        // be unreliable.
        // if we know that a random query returns <> 200, then a 200 response likely means
        // something!
        // this logic is all about avoiding false positives, while still attempting to match on
        // actual vulnerabilities
        msg = getNewMsg();
        setParameter(msg, param, NON_EXISTANT_FILENAME);

        // send the modified message (with a hopefully non-existent filename), and see what we
        // get back
        try {
            sendAndReceive(msg);

        } catch (SocketException | IllegalStateException | UnknownHostException | IllegalArgumentException
                | InvalidRedirectLocationException | URIException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                        + msg.getRequestHeader().getURI().toString());
            }

            return; // Something went wrong, no point continuing
        }

        // do some pattern matching on the results.
        Pattern errorPattern = Pattern.compile("Exception|Error");
        Matcher errorMatcher = errorPattern.matcher(msg.getResponseBody().toString());

        String urlfilename = msg.getRequestHeader().getURI().getName();

        // url file name may be empty, i.e. there is no file name for next check
        if (!StringUtils.isEmpty(urlfilename)
                && (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK || errorMatcher.find())) {

            if (log.isDebugEnabled()) {
                log.debug("It is possible to check for local file Path Traversal on the url filename on ["
                        + msg.getRequestHeader().getMethod() + "] [" + msg.getRequestHeader().getURI() + "], ["
                        + param + "]");
            }

            String prefixedUrlfilename;

            // for the url filename, try each of the prefixes in turn
            for (String prefix : LOCAL_FILE_RELATIVE_PREFIXES) {

                prefixedUrlfilename = prefix + urlfilename;
                msg = getNewMsg();
                setParameter(msg, param, prefixedUrlfilename);

                // send the modified message (with the url filename), and see what we get back
                try {
                    sendAndReceive(msg);

                } catch (SocketException | IllegalStateException | UnknownHostException
                        | IllegalArgumentException | InvalidRedirectLocationException | URIException ex) {
                    if (log.isDebugEnabled()) {
                        log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage()
                                + " when accessing: " + msg.getRequestHeader().getURI().toString());
                    }

                    continue; // Something went wrong, move to the next prefix in the loop
                }

                // did we get an Exception or an Error?
                errorMatcher = errorPattern.matcher(msg.getResponseBody().toString());
                if ((msg.getResponseHeader().getStatusCode() == HttpStatusCode.OK) && (!errorMatcher.find())) {

                    // if it returns OK, and the random string above did NOT return ok, then
                    // raise an alert
                    // since the filename has likely been picked up and used as a file name from
                    // the parameter
                    bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, null, param, prefixedUrlfilename, null,
                            msg);

                    // All done. No need to look for vulnerabilities on subsequent parameters
                    // on the same request (to reduce performance impact)
                    return;
                }

                // Check if the scan has been stopped
                // if yes dispose resources and exit
                if (isStop()) {
                    // Dispose all resources
                    // Exit the plugin
                    return;
                }
            }
        }

        // Check 6 for local file names
        // TODO: consider making this check 1, for performance reasons
        // TODO: if the original query was http://www.example.com/a/b/c/d.jsp?param=paramvalue
        // then check if the following gives comparable results to the original query
        // http://www.example.com/a/b/c/d.jsp?param=../c/paramvalue
        // if it does, then we likely have a local file Path Traversal vulnerability
        // this is nice because it means we do not have to guess any file names, and would only
        // require one
        // request to find the vulnerability
        // but it would be foiled by simple input validation on "..", for instance.

    } catch (SocketTimeoutException ste) {
        log.warn("A timeout occurred while checking [" + msg.getRequestHeader().getMethod() + "] ["
                + msg.getRequestHeader().getURI() + "], parameter [" + param + "] for Path Traversal. "
                + "The currently configured timeout is: " + Integer.toString(
                        Model.getSingleton().getOptionsParam().getConnectionParam().getTimeoutInSecs()));

        if (log.isDebugEnabled()) {
            log.debug("Caught " + ste.getClass().getName() + " " + ste.getMessage());
        }

    } catch (IOException e) {
        log.warn("An error occurred while checking [" + msg.getRequestHeader().getMethod() + "] ["
                + msg.getRequestHeader().getURI() + "], parameter [" + param + "] for Path Traversal."
                + "Caught " + e.getClass().getName() + " " + e.getMessage());
    }
}

From source file:utybo.branchingstorytree.swing.OpenBSTGUI.java

/**
 * Load and parse a file, using appropriate dialogs if an error occurs to
 * inform the user and even give him the option to reload the file
 *
 * @param file/*from w w w  .  j  a v  a2s  . co m*/
 *            The file to load
 * @param client
 *            The BST Client. This is required for parsing the file
 * @return
 */
public void loadFile(final File file, final TabClient client, Consumer<BranchingStory> callback) {
    SwingWorker<BranchingStory, Object> worker = new SwingWorker<BranchingStory, Object>() {
        @Override
        protected BranchingStory doInBackground() throws Exception {
            try {
                LOG.trace("Parsing story");
                String ext = FilenameUtils.getExtension(file.getName());
                BranchingStory bs = null;
                if (ext.equals("bsp")) {
                    bs = BSTPackager.fromPackage(new ProgressMonitorInputStream(instance,
                            "Opening " + file.getName() + "...", new FileInputStream(file)), client);
                } else {
                    bs = parser
                            .parse(new BufferedReader(new InputStreamReader(
                                    new ProgressMonitorInputStream(instance,
                                            "Opening " + file.getName() + "...", new FileInputStream(file)),
                                    StandardCharsets.UTF_8)), new Dictionary(), client, "<main>");
                    client.setBRMHandler(new BRMFileClient(file, client, bs));
                }
                callback.accept(bs);
                return bs;
            } catch (final IOException e) {
                LOG.error("IOException caught", e);
                showException(Lang.get("file.error").replace("$e", e.getClass().getSimpleName()).replace("$m",
                        e.getMessage()), e);
                return null;
            } catch (final BSTException e) {
                LOG.error("BSTException caught", e);
                String s = "<html>" + Lang.get("file.bsterror.1");
                s += Lang.get("file.bsterror.2");
                s += Lang.get("file.bsterror.3").replace("$l", "" + e.getWhere()).replace("$f", "[main]");
                if (e.getCause() != null) {
                    s += Lang.get("file.bsterror.4").replace("$e", e.getCause().getClass().getSimpleName())
                            .replace("$m", e.getCause().getMessage());
                }
                s += Lang.get("file.bsterror.5").replace("$m", "" + e.getMessage());
                s += Lang.get("file.bsterror.6");
                String s2 = s;
                if (doAndReturn(() -> Messagers.showConfirm(instance, s2, Messagers.OPTIONS_YES_NO,
                        Messagers.TYPE_ERROR, Lang.get("bsterror"))) == Messagers.OPTION_YES) {
                    LOG.debug("Reloading");
                    return doInBackground();
                }
                return null;
            } catch (final Exception e) {
                LOG.error("Random exception caught", e);
                showException(Lang.get("file.crash"), e);
                return null;
            }

        }

        private <T> T doAndReturn(Supplier<T> supplier) {
            ArrayList<T> l = new ArrayList<>();
            invokeSwingAndWait(() -> {
                l.add(supplier.get());
            });
            return l.size() == 0 ? null : l.get(0);
        }

        @Override
        protected void done() {
            try {
                get();
            } catch (InterruptedException e) {
                // Shouldn't happen
            } catch (ExecutionException e) {
                LOG.error("Random exception caught", e);
                Messagers.showException(instance, Lang.get("file.crash"), e);
            }
        }
    };
    worker.execute();
}

From source file:de.j4velin.mapsmeasure.Map.java

@SuppressLint("NewApi")
@Override/*from ww w .j  av a 2  s  .c om*/
public void onCreate(final Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
    } catch (final BadParcelableException bpe) {
        bpe.printStackTrace();
    }
    setContentView(R.layout.activity_map);

    formatter_no_dec.setMaximumFractionDigits(0);
    formatter_two_dec.setMaximumFractionDigits(2);

    final SharedPreferences prefs = getSharedPreferences("settings", Context.MODE_PRIVATE);

    // use metric a the default everywhere, except in the US
    metric = prefs.getBoolean("metric", !Locale.getDefault().equals(Locale.US));

    final View topCenterOverlay = findViewById(R.id.topCenterOverlay);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    final View menuButton = findViewById(R.id.menu);
    if (menuButton != null) {
        menuButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                mDrawerLayout.openDrawer(GravityCompat.START);
            }
        });
    }

    if (mDrawerLayout != null) {
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {

            private boolean menuButtonVisible = true;

            @Override
            public void onDrawerStateChanged(int newState) {

            }

            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onDrawerSlide(final View drawerView, final float slideOffset) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
                    topCenterOverlay.setAlpha(1 - slideOffset);
                if (menuButtonVisible && menuButton != null && slideOffset > 0) {
                    menuButton.setVisibility(View.INVISIBLE);
                    menuButtonVisible = false;
                }
            }

            @Override
            public void onDrawerOpened(final View drawerView) {
                if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
                    topCenterOverlay.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onDrawerClosed(final View drawerView) {
                if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
                    topCenterOverlay.setVisibility(View.VISIBLE);
                if (menuButton != null) {
                    menuButton.setVisibility(View.VISIBLE);
                    menuButtonVisible = true;
                }
            }
        });
    }

    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    if (mMap == null) {
        Dialog d = GooglePlayServicesUtil
                .getErrorDialog(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this), this, 0);
        d.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
        d.show();
        return;
    }

    marker = BitmapDescriptorFactory.fromResource(R.drawable.marker);
    mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(final Marker click) {
            addPoint(click.getPosition());
            return true;
        }
    });

    mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
        @Override
        public boolean onMyLocationButtonClick() {
            if (mMap.getMyLocation() != null) {
                LatLng myLocation = new LatLng(mMap.getMyLocation().getLatitude(),
                        mMap.getMyLocation().getLongitude());
                double distance = SphericalUtil.computeDistanceBetween(myLocation,
                        mMap.getCameraPosition().target);

                // Only if the distance is less than 50cm we are on our location, add the marker
                if (distance < 0.5) {
                    Toast.makeText(Map.this, R.string.marker_on_current_location, Toast.LENGTH_SHORT).show();
                    addPoint(myLocation);
                }
            }
            return false;
        }
    });

    // check if open with csv file
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        try {
            Util.loadFromFile(getIntent().getData(), this);
            if (!trace.isEmpty())
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(trace.peek(), 16));
        } catch (IOException e) {
            Toast.makeText(this,
                    getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(final Bundle bundle) {
                    Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    if (l != null && mMap.getCameraPosition().zoom <= 2) {
                        mMap.moveCamera(CameraUpdateFactory
                                .newLatLngZoom(new LatLng(l.getLatitude(), l.getLongitude()), 16));
                    }
                    mGoogleApiClient.disconnect();
                }

                @Override
                public void onConnectionSuspended(int cause) {

                }
            }).build();
    mGoogleApiClient.connect();

    valueTv = (TextView) findViewById(R.id.distance);
    updateValueText();
    valueTv.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (type == MeasureType.DISTANCE)
                changeType(MeasureType.AREA);
            // only switch to elevation mode is an internet connection is
            // available and user has access to this feature
            else if (type == MeasureType.AREA && Util.checkInternetConnection(Map.this) && PRO_VERSION)
                changeType(MeasureType.ELEVATION);
            else
                changeType(MeasureType.DISTANCE);
        }
    });

    View delete = findViewById(R.id.delete);
    delete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            removeLast();
        }
    });
    delete.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(final View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(Map.this);
            builder.setMessage(getString(R.string.delete_all, trace.size()));
            builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    clear();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
            return true;
        }
    });

    mMap.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(final LatLng center) {
            addPoint(center);
        }
    });

    // Drawer stuff
    ListView drawerList = (ListView) findViewById(R.id.left_drawer);
    drawerListAdapert = new DrawerListAdapter(this);
    drawerList.setAdapter(drawerListAdapert);
    drawerList.setDivider(null);
    drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, int position, long id) {
            switch (position) {
            case 0: // Search before Android 5.0
                Dialogs.getSearchDialog(Map.this).show();
                closeDrawer();
                break;
            case 2: // Units
                Dialogs.getUnits(Map.this, distance, SphericalUtil.computeArea(trace)).show();
                closeDrawer();
                break;
            case 3: // distance
                changeType(MeasureType.DISTANCE);
                break;
            case 4: // area
                changeType(MeasureType.AREA);
                break;
            case 5: // elevation
                if (PRO_VERSION) {
                    changeType(MeasureType.ELEVATION);
                } else {
                    Dialogs.getElevationAccessDialog(Map.this, mService).show();
                }
                break;
            case 7: // map
                changeView(GoogleMap.MAP_TYPE_NORMAL);
                break;
            case 8: // satellite
                changeView(GoogleMap.MAP_TYPE_HYBRID);
                break;
            case 9: // terrain
                changeView(GoogleMap.MAP_TYPE_TERRAIN);
                break;
            case 11: // save
                Dialogs.getSaveNShare(Map.this, trace).show();
                closeDrawer();
                break;
            case 12: // more apps
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:j4velin"))
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (ActivityNotFoundException anf) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://play.google.com/store/apps/developer?id=j4velin"))
                                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;
            case 13: // about
                Dialogs.getAbout(Map.this).show();
                closeDrawer();
                break;
            default:
                break;
            }
        }
    });

    changeView(prefs.getInt("mapView", GoogleMap.MAP_TYPE_NORMAL));
    changeType(MeasureType.DISTANCE);

    // KitKat translucent decor enabled? -> Add some margin/padding to the
    // drawer and the map
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {

        int statusbar = Util.getStatusBarHeight(this);

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) topCenterOverlay.getLayoutParams();
        lp.setMargins(0, statusbar + 10, 0, 0);
        topCenterOverlay.setLayoutParams(lp);

        // on most devices and in most orientations, the navigation bar
        // should be at the bottom and therefore reduces the available
        // display height
        int navBarHeight = Util.getNavigationBarHeight(this);

        DisplayMetrics total, available;
        total = new DisplayMetrics();
        available = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(available);
        API17Wrapper.getRealMetrics(getWindowManager().getDefaultDisplay(), total);

        boolean navBarOnRight = getResources()
                .getConfiguration().orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
                && (total.widthPixels - available.widthPixels > 0);

        if (navBarOnRight) {
            // in landscape on phones, the navigation bar might be at the
            // right side, reducing the available display width
            mMap.setPadding(mDrawerLayout == null ? Util.dpToPx(this, 200) : 0, statusbar, navBarHeight, 0);
            drawerList.setPadding(0, statusbar + 10, 0, 0);
            if (menuButton != null)
                menuButton.setPadding(0, 0, 0, 0);
        } else {
            mMap.setPadding(0, statusbar, 0, navBarHeight);
            drawerList.setPadding(0, statusbar + 10, 0, 0);
            drawerListAdapert.setMarginBottom(navBarHeight);
            if (menuButton != null)
                menuButton.setPadding(0, 0, 0, navBarHeight);
        }
    }

    mMap.setMyLocationEnabled(true);

    PRO_VERSION |= prefs.getBoolean("pro", false);
    if (!PRO_VERSION) {
        bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND")
                .setPackage("com.android.vending"), mServiceConn, Context.BIND_AUTO_CREATE);
    }
}

From source file:photosharing.api.conx.FileDefinition.java

/**
 * gets the user library results//from   w w w  .j  av a 2  s .co m
 * 
 * @param request
 * @param response
 */
public void getUserLibraryResults(String bearer, HttpServletRequest request, HttpServletResponse response) {

    String userId = request.getParameter("userid");
    if (userId == null || userId.isEmpty()) {
        logger.warning("userId is null");
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    } else {
        // sets the content type - application/json
        response.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        String apiUrl = getUserLibraryApiUrl(userId);

        logger.info(apiUrl);

        Request get = Request.Get(apiUrl);
        get.addHeader("Authorization", "Bearer " + bearer);

        try {

            Executor exec = ExecutorUtil.getExecutor();
            Response apiResponse = exec.execute(get);

            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            // Session is no longer valid or access token is expired
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Default to SC_OK (200)
            else if (code == HttpStatus.SC_OK) {
                response.setStatus(HttpStatus.SC_OK);

                InputStream in = hr.getEntity().getContent();
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(in);

                // Logging out the JSON Object
                logger.info(jsonString);

                JSONObject feed = new JSONObject(jsonString).getJSONObject("feed");

                logger.info(feed.toString());

                JSONArray files = new JSONArray();

                JSONArray entries = null;
                if (feed.has("entry")) {
                    //Check if the Entry is a JSONObject or JSONArray
                    Object o = feed.get("entry");
                    if (o.getClass().getName().contains("JSONObject")) {
                        entries = new JSONArray();
                        entries.put(o);
                    } else {
                        entries = (JSONArray) o;
                    }
                } else {
                    entries = new JSONArray();
                }

                int len = entries.length();
                for (int i = 0; i < len; i++) {

                    JSONObject entry = entries.getJSONObject(i);
                    logger.info(entry.toString());

                    JSONObject author = entry.getJSONObject("author");
                    String photographer = author.getString("name");
                    String uid = author.getString("userid");

                    String title = entry.getJSONObject("title").getString("content");

                    String lid = entry.getString("libraryId");

                    String pid = entry.getString("uuid");

                    String thumbnail = "./api/file?action=thumbnail&pid=" + pid + "&lid=" + lid;

                    files.add(createPhoto(lid, pid, title, uid, photographer, thumbnail));

                }

                // Flush the Object to the Stream with content type
                response.setHeader("Content-Type", "application/json");
                PrintWriter out = response.getWriter();
                out.println(files.toString());
                out.flush();

            }

        } catch (IOException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("Issue with read userlibrary " + e.toString());
        } catch (JSONException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("Issue with read userlibrary " + e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("Issue with read userlibrary " + e.toString());
        }

    }

}

From source file:photosharing.api.conx.FileDefinition.java

/**
 * gets the user file metadata results//from  www . j  a  v a2  s . c  o m
 * 
 * Payload
 *  {"uid":"20971118","thumbnail":
 * ".\/api\/file?action=thumbnail&pid=7fdedc74-a9f4-46f1-acde-39bef9975847&lid=2597409c-b292-4059-bb4f-3c92c90f5c2e",
 * "like":true,"lid":"2597409c-b292-4059-bb4f-3c92c90f5c2e","pid":"7fdedc74-a9f4-46f1-acde-39bef9975847","photographer":"ASIC
 * ASIC","title":"Test32ab.jpeg","tags":["abcd","photojava"]}
 * 
 * @param request
 * @param response
 */
public void getFileMetadata(String bearer, HttpServletRequest request, HttpServletResponse response) {

    String library = request.getParameter("lid");
    String file = request.getParameter("pid");
    if (library == null || library.isEmpty() || file == null || file.isEmpty()) {
        logger.warning("library or file is null");
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    } else {
        // sets the content type - application/json
        response.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        String apiUrl = getFileMetadata(file, library);

        logger.info(apiUrl);

        Request get = Request.Get(apiUrl);
        get.addHeader("Authorization", "Bearer " + bearer);

        try {

            Executor exec = ExecutorUtil.getExecutor();
            Response apiResponse = exec.execute(get);

            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            // Session is no longer valid or access token is expired
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Default to SC_OK (200)
            else if (code == HttpStatus.SC_OK) {
                response.setStatus(HttpStatus.SC_OK);

                InputStream in = hr.getEntity().getContent();
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(in);

                // Logging out the JSON Object
                logger.info(jsonString);

                JSONObject result = new JSONObject(jsonString);
                JSONObject entry = result.getJSONObject("entry");

                logger.info(entry.toString());

                JSONObject author = entry.getJSONObject("author");
                String photographer = author.getString("name");
                String uid = author.getString("userid");
                String date = entry.getString("published");

                String title = entry.getJSONObject("title").getString("content");

                String lid = entry.getString("libraryId");

                String pid = entry.getString("uuid");

                String thumbnail = "./api/file?action=thumbnail&pid=" + pid + "&lid=" + lid;

                JSONObject res = new JSONObject(createPhoto(lid, pid, title, uid, photographer, thumbnail));

                JSONArray links = entry.getJSONArray("link");
                @SuppressWarnings("rawtypes")
                Iterator iter = links.iterator();
                while (iter.hasNext()) {
                    JSONObject obj = (JSONObject) iter.next();
                    String rel = obj.getString("rel");
                    if (rel != null && rel.compareTo("recommendation") == 0) {
                        res.put("like", true);
                    }
                }

                JSONArray categories = entry.getJSONArray("category");
                iter = categories.iterator();
                JSONArray tags = new JSONArray();
                while (iter.hasNext()) {
                    JSONObject obj = (JSONObject) iter.next();
                    if (!obj.has("scheme")) {
                        tags.put(obj.getString("term"));
                    }
                }
                res.put("tags", tags);
                res.put("published", date);

                // Flush the Object to the Stream with content type
                response.setHeader("Content-Type", "application/json");
                PrintWriter out = response.getWriter();
                out.println(res.toString());
                out.flush();

            }

        } catch (IOException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("Issue with read userlibrary " + e.toString());
        } catch (JSONException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("Issue with read userlibrary " + e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("Issue with read userlibrary " + e.toString());
        }

    }

}

From source file:org.apache.hadoop.hbase.ipc.ServerRpcConnection.java

public void saslReadAndProcess(ByteBuff saslToken) throws IOException, InterruptedException {
    if (saslContextEstablished) {
        RpcServer.LOG.trace("Read input token of size={} for processing by saslServer.unwrap()",
                saslToken.limit());// w  w w  .j  a  v  a  2 s.  com
        if (!useWrap) {
            processOneRpc(saslToken);
        } else {
            byte[] b = saslToken.hasArray() ? saslToken.array() : saslToken.toBytes();
            byte[] plaintextData;
            if (useCryptoAesWrap) {
                // unwrap with CryptoAES
                plaintextData = cryptoAES.unwrap(b, 0, b.length);
            } else {
                plaintextData = saslServer.unwrap(b, 0, b.length);
            }
            processUnwrappedData(plaintextData);
        }
    } else {
        byte[] replyToken;
        try {
            if (saslServer == null) {
                saslServer = new HBaseSaslRpcServer(authMethod, rpcServer.saslProps, rpcServer.secretManager);
                RpcServer.LOG.debug("Created SASL server with mechanism={}", authMethod.getMechanismName());
            }
            RpcServer.LOG.debug(
                    "Read input token of size={} for processing by saslServer." + "evaluateResponse()",
                    saslToken.limit());
            replyToken = saslServer
                    .evaluateResponse(saslToken.hasArray() ? saslToken.array() : saslToken.toBytes());
        } catch (IOException e) {
            IOException sendToClient = e;
            Throwable cause = e;
            while (cause != null) {
                if (cause instanceof InvalidToken) {
                    sendToClient = (InvalidToken) cause;
                    break;
                }
                cause = cause.getCause();
            }
            doRawSaslReply(SaslStatus.ERROR, null, sendToClient.getClass().getName(),
                    sendToClient.getLocalizedMessage());
            this.rpcServer.metrics.authenticationFailure();
            String clientIP = this.toString();
            // attempting user could be null
            RpcServer.AUDITLOG
                    .warn(RpcServer.AUTH_FAILED_FOR + clientIP + ":" + saslServer.getAttemptingUser());
            throw e;
        }
        if (replyToken != null) {
            if (RpcServer.LOG.isDebugEnabled()) {
                RpcServer.LOG.debug("Will send token of size " + replyToken.length + " from saslServer.");
            }
            doRawSaslReply(SaslStatus.SUCCESS, new BytesWritable(replyToken), null, null);
        }
        if (saslServer.isComplete()) {
            String qop = saslServer.getNegotiatedQop();
            useWrap = qop != null && !"auth".equalsIgnoreCase(qop);
            ugi = getAuthorizedUgi(saslServer.getAuthorizationID());
            if (RpcServer.LOG.isDebugEnabled()) {
                RpcServer.LOG.debug("SASL server context established. Authenticated client: " + ugi
                        + ". Negotiated QoP is " + qop);
            }
            this.rpcServer.metrics.authenticationSuccess();
            RpcServer.AUDITLOG.info(RpcServer.AUTH_SUCCESSFUL_FOR + ugi);
            saslContextEstablished = true;
        }
    }
}

From source file:com.meidusa.venus.client.RemotingInvocationHandler.java

protected Object invokeRemoteService(Service service, Endpoint endpoint, Method method,
        EndpointParameter[] params, Object[] args) throws Exception {
    String apiName = VenusAnnotationUtils.getApiname(method, service, endpoint);

    AthenaTransactionId athenaTransactionId = null;
    if (service.athenaFlag()) {
        athenaTransactionId = AthenaTransactionDelegate.getDelegate().startClientTransaction(apiName);
    }/*  ww w.j a  va  2  s  .  co  m*/
    boolean async = false;

    if (endpoint.async()) {
        async = true;
    }

    byte[] traceID = VenusTracerUtil.getTracerID();

    if (traceID == null) {
        traceID = VenusTracerUtil.randomTracerID();
    }

    Serializer serializer = SerializerFactory.getSerializer(serializeType);

    SerializeServiceRequestPacket serviceRequestPacket = new SerializeServiceRequestPacket(serializer, null);

    serviceRequestPacket.clientId = PacketConstant.VENUS_CLIENT_ID;
    serviceRequestPacket.clientRequestId = sequenceId.getAndIncrement();
    serviceRequestPacket.traceId = traceID;
    serviceRequestPacket.apiName = apiName;
    serviceRequestPacket.serviceVersion = service.version();
    serviceRequestPacket.parameterMap = new HashMap<String, Object>();

    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            if (args[i] instanceof InvocationListener) {
                async = true;
                ReferenceInvocationListener listener = new ReferenceInvocationListener();
                ServicePacketBuffer buffer = new ServicePacketBuffer(16);
                buffer.writeLengthCodedString(args[i].getClass().getName(), "utf-8");
                buffer.writeInt(System.identityHashCode(args[i]));
                listener.setIdentityData(buffer.toByteBuffer().array());
                Type type = method.getGenericParameterTypes()[i];
                if (type instanceof ParameterizedType) {
                    ParameterizedType genericType = ((ParameterizedType) type);
                    container.putInvocationListener((InvocationListener) args[i],
                            genericType.getActualTypeArguments()[0]);
                } else {
                    throw new InvalidParameterException("invocationListener is not generic");
                }

                serviceRequestPacket.parameterMap.put(params[i].getParamName(), listener);
            } else {
                serviceRequestPacket.parameterMap.put(params[i].getParamName(), args[i]);
            }

        }
    }
    setTransactionId(serviceRequestPacket, athenaTransactionId);

    PerformanceLevel pLevel = AnnotationUtil.getAnnotation(method.getAnnotations(), PerformanceLevel.class);
    long start = TimeUtil.currentTimeMillis();
    long borrowed = start;

    if (async) {
        if (!this.isEnableAsync()) {
            throw new VenusConfigException("service async call disabled");
        }

        BackendConnection conn = null;
        try {

            if (nioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (BackendConnection) ((RequestLoadbalanceObjectPool) nioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = nioConnPool.borrowObject();
            }
            borrowed = TimeUtil.currentTimeMillis();

            conn.write(serviceRequestPacket.toByteBuffer());
            VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                    JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
            return null;
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            if (performanceLogger.isDebugEnabled()) {
                long end = TimeUtil.currentTimeMillis();
                long time = end - borrowed;
                StringBuffer buffer = new StringBuffer();
                buffer.append("[").append(borrowed - start).append(",").append(time)
                        .append("]ms (*client,async*) traceID=").append(UUID.toString(traceID)).append(", api=")
                        .append(serviceRequestPacket.apiName);

                performanceLogger.debug(buffer.toString());
            }

            if (conn != null) {
                nioConnPool.returnObject(conn);
            }
        }
    } else {
        AbstractBIOConnection conn = null;
        int soTimeout = 0;
        int oldTimeout = 0;
        boolean success = true;
        int errorCode = 0;
        AbstractServicePacket packet = null;
        String remoteAddress = null;
        boolean invalided = false;
        try {
            if (bioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (AbstractBIOConnection) ((RequestLoadbalanceObjectPool) bioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = (AbstractBIOConnection) bioConnPool.borrowObject();
            }
            remoteAddress = conn.getRemoteAddress();
            borrowed = TimeUtil.currentTimeMillis();
            ServiceConfig config = this.serviceFactory.getServiceConfig(method.getDeclaringClass());

            oldTimeout = conn.getSoTimeout();
            if (config != null) {
                EndpointConfig endpointConfig = config.getEndpointConfig(endpoint.name());
                if (endpointConfig != null) {
                    int eTimeOut = endpointConfig.getTimeWait();
                    if (eTimeOut > 0) {
                        soTimeout = eTimeOut;
                    }
                } else {
                    if (config.getTimeWait() > 0) {
                        soTimeout = config.getTimeWait();
                    } else {
                        if (endpoint.timeWait() > 0) {
                            soTimeout = endpoint.timeWait();
                        }
                    }
                }

            } else {

                if (endpoint.timeWait() > 0) {
                    soTimeout = endpoint.timeWait();
                }
            }

            byte[] bts;

            try {

                if (soTimeout > 0) {
                    conn.setSoTimeout(soTimeout);
                }
                conn.write(serviceRequestPacket.toByteArray());
                VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                        JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                bts = conn.read();
            } catch (IOException e) {
                try {
                    conn.close();
                } catch (Exception e1) {
                    // ignore
                }

                bioConnPool.invalidateObject(conn);
                invalided = true;
                Class<?>[] eClass = method.getExceptionTypes();

                if (eClass != null && eClass.length > 0) {
                    for (Class<?> clazz : eClass) {
                        if (e.getClass().isAssignableFrom(clazz)) {
                            throw e;
                        }
                    }
                }

                throw new RemoteSocketIOException("api=" + serviceRequestPacket.apiName + ", remoteIp="
                        + conn.getRemoteAddress() + ",(" + e.getMessage() + ")", e);
            }

            int type = AbstractServicePacket.getType(bts);
            switch (type) {
            case PacketConstant.PACKET_TYPE_ERROR:
                ErrorPacket error = new ErrorPacket();
                error.init(bts);
                packet = error;
                Exception e = venusExceptionFactory.getException(error.errorCode, error.message);
                if (e == null) {
                    throw new DefaultVenusException(error.errorCode, error.message);
                } else {
                    if (error.additionalData != null) {
                        Map<String, Type> tmap = Utils.getBeanFieldType(e.getClass(), Exception.class);
                        if (tmap != null && tmap.size() > 0) {
                            Object obj = serializer.decode(error.additionalData, tmap);
                            BeanUtils.copyProperties(e, obj);
                        }
                    }
                    throw e;
                }
            case PacketConstant.PACKET_TYPE_OK:
                OKPacket ok = new OKPacket();
                ok.init(bts);
                packet = ok;
                return null;
            case PacketConstant.PACKET_TYPE_SERVICE_RESPONSE:
                ServiceResponsePacket response = new SerializeServiceResponsePacket(serializer,
                        method.getGenericReturnType());
                response.init(bts);
                packet = response;
                return response.result;
            default: {
                logger.warn("unknow response type=" + type);
                success = false;
                return null;
            }
            }
        } catch (Exception e) {
            success = false;

            if (e instanceof CodedException
                    || (errorCode = venusExceptionFactory.getErrorCode(e.getClass())) != 0
                    || e instanceof RuntimeException) {
                if (e instanceof CodedException) {
                    errorCode = ((CodedException) e).getErrorCode();
                }
                throw e;
            } else {
                RemoteException code = e.getClass().getAnnotation(RemoteException.class);
                if (code != null) {
                    errorCode = code.errorCode();
                    throw e;
                } else {
                    ExceptionCode eCode = e.getClass().getAnnotation(ExceptionCode.class);
                    if (eCode != null) {
                        errorCode = eCode.errorCode();
                        throw e;
                    } else {
                        errorCode = -1;
                        if (conn == null) {
                            throw new DefaultVenusException(e.getMessage(), e);
                        } else {
                            throw new DefaultVenusException(
                                    e.getMessage() + ". remoteAddress=" + conn.getRemoteAddress(), e);
                        }
                    }
                }
            }
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            long end = TimeUtil.currentTimeMillis();
            long time = end - borrowed;
            StringBuffer buffer = new StringBuffer();
            buffer.append("[").append(borrowed - start).append(",").append(time)
                    .append("]ms (*client,sync*) traceID=").append(UUID.toString(traceID)).append(", api=")
                    .append(serviceRequestPacket.apiName);
            if (remoteAddress != null) {
                buffer.append(", remote=").append(remoteAddress);
            } else {
                buffer.append(", pool=").append(bioConnPool.toString());
            }
            buffer.append(", clientID=").append(PacketConstant.VENUS_CLIENT_ID).append(", requestID=")
                    .append(serviceRequestPacket.clientRequestId);

            if (packet != null) {
                if (packet instanceof ErrorPacket) {
                    buffer.append(", errorCode=").append(((ErrorPacket) packet).errorCode);
                    buffer.append(", message=").append(((ErrorPacket) packet).message);
                } else {
                    buffer.append(", errorCode=0");
                }
            }

            if (pLevel != null) {

                if (pLevel.printParams()) {
                    buffer.append(", params=");
                    buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                }

                if (time > pLevel.error() && pLevel.error() > 0) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time > pLevel.warn() && pLevel.warn() > 0) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time > pLevel.info() && pLevel.info() > 0) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            } else {
                buffer.append(", params=");
                buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));

                if (time >= 30 * 1000) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time >= 10 * 1000) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time >= 5 * 1000) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            }

            if (conn != null && !invalided) {
                if (!conn.isClosed() && soTimeout > 0) {
                    conn.setSoTimeout(oldTimeout);
                }
                bioConnPool.returnObject(conn);
            }

        }
    }
}

From source file:com.amalto.core.delegator.IItemCtrlDelegator.java

public ArrayList<String> viewSearch(DataClusterPOJOPK dataClusterPOJOPK, ViewPOJOPK viewPOJOPK,
        IWhereItem whereItem, String orderBy, String direction, int start, int limit) throws XtentisException {
    try {/* w  ww . ja v a 2  s .c  o  m*/
        ViewPOJO view = getViewPOJO(viewPOJOPK);
        whereItem = Util.fixWebConditions(whereItem, getLocalUser().getUserXML());
        // Create an ItemWhere which combines the search and and view wheres
        ArrayList<IWhereItem> conditions = view.getWhereConditions().getList();
        // fix conditions: value of condition do not generate xquery.
        Util.fixConditions(conditions);
        // Set User Property conditions.
        if (Util.isContainUserProperty(conditions)) {
            Util.updateUserPropertyCondition(conditions, getLocalUser().getUserXML());
        }
        IWhereItem fullWhere = getFullWhereCondition(whereItem, conditions);
        // Add Filters from the Roles
        ILocalUser user = getLocalUser();
        HashSet<String> roleNames = user.getRoles();
        String objectType = "View"; //$NON-NLS-1$
        ArrayList<IWhereItem> roleWhereConditions = new ArrayList<IWhereItem>();
        for (String roleName : roleNames) {
            if (SecurityConfig.isSecurityPermission(roleName)) {
                continue;
            }
            // load Role
            RolePOJO role = ObjectPOJO.load(RolePOJO.class, new RolePOJOPK(roleName));
            // get Specifications for the View Object
            RoleSpecification specification = role.getRoleSpecifications().get(objectType);
            if (specification != null) {
                if (!specification.isAdmin()) {
                    Set<String> regexIds = specification.getInstances().keySet();
                    for (String regexId : regexIds) {
                        if (viewPOJOPK.getIds()[0].matches(regexId)) {
                            HashSet<String> parameters = specification.getInstances().get(regexId)
                                    .getParameters();
                            for (String marshaledWhereCondition : parameters) {
                                if (marshaledWhereCondition == null
                                        || marshaledWhereCondition.trim().length() == 0) {
                                    continue;
                                }
                                WhereCondition whereCondition = RoleWhereCondition
                                        .parse(marshaledWhereCondition).toWhereCondition();
                                String conditionValue = whereCondition.getRightValueOrPath();
                                if ((conditionValue != null && conditionValue.length() > 0)
                                        || WhereCondition.EMPTY_NULL.equals(whereCondition.getOperator())) {
                                    roleWhereConditions.add(whereCondition);
                                }
                            }
                        }
                    }
                }
            }
        }
        // add collected additional conditions
        if (roleWhereConditions.size() > 0) {
            // Set User Property conditions.
            if (Util.isContainUserProperty(roleWhereConditions)) {
                Util.updateUserPropertyCondition(roleWhereConditions, getLocalUser().getUserXML());
            }
            IWhereItem normalizedRolesConditions = normalizeConditions(roleWhereConditions);
            if (fullWhere == null) {
                fullWhere = normalizedRolesConditions;
            } else {
                WhereAnd wAnd = new WhereAnd();
                wAnd.add(fullWhere);
                wAnd.add(normalizedRolesConditions);
                fullWhere = wAnd;
            }
        }
        // Find revision id for type
        String typeName = view.getSearchableBusinessElements().getList().get(0).split("/")[0]; //$NON-NLS-1$
        // Try to get storage for revision
        Server server = ServerContext.INSTANCE.get();
        String dataModelName = dataClusterPOJOPK.getUniqueId();
        StorageAdmin storageAdmin = server.getStorageAdmin();
        Storage storage = storageAdmin.get(dataModelName, storageAdmin.getType(dataModelName));
        MetadataRepository repository = storage.getMetadataRepository();
        boolean isStaging = storage.getType() == StorageType.STAGING;
        // Build query (from 'main' type)
        ComplexTypeMetadata type = repository.getComplexType(typeName);
        if (type == null) {
            throw new IllegalArgumentException(
                    "Type '" + typeName + "' does not exist in data cluster '" + dataModelName //$NON-NLS-1$ //$NON-NLS-2$
                            + "'."); //$NON-NLS-1$
        }
        UserQueryBuilder qb = UserQueryBuilder.from(type);
        // Select fields
        ArrayListHolder<String> viewableBusinessElements = view.getViewableBusinessElements();
        for (String viewableBusinessElement : viewableBusinessElements.getList()) {
            String viewableTypeName = StringUtils.substringBefore(viewableBusinessElement, "/"); //$NON-NLS-1$
            String viewablePath = StringUtils.substringAfter(viewableBusinessElement, "/"); //$NON-NLS-1$
            if (viewablePath.isEmpty()) {
                throw new IllegalArgumentException("View element '" + viewableBusinessElement //$NON-NLS-1$
                        + "' is invalid: no path to element."); //$NON-NLS-1$
            }
            ComplexTypeMetadata viewableType = repository.getComplexType(viewableTypeName);
            List<TypedExpression> fields = UserQueryHelper.getFields(viewableType, viewablePath);
            for (TypedExpression field : fields) {
                if (isNeedToAddExplicitly(isStaging, field)) {
                    qb.select(field);
                }
            }
        }
        qb.select(repository.getComplexType(typeName), "../../taskId"); //$NON-NLS-1$
        if (isStaging) {
            qb.select(repository.getComplexType(typeName), "$staging_status$"); //$NON-NLS-1$
            qb.select(repository.getComplexType(typeName), "$staging_error$"); //$NON-NLS-1$
            qb.select(repository.getComplexType(typeName), "$staging_source$"); //$NON-NLS-1$
        }
        // Condition and paging
        qb.where(UserQueryHelper.buildCondition(qb, fullWhere, repository));
        qb.start(start < 0 ? 0 : start); // UI can send negative start index
        qb.limit(limit);
        // Order by
        if (orderBy != null) {
            ComplexTypeMetadata orderByType = repository
                    .getComplexType(StringUtils.substringBefore(orderBy, "/")); //$NON-NLS-1$
            String orderByFieldName = StringUtils.substringAfter(orderBy, "/"); //$NON-NLS-1$
            List<TypedExpression> fields = UserQueryHelper.getFields(orderByType, orderByFieldName);
            OrderBy.Direction queryDirection;
            if ("ascending".equals(direction) //$NON-NLS-1$
                    || "NUMBER:ascending".equals(direction) //$NON-NLS-1$
                    || "ASC".equals(direction)) { //$NON-NLS-1$
                queryDirection = OrderBy.Direction.ASC;
            } else {
                queryDirection = OrderBy.Direction.DESC;
            }
            for (TypedExpression field : fields) {
                qb.orderBy(field, queryDirection);
            }
        }
        // Get records
        ArrayList<String> resultsAsString = new ArrayList<String>();
        try {
            storage.begin();
            StorageResults results = storage.fetch(qb.getSelect());
            resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$
            DataRecordWriter writer = new ViewSearchResultsWriter();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            for (DataRecord result : results) {
                try {
                    writer.write(result, output);
                } catch (IOException e) {
                    throw new XmlServerException(e);
                }
                String document = new String(output.toByteArray(), Charset.forName("UTF-8")); //$NON-NLS-1$
                resultsAsString.add(document);
                output.reset();
            }
            storage.commit();
        } catch (Exception e) {
            storage.rollback();
            throw new XmlServerException(e);
        }
        return resultsAsString;
    } catch (XtentisException e) {
        throw (e);
    } catch (Exception e) {
        String err = "Unable to single search: " + ": " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                + e.getLocalizedMessage();
        LOGGER.error(err, e);
        throw new XtentisException(err, e);
    }
}

From source file:com.ibm.stocator.fs.swift.http.SwiftConnectionManager.java

/**
 * Creates custom retry handler to be used if HTTP exception happens
 *
 * @return retry handler/* ww w .  jav  a 2s  .  co m*/
 */
private HttpRequestRetryHandler getRetryHandler() {

    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            System.out.println(executionCount);
            if (executionCount >= connectionConfiguration.getExecutionCount()) {
                // Do not retry if over max retry count
                LOG.debug("Execution count {} is bigger then threashold. Stop", executionCount);
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                LOG.debug("NoHttpResponseException exception. Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof UnknownHostException) {
                LOG.debug("UnknownHostException. Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof ConnectTimeoutException) {
                LOG.debug("ConnectTimeoutException. Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof SocketTimeoutException
                    || exception.getClass() == SocketTimeoutException.class
                    || exception.getClass().isInstance(SocketTimeoutException.class)) {
                // Connection refused
                LOG.debug("socketTimeoutException Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                LOG.debug("InterruptedIOException Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof SSLException) {
                LOG.debug("SSLException Retry count {}", executionCount);
                return true;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                LOG.debug("HttpEntityEnclosingRequest. Retry count {}", executionCount);
                return true;
            }
            LOG.debug("Retry stopped. Retry count {}", executionCount);
            return false;
        }
    };
    return myRetryHandler;
}

From source file:org.hippoecm.frontend.plugins.console.menu.patch.ApplyPatchDialog.java

private boolean uploadPatch() {
    final FileUpload upload = fileUploadField.getFileUpload();
    if (upload == null) {
        error("No file selected");
        return false;
    }/*ww  w  .j ava  2 s  .co m*/

    boolean result = false;
    InputStream uis = null, fis = null;
    OutputStream fos = null;
    final StringBuilder sb = new StringBuilder();
    try {
        uis = upload.getInputStream();
        tempFile = File.createTempFile("patch-" + Time.now(), ".xml");
        fos = new FileOutputStream(tempFile);
        IOUtils.copy(uis, fos);
        fis = new FileInputStream(tempFile);
        final Patch patch = parsePatch(fis);
        final String target = patch.getTarget();
        if (target != null && !target.equals(getModelObject().getPath())) {
            sb.append(
                    "The patch seems to be targeted at a different node than the one to which you are about to apply it.");
            sb.append(" Patch is targeted at ").append(target).append(".");
            sb.append(" About to apply patch to ").append(getModelObject().getPath()).append(".");
            sb.append(" Continue?");
        }
        if (patch.getOperations().isEmpty()) {
            sb.append("The patch is empty.");
        }
        result = true;
    } catch (IOException e) {
        final String message = "An unexpected error occurred: " + e.getMessage();
        error(message);
        log.error(message, e);
    } catch (RepositoryException e) {
        final String message = "An unexpected error occurred: " + e.getMessage();
        error(message);
        log.error(message, e);
    } finally {
        IOUtils.closeQuietly(uis);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(fis);
        final String message = sb.toString();
        if (!message.isEmpty()) {
            info(message);
        }
        if (result) {
            final AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class);
            try {
                fis = new FileInputStream(tempFile);
                textArea.setDefaultModelObject(new String(IOUtils.toCharArray(fis)));
                target.add(textArea);
            } catch (IOException e) {
                log.error(e.getClass().getName() + ": " + e.getMessage(), e);
            } finally {
                IOUtils.closeQuietly(fis);
            }
            fileUploadField.setEnabled(false);
            target.add(fileUploadField);
        }
    }

    return result;
}