Example usage for java.lang System loadLibrary

List of usage examples for java.lang System loadLibrary

Introduction

In this page you can find the example usage for java.lang System loadLibrary.

Prototype

@CallerSensitive
public static void loadLibrary(String libname) 

Source Link

Document

Loads the native library specified by the libname argument.

Usage

From source file:ml.dmlc.xgboost4j.java.NativeLibrary.java

/**
 * Load order:/*  ww w. j  a  va  2 s.  com*/
 *
 */
private void doLoad() throws IOException {
    final String libName = getName();
    try {
        System.loadLibrary(libName);
    } catch (UnsatisfiedLinkError e) {
        try {
            extractAndLoad(getPlatformLibraryPath(), getSimpleLibraryPath());
        } catch (IOException ioe) {
            logger.warn("Failed to load library from both native path and jar!");
            throw ioe;
        }
    }
}

From source file:org.nd4j.linalg.api.buffer.util.LibUtils.java

/**
 * Loads the specified library. The full name of the library
 * is created by calling {@link LibUtils#createLibName(String)}
 * with the given argument. The method will attempt to load
 * the library as a as a resource (for usage within a JAR),
 * and, if this fails, using the usual System.loadLibrary
 * call.//ww w  .j a va2 s  .  c o  m
 *
 * @param baseName The base name of the library
 * @throws UnsatisfiedLinkError if the native library
 * could not be loaded.
 */
public static void loadLibrary(String baseName) {
    String libName = LibUtils.createLibName(baseName);

    Throwable throwable = null;
    final boolean tryResource = true;
    if (tryResource) {
        try {
            loadLibraryResource(libName);
            return;
        } catch (Throwable t) {
            throwable = t;
        }
    }

    try {
        System.loadLibrary(libName);
        return;
    } catch (Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        pw.println(
                "Error while loading native library \"" + libName + "\" with base name \"" + baseName + "\"");
        pw.println("Operating system name: " + System.getProperty("os.name"));
        pw.println("Architecture         : " + System.getProperty("os.arch"));
        pw.println("Architecture bit size: " + System.getProperty("sun.arch.data.model"));

        if (throwable != null) {
            pw.println("Stack trace from the attempt to " + "load the library as a resource:");
            throwable.printStackTrace(pw);
        }

        pw.println("Stack trace from the attempt to " + "load the library as a file:");
        t.printStackTrace(pw);

        pw.flush();
        pw.close();
        throw new UnsatisfiedLinkError("Could not load the native library.\n" + sw.toString());
    }
}

From source file:org.cocos2dx.lib.Cocos2dxActivity.java

protected void onLoadNativeLibraries() {
    try {//from  ww  w  .j  av  a2 s .  c  o m
        ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(),
                PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        String libName = bundle.getString("android.app.lib_name");
        System.loadLibrary(libName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.hadoop.compression.fourmc.FourMcNativeCodeLoader.java

private static synchronized void loadLibrary() {
    if (nativeLibraryLoaded) {
        LOG.info("hadoop-4mc: native library is already loaded");
        return;/*from   w ww. ja va  2  s  .  com*/
    }

    if (useBinariesOnLibPath()) {
        try {
            System.loadLibrary("hadoop-4mc");
            nativeLibraryLoaded = true;
            LOG.info("hadoop-4mc: loaded native library (lib-path)");
        } catch (Exception e) {
            LOG.error("hadoop-4mc: cannot load native library (lib-path): ", e);
        }
        return;
    }

    // unpack and use embedded libraries

    String resourceName = resourceName();
    InputStream is = FourMcNativeCodeLoader.class.getResourceAsStream(resourceName);
    if (is == null) {
        throw new UnsupportedOperationException(
                "Unsupported OS/arch, cannot find " + resourceName + ". Please try building from source.");
    }
    File tempLib;
    try {
        tempLib = File.createTempFile("libhadoop-4mc", "." + os().libExtension);
        // copy to tempLib
        FileOutputStream out = new FileOutputStream(tempLib);
        try {
            byte[] buf = new byte[4096];
            while (true) {
                int read = is.read(buf);
                if (read == -1) {
                    break;
                }
                out.write(buf, 0, read);
            }
            try {
                out.close();
                out = null;
            } catch (IOException e) {
                // ignore
            }
            System.load(tempLib.getAbsolutePath());
            nativeLibraryLoaded = true;
            LOG.info("hadoop-4mc: loaded native library (embedded)");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                // ignore
            }
            if (tempLib.exists()) {
                if (!nativeLibraryLoaded) {
                    tempLib.delete();
                } else {
                    tempLib.deleteOnExit();
                }
            }
        }
    } catch (Exception e) {
        LOG.error("hadoop-4mc: cannot load native library  (embedded): ", e);
    }
}

From source file:Questao3.java

/**
 * Metodo para normalizar uma matriz/*from  w  w  w  . ja  v a 2 s  .  c  om*/
 * maior valor = 255
 * menor valor = 0
 * @param matriz
 * @return
 */
public double[][] normalizacao(double[][] matriz) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    /**
     * Maior e menor valor da matriz
     */
    double max = maxValue(matriz);
    double min = minValue(matriz);

    /**
     * Calcula a distancia entre os valores, que ser o valor
     * utilizado para normalizar
     */
    double dis = 255 / (max - min);

    /**
     * Matriz resultante = copia da original
     */
    double[][] result = matriz.clone();

    /**
     * Normalizacao - para cada pixel da matriz, multiplica-se o valor dis.
     */
    for (int i = 0; i < result.length; i++) {
        for (int j = 0; j < result[0].length; j++) {
            result[i][j] *= dis;
            ruido.put(i, j, result[i][j]);
        }
    }

    /**
     * Restorna o resultado
     */
    return result;
}

From source file:xbird.util.system.SystemUtils.java

private static void initializeSunJdk() {
    boolean useSunMx = false;
    if (IS_SUN_VM) {
        OperatingSystemMXBean mx = ManagementFactory.getOperatingSystemMXBean();
        com.sun.management.OperatingSystemMXBean sunmx = (com.sun.management.OperatingSystemMXBean) mx;
        long testval = sunmx.getProcessCpuTime();
        if (testval != -1L) {
            useSunMx = true;/*from  w w w.ja v  a2s . c o  m*/
        }
    }
    if (!useSunMx) {
        if (System.getProperty("xbird.use_jni") != null) {
            throw new IllegalStateException("Please set `xbird.use_jni' system property");
        }
        try {
            System.loadLibrary("xbird_util_lang_SystemUtils");
        } catch (UnsatisfiedLinkError le) {
            LogFactory.getLog(SystemUtils.class).warn(
                    "Performance monitoring is not supported for this JVM. Please ensure that 'xbird.profiling' property is not enabled in your 'xbird.properties'");
        }
    }
    useSunJdk6 = useSunMx;
}

From source file:uk.co.armedpineapple.innoextract.ExtractService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    mLoggingThread = new LoggingThread("Logging");

    Log.d(LOG_TAG, "Loading Library");
    System.loadLibrary("innoextract");

    mExtractDir = intent.getStringExtra(EXTRACT_DIR);
    mExtractFile = intent.getStringExtra(EXTRACT_FILE_PATH);
    mExtractFileName = intent.getStringExtra(EXTRACT_FILE_NAME);

    final Intent logIntent = new Intent(this, LogActivity.class);

    ExtractCallback cb = new ExtractCallback() {

        private String writeLogToFile() throws IOException {
            Log.d(LOG_TAG, "Writing log to file");
            String path = getCacheDir().getAbsolutePath() + File.separator + mExtractFileName + ".log.html";
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File(path)));
            bw.write(logBuilder.toString());
            bw.close();/* www . jav a 2s.  c o m*/
            Log.d(LOG_TAG, "Done writing to file");
            return path;
        }

        @Override
        public void onProgress(int value, int max) {
            mNotificationBuilder.setProgress(max, value, false);
            startForeground(ONGOING_NOTIFICATION, mNotificationBuilder.build());
        }

        @Override
        public void onSuccess() {
            Log.i(LOG_TAG, "SUCCESS! :)");

            mFinalNotificationBuilder.setTicker("Extract Successful").setSmallIcon(R.drawable.ic_extracting)
                    .setContentTitle("Extracted").setContentText("Extraction Successful");

            try {
                logIntent.putExtra("log", writeLogToFile());

                PendingIntent logPendingIntent = PendingIntent.getActivity(ExtractService.this, 0, logIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                mFinalNotificationBuilder.addAction(R.drawable.ic_view_log, "View Log", logPendingIntent);
            } catch (IOException e) {
                Log.d(LOG_TAG, "couldn't write log");
            }

            mNotificationManager.notify(FINAL_NOTIFICATION, mFinalNotificationBuilder.build());
            stopSelf();

        }

        @Override
        public void onFailure(Exception e) {
            Log.i(LOG_TAG, "FAIL! :(");
            mFinalNotificationBuilder.setTicker("Extract Failed").setSmallIcon(R.drawable.ic_extracting)
                    .setContentTitle("Extract Failed");

            try {
                logIntent.putExtra("log", writeLogToFile());

                PendingIntent logPendingIntent = PendingIntent.getActivity(ExtractService.this, 0, logIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                mFinalNotificationBuilder.addAction(R.drawable.ic_view_log, "View Log", logPendingIntent);
            } catch (IOException eb) {
                Log.d(LOG_TAG, "couldn't write log");
            }

            mNotificationManager.notify(FINAL_NOTIFICATION, mFinalNotificationBuilder.build());
            stopSelf();

        }

    };
    mFinalNotificationBuilder = new NotificationCompat.Builder(this);
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mNotificationBuilder.setContentTitle("Extracting...").setSmallIcon(R.drawable.ic_extracting)
            .setTicker("Extracting inno setup file").setContentText("Extracting inno setup file");
    startForeground(ONGOING_NOTIFICATION, mNotificationBuilder.build());

    performExtract(mExtractFile, mExtractDir, cb);

    return START_NOT_STICKY;
}

From source file:com.github.rosjava_catkin_package_a.ARLocROS.ARLoc.java

@Override
public void onStart(final ConnectedNode connectedNode) {
    // load OpenCV shared library
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    // read configuration variables from the ROS Runtime (configured in the
    // launch file)
    log = connectedNode.getLog();/*ww  w. j a  v  a  2 s  . c  o m*/
    log.info("Reading parameters");
    this.parameter = Parameter.createFromParameterTree(connectedNode.getParameterTree());

    // Read Marker Config
    markerConfig = MarkerConfig.createFromConfig(parameter.markerConfigFile(), parameter.patternDirectory());

    // setup rotation vector and translation vector storing output of the
    // localization
    rvec = new Mat(3, 1, CvType.CV_64F);
    tvec = new MatOfDouble(1.0, 1.0, 1.0);

    camp = getCameraInfo(connectedNode, parameter);

    // start to listen to transform messages in /tf in order to feed the
    // Transformer and lookup transforms
    final TransformationService transformationService = TransformationService.create(connectedNode);

    // Subscribe to Image
    Subscriber<sensor_msgs.Image> subscriberToImage = connectedNode.newSubscriber(parameter.cameraImageTopic(),
            sensor_msgs.Image._TYPE);

    ComputePose computePose = null;
    try {
        final Mat cameraMatrix = CameraParams.getCameraMatrix(camp);
        final MatOfDouble distCoeffs = CameraParams.getDistCoeffs(camp);
        computePose = ComputePose.create(markerConfig, new Size(camp.width(), camp.height()), cameraMatrix,
                distCoeffs, this.parameter.visualization());
    } catch (NyARException e) {
        logger.info("Cannot initialize ComputePose", e);
    } catch (FileNotFoundException e) {
        logger.info("Cannot find file when initialize ComputePose", e);
    }
    final ComputePose poseProcessor = computePose;
    subscriberToImage.addMessageListener(new MessageListener<sensor_msgs.Image>() {

        @Override
        public void onNewMessage(sensor_msgs.Image message) {
            //
            if (!message.getEncoding().toLowerCase().equals("rgb8")) {
                log.error("Sorry, " + message.getEncoding() + " Image encoding is not supported! EXITING");
                System.exit(-1);
            }
            if (camp != null) {
                try {
                    //
                    image = Utils.matFromImage(message);
                    // uncomment to add more contrast to the image
                    //Utils.tresholdContrastBlackWhite(image, 600);
                    Imgproc.threshold(image, image, 200, 255, Imgproc.THRESH_BINARY);
                    // Mat cannyimg = new Mat(image.height(), image.width(),
                    // CvType.CV_8UC3);
                    // Imgproc.Canny(image, cannyimg, 10, 100);
                    // Imshow.show(cannyimg);

                    // image.convertTo(image, -1, 1.5, 0);
                    // setup camera matrix and return vectors
                    // compute pose
                    if (poseProcessor.computePose(rvec, tvec, image)) {
                        // notify publisher threads (pose and tf, see below)
                        synchronized (tvec) {
                            tvec.notifyAll();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    // publish tf CAMERA_FRAME_NAME --> MARKER_FRAME_NAME
    final Publisher<tf2_msgs.TFMessage> tfPublisherCamToMarker = connectedNode.newPublisher("tf",
            tf2_msgs.TFMessage._TYPE);
    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {

            synchronized (tvec) {
                tvec.wait();
            }

            QuaternionHelper q = new QuaternionHelper();

            /*
             * http://euclideanspace.com/maths/geometry/rotations/
             * conversions/matrixToEuler/index.htm
             * http://stackoverflow.com/questions/12933284/rodrigues-into-
             * eulerangles-and-vice-versa
             * 
             * heading = atan2(-m20,m00) attitude = asin(m10) bank =
             * atan2(-m12,m11)
             */
            // convert output rotation vector rvec to rotation matrix R
            Mat R = new Mat(3, 3, CvType.CV_32FC1);
            Calib3d.Rodrigues(rvec, R);
            // get rotations around X,Y,Z from rotation matrix R
            double bankX = Math.atan2(-R.get(1, 2)[0], R.get(1, 1)[0]);
            double headingY = Math.atan2(-R.get(2, 0)[0], R.get(0, 0)[0]);
            double attitudeZ = Math.asin(R.get(1, 0)[0]);
            // convert Euler angles to quarternion
            q.setFromEuler(bankX, headingY, attitudeZ);

            // set information to message
            TFMessage tfmessage = tfPublisherCamToMarker.newMessage();
            TransformStamped posestamped = connectedNode.getTopicMessageFactory()
                    .newFromType(geometry_msgs.TransformStamped._TYPE);
            Transform transform = posestamped.getTransform();

            Quaternion orientation = transform.getRotation();
            Vector3 point = transform.getTranslation();
            point.setX(tvec.get(0, 0)[0]);
            point.setY(tvec.get(1, 0)[0]);
            point.setZ(tvec.get(2, 0)[0]);

            orientation.setW(q.getW());
            orientation.setX(q.getX());
            orientation.setY(q.getY());
            orientation.setZ(q.getZ());
            posestamped.getHeader().setFrameId(parameter.cameraFrameName());
            posestamped.setChildFrameId(parameter.markerFrameName());
            posestamped.getHeader().setStamp(connectedNode.getCurrentTime());
            // frame_id too
            tfmessage.getTransforms().add(posestamped);
            tfPublisherCamToMarker.publish(tfmessage);
        }
    });

    // publish Markers
    final Publisher<visualization_msgs.Marker> markerPublisher = connectedNode.newPublisher("markers",
            visualization_msgs.Marker._TYPE);
    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {
            // publish markers every 500ms
            Thread.sleep(500);
            // get marker points from markerConfig, each marker has 4
            // vertices
            List<Point3> points3dlist = markerConfig.getUnordered3DPointList();
            int i = 0;
            for (Point3 p : points3dlist) {
                Marker markermessage = markerPublisher.newMessage();
                // FIXME If the markers are published into an existing frame
                // (e.g. map or odom) the node will consume very high CPU
                // and will fail after a short time. The markers are
                // probably published in the wrong way.
                markermessage.getHeader().setFrameId(parameter.markerFrameName());
                markermessage.setId(i);
                i++;
                markermessage.setType(visualization_msgs.Marker.SPHERE);
                markermessage.setAction(visualization_msgs.Marker.ADD);
                // position
                double x = p.x;
                markermessage.getPose().getPosition().setX(x);
                double y = p.y;
                markermessage.getPose().getPosition().setY(y);
                double z = p.z;
                markermessage.getPose().getPosition().setZ(z);
                // orientation
                markermessage.getPose().getOrientation().setX(0);
                markermessage.getPose().getOrientation().setY(0);
                markermessage.getPose().getOrientation().setZ(0);
                markermessage.getPose().getOrientation().setW(1);
                // patterntSize
                markermessage.getScale().setX(0.1);
                markermessage.getScale().setY(0.1);
                markermessage.getScale().setZ(0.1);
                // color
                markermessage.getColor().setA(1);
                markermessage.getColor().setR(1);
                markermessage.getColor().setG(0);
                markermessage.getColor().setB(0);

                markerPublisher.publish(markermessage);
            }
        }
    });

    // publish tf map --> odom
    final Publisher<tf2_msgs.TFMessage> tfPublisherMapToOdom = connectedNode.newPublisher("tf",
            tf2_msgs.TFMessage._TYPE);
    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {

            // since this is an infinite loop, wait to be notified if new
            // image was processed
            synchronized (tvec) {
                tvec.wait();
            }

            // compute transform map to odom from map to
            // camera_rgb_optical_frame and odom to camera_rgb_optical_frame

            // map to camera_rgb_optical_frame
            Mat tvec_map_cam = new MatOfDouble(1.0, 1.0, 1.0);
            QuaternionHelper q = new QuaternionHelper();
            // get rotation matrix R from solvepnp output rotation vector
            // rvec
            Mat R = new Mat(3, 3, CvType.CV_32FC1);
            Calib3d.Rodrigues(rvec, R);
            // transpose R, because we need the transformation from
            // world(map) to camera
            R = R.t();
            // get rotation around X,Y,Z from R in radiants
            double bankX = Math.atan2(-R.get(1, 2)[0], R.get(1, 1)[0]);
            double headingY = Math.atan2(-R.get(2, 0)[0], R.get(0, 0)[0]);
            double attitudeZ = Math.asin(R.get(1, 0)[0]);
            q.setFromEuler(bankX, headingY, attitudeZ);
            // compute translation vector from world (map) to cam
            // tvec_map_cam
            Core.multiply(R, new Scalar(-1), R); // R=-R
            Core.gemm(R, tvec, 1, new Mat(), 0, tvec_map_cam, 0); // tvec_map_cam=R*tvec

            org.ros.rosjava_geometry.Quaternion rotation = new org.ros.rosjava_geometry.Quaternion(q.getX(),
                    q.getY(), q.getZ(), q.getW());
            double x = tvec_map_cam.get(0, 0)[0];
            double y = tvec_map_cam.get(1, 0)[0];
            double z = tvec_map_cam.get(2, 0)[0];
            // create a Transform Object that hold the transform map to cam
            org.ros.rosjava_geometry.Vector3 translation = new org.ros.rosjava_geometry.Vector3(x, y, z);
            org.ros.rosjava_geometry.Transform transform_map_cam = new org.ros.rosjava_geometry.Transform(
                    translation, rotation);

            // odom to camera_rgb_optical_frame
            GraphName sourceFrame = GraphName.of(parameter.cameraFrameName());
            GraphName targetFrame = GraphName.of("odom");
            org.ros.rosjava_geometry.Transform transform_cam_odom = null;
            if (transformationService.canTransform(targetFrame, sourceFrame)) {
                try {
                    transform_cam_odom = transformationService.lookupTransform(targetFrame, sourceFrame);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to "
                            + "odom! " + "However, " + "will continue..");
                    return;
                }
            } else {
                log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to " + "odom! "
                        + "However, will " + "continue..");
                // cancel this loop..no result can be computed
                return;
            }
            // multiply results
            org.ros.rosjava_geometry.Transform result = org.ros.rosjava_geometry.Transform.identity();
            result = result.multiply(transform_map_cam);
            result = result.multiply(transform_cam_odom);

            // set information to ROS message
            TFMessage tfMessage = tfPublisherMapToOdom.newMessage();
            TransformStamped transformStamped = connectedNode.getTopicMessageFactory()
                    .newFromType(geometry_msgs.TransformStamped._TYPE);
            Transform transform = transformStamped.getTransform();

            Quaternion orientation = transform.getRotation();
            Vector3 vector = transform.getTranslation();
            vector.setX(result.getTranslation().getX());
            vector.setY(result.getTranslation().getY());
            vector.setZ(result.getTranslation().getZ());

            orientation.setW(result.getRotationAndScale().getW());
            orientation.setX(result.getRotationAndScale().getX());
            orientation.setY(result.getRotationAndScale().getY());
            orientation.setZ(result.getRotationAndScale().getZ());
            transformStamped.getHeader().setFrameId("map");
            transformStamped.setChildFrameId("odom");
            transformStamped.getHeader().setStamp(connectedNode.getCurrentTime());
            // frame_id too
            tfMessage.getTransforms().add(transformStamped);
            tfPublisherMapToOdom.publish(tfMessage);
            // System.exit(0);
        }
    });

    // Publish Pose

    final Publisher<geometry_msgs.PoseStamped> posePublisher = connectedNode
            .newPublisher(parameter.poseTopicName(), geometry_msgs.PoseStamped._TYPE);

    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {

            // since this is an infinite loop, wait here to be notified if
            // new image was processed
            synchronized (tvec) {
                tvec.wait();
            }
            final QuaternionHelper q = new QuaternionHelper();

            // convert rotation vector result of solvepnp to rotation matrix
            Mat R = new Mat(3, 3, CvType.CV_32FC1);
            Calib3d.Rodrigues(rvec, R);
            // see publishers before for documentation
            final Mat tvec_map_cam = new MatOfDouble(1.0, 1.0, 1.0);
            R = R.t();
            final double bankX = Math.atan2(-R.get(1, 2)[0], R.get(1, 1)[0]);
            final double headingY = Math.atan2(-R.get(2, 0)[0], R.get(0, 0)[0]);
            final double attitudeZ = Math.asin(R.get(1, 0)[0]);
            q.setFromEuler(bankX, headingY, attitudeZ);
            Core.multiply(R, new Scalar(-1), R);
            Core.gemm(R, tvec, 1, new Mat(), 0, tvec_map_cam, 0);
            final org.ros.rosjava_geometry.Quaternion rotation = new org.ros.rosjava_geometry.Quaternion(
                    q.getX(), q.getY(), q.getZ(), q.getW());
            final double x = tvec_map_cam.get(0, 0)[0];
            final double y = tvec_map_cam.get(1, 0)[0];
            final double z = tvec_map_cam.get(2, 0)[0];

            final org.ros.rosjava_geometry.Vector3 translation = new org.ros.rosjava_geometry.Vector3(x, y, z);
            final org.ros.rosjava_geometry.Transform transform_map_cam = new org.ros.rosjava_geometry.Transform(
                    translation, rotation);

            // odom to camera_rgb_optical_frame
            final GraphName sourceFrame = GraphName.of(parameter.cameraFrameName());
            final GraphName targetFrame = GraphName.of("base_link");
            org.ros.rosjava_geometry.Transform transform_cam_base = null;

            if (transformationService.canTransform(targetFrame, sourceFrame)) {
                try {
                    transform_cam_base = transformationService.lookupTransform(targetFrame, sourceFrame);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to "
                            + "base_link! " + "However, will continue..");
                    // cancel this loop..no result can be computed
                    return;
                }
            } else {
                log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to "
                        + "base_link!" + " However, " + "will continue..");
                // cancel this loop..no result can be computed
                return;
            }

            // multiply results
            org.ros.rosjava_geometry.Transform current_pose = org.ros.rosjava_geometry.Transform.identity();
            current_pose = current_pose.multiply(transform_map_cam);
            current_pose = current_pose.multiply(transform_cam_base);

            // check for plausibility of the pose by checking if movement
            // exceeds max speed (defined) of the robot
            if (parameter.badPoseReject()) {
                Time current_timestamp = connectedNode.getCurrentTime();
                // TODO Unfortunately, we do not have the tf timestamp at
                // hand here. So we can only use the current timestamp.
                double maxspeed = 5;
                boolean goodpose = false;
                // if (current_pose != null && current_timestamp != null) {
                if (last_pose != null && last_timestamp != null) {
                    // check speed of movement between last and current pose
                    double distance = PoseCompare.distance(current_pose, last_pose);
                    double timedelta = PoseCompare.timedelta(current_timestamp, last_timestamp);
                    if ((distance / timedelta) < maxspeed) {
                        if (smoothing) {
                            double xold = last_pose.getTranslation().getX();
                            double yold = last_pose.getTranslation().getY();
                            double zold = last_pose.getTranslation().getZ();
                            double xnew = current_pose.getTranslation().getX();
                            double ynew = current_pose.getTranslation().getY();
                            double znew = current_pose.getTranslation().getZ();
                            final org.ros.rosjava_geometry.Vector3 smoothTranslation = new org.ros.rosjava_geometry.Vector3(
                                    (xold * 2 + xnew) / 3, (yold * 2 + ynew) / 3, (zold * 2 + znew) / 3);
                            current_pose = new org.ros.rosjava_geometry.Transform(smoothTranslation,
                                    current_pose.getRotationAndScale());
                            last_pose = current_pose;
                        }
                        last_pose = current_pose;
                        last_timestamp = current_timestamp;
                        goodpose = true;
                    } else {
                        log.info("distance " + distance + " time: " + timedelta + " --> Pose rejected");
                    }

                } else {
                    last_pose = current_pose;
                    last_timestamp = current_timestamp;
                }
                // }
                // bad pose rejection
                if (!goodpose) {
                    return;
                }
            }

            // set information to message
            geometry_msgs.PoseStamped posestamped = posePublisher.newMessage();
            Pose pose = posestamped.getPose();
            Quaternion orientation = pose.getOrientation();
            Point point = pose.getPosition();

            point.setX(current_pose.getTranslation().getX());

            point.setY(current_pose.getTranslation().getY());

            point.setZ(current_pose.getTranslation().getZ());

            orientation.setW(current_pose.getRotationAndScale().getW());
            orientation.setX(current_pose.getRotationAndScale().getX());
            orientation.setY(current_pose.getRotationAndScale().getY());
            orientation.setZ(current_pose.getRotationAndScale().getZ());

            // frame_id too
            posestamped.getHeader().setFrameId("map");
            posestamped.getHeader().setStamp(connectedNode.getCurrentTime());
            posePublisher.publish(posestamped);

        }
    });

}

From source file:com.ttolley.pongbot.opencv.CvWorker.java

public CvWorker() {
    yPos = new DescriptiveStatistics();
    xPos = new DescriptiveStatistics();
    xPos.setWindowSize(10);/*ww  w. j av a 2  s. c  o m*/
    yPos.setWindowSize(10);

    try {
        // Load the native library.  
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        capture = new VideoCapture(1);

    } catch (Exception ex) {
        System.out.println(ex.getCause().getMessage());
    }

}

From source file:org.tigris.subversion.svnclientadapter.javahl.JhlClientAdapterFactory.java

@SuppressWarnings("rawtypes")
public static boolean isAvailable() {
    if (!availabilityCached) {
        Class c = null;/*from  ww  w .  j a  v  a 2s . c  o  m*/
        try {
            // load a JavaHL class to see if it is found.  Do not use SVNClient as
            // it will try to load native libraries and we do not want that yet
            c = Class.forName("org.apache.subversion.javahl.ClientException");
            if (c == null)
                return false;
        } catch (Throwable t) {
            availabilityCached = true;
            return false;
        }
        // if library is already loaded, it will not be reloaded

        //workaround to solve Subclipse ISSUE #83
        // we will ignore these exceptions to handle scenarios where
        // javaHL was built diffently.  Ultimately, if javaHL fails to load
        // because of a problem in one of these libraries the proper behavior
        // will still occur -- meaning JavaHL adapter is disabled.
        if (isOsWindows()) {

            for (int i = 0; i < WINDOWSLIBS.length; i++) {
                try {
                    System.loadLibrary(WINDOWSLIBS[i]);
                } catch (Exception e) {
                    javaHLErrors.append(e.getMessage()).append("\n");
                } catch (UnsatisfiedLinkError e) {
                    javaHLErrors.append(e.getMessage()).append("\n");
                }
            }

        }
        //workaround to solve Subclipse ISSUE #83
        available = false;
        try {
            /*
             * see if the user has specified the fully qualified path to the native
             * library
             */
            try {
                String specifiedLibraryName = System.getProperty("subversion.native.library");
                if (specifiedLibraryName != null) {
                    System.load(specifiedLibraryName);
                    available = true;
                }
            } catch (UnsatisfiedLinkError ex) {
                javaHLErrors.append(ex.getMessage()).append("\n");
            }
            if (!available) {
                /*
                 * first try to load the library by the new name.
                 * if that fails, try to load the library by the old name.
                 */
                try {
                    System.loadLibrary("libsvnjavahl-1");
                } catch (UnsatisfiedLinkError ex) {
                    javaHLErrors.append(ex.getMessage() + "\n");
                    try {
                        System.loadLibrary("svnjavahl-1");
                    } catch (UnsatisfiedLinkError e) {
                        javaHLErrors.append(e.getMessage()).append("\n");
                        System.loadLibrary("svnjavahl");
                    }
                }

                available = true;
            }
        } catch (Exception e) {
            available = false;
            javaHLErrors.append(e.getMessage()).append("\n");
        } catch (UnsatisfiedLinkError e) {
            available = false;
            javaHLErrors.append(e.getMessage()).append("\n");
        } finally {
            availabilityCached = true;
        }
        if (!available) {
            String libraryPath = System.getProperty("java.library.path");
            if (libraryPath != null)
                javaHLErrors.append("java.library.path = " + libraryPath);
            // System.out.println(javaHLErrors.toString());
        } else {
            // At this point, the library appears to be available, but
            // it could be too old version of JavaHL library.  We have to try
            // to get the version of the library to be sure.
            try {
                ISVNClient svnClient = new SVNClient();
                Version version = svnClient.getVersion();
                if (version.getMajor() == 1 && version.getMinor() == 8)
                    available = true;
                else {
                    available = false;
                    javaHLErrors = new StringBuffer(
                            "Incompatible JavaHL library loaded.  Subversion 1.8.x required.");
                }
            } catch (UnsatisfiedLinkError e) {
                available = false;
                javaHLErrors = new StringBuffer(
                        "Incompatible JavaHL library loaded.  1.8.x or later required.");
            }
        }
    }

    return available;
}