Example usage for java.util Random nextFloat

List of usage examples for java.util Random nextFloat

Introduction

In this page you can find the example usage for java.util Random nextFloat.

Prototype

public float nextFloat() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.

Usage

From source file:org.zaproxy.zap.extension.ascanrulesBeta.ExpressionLanguageInjectionPlugin.java

/**
 * Scan for Expression Language Injection Vulnerabilites
 *
 * @param msg a request only copy of the original message (the response isn't copied)
 * @param paramName the parameter name that need to be exploited
 * @param value the original parameter value
 *//* w w  w .  j a  v a 2s.c  o  m*/
@Override
public void scan(HttpMessage msg, String paramName, String value) {

    String originalContent = getBaseMsg().getResponseBody().toString();
    Random rand = new Random();
    String addedString;
    int bignum1;
    int bignum2;
    int tries = 0;

    do {
        bignum1 = MEAN_VALUE + (int) (rand.nextFloat() * (DEVIATION_VALUE - MEAN_VALUE + 1));
        bignum2 = MEAN_VALUE + (int) (rand.nextFloat() * (DEVIATION_VALUE - MEAN_VALUE + 1));
        addedString = String.valueOf(bignum1 + bignum2);
        tries++;

    } while (originalContent.contains(addedString) && (tries < MAX_NUM_TRIES));

    // Build the evil payload ${100146+99273}
    String payload = "${" + bignum1 + "+" + bignum2 + "}";

    try {
        // Set the expression value
        setParameter(msg, paramName, payload);
        try {
            // Send the request and retrieve the response
            sendAndReceive(msg);
        } catch (InvalidRedirectLocationException | URIException | UnknownHostException
                | IllegalArgumentException ex) {
            if (log.isDebugEnabled())
                log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                        + msg.getRequestHeader().getURI().toString()
                        + "\n The target may have replied with a poorly formed redirect due to our input.");
            return;
        }
        // Check if the resulting content contains the executed addition
        if (msg.getResponseBody().toString().contains(addedString)) {
            // We Found IT!
            // First do logging
            log.debug("[Expression Langage Injection Found] on parameter [" + paramName + "]  with payload ["
                    + payload + "]");

            // Now create the alert message
            this.bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, msg.getRequestHeader().getURI().toString(),
                    paramName, payload, null, addedString, msg);
        }

    } catch (IOException ex) {
        // Do not try to internationalise this.. we need an error message in any event..
        // if it's in English, it's still better than not having it at all.
        log.error("Expression Language Injection vulnerability check failed for parameter [" + paramName
                + "] and payload [" + payload + "] due to an I/O error", ex);
    }
}

From source file:com.orange.cepheus.cep.EsperEventProcessorTest.java

private void sendXtemperature() {
    Random random = new Random(15);
    for (int i = 1; i < 100; i++) {
        try {/*from   w  w  w .j  ava 2 s  . c  om*/
            esperEventProcessor.processEvent(buildBasicEvent((double) (15.5 + random.nextFloat())));
        } catch (EventProcessingException e) {
            Assert.fail("Not expected EventProcessingException");
        }
    }
}

From source file:com.github.chrisbanes.photoview.sample.SimpleSampleActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Simple Sample");
    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override// ww  w. j  a va2 s  .c o m
        public void onClick(View v) {
            onBackPressed();
        }
    });
    toolbar.inflateMenu(R.menu.main_menu);
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.menu_zoom_toggle:
                mPhotoView.setZoomable(!mPhotoView.isZoomEnabled());
                item.setTitle(
                        mPhotoView.isZoomEnabled() ? R.string.menu_zoom_disable : R.string.menu_zoom_enable);
                return true;

            case R.id.menu_scale_fit_center:
                mPhotoView.setScaleType(ImageView.ScaleType.CENTER);
                return true;

            case R.id.menu_scale_fit_start:
                mPhotoView.setScaleType(ImageView.ScaleType.FIT_START);
                return true;

            case R.id.menu_scale_fit_end:
                mPhotoView.setScaleType(ImageView.ScaleType.FIT_END);
                return true;

            case R.id.menu_scale_fit_xy:
                mPhotoView.setScaleType(ImageView.ScaleType.FIT_XY);
                return true;

            case R.id.menu_scale_scale_center:
                mPhotoView.setScaleType(ImageView.ScaleType.CENTER);
                return true;

            case R.id.menu_scale_scale_center_crop:
                mPhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                return true;

            case R.id.menu_scale_scale_center_inside:
                mPhotoView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                return true;

            case R.id.menu_scale_random_animate:
            case R.id.menu_scale_random:
                Random r = new Random();

                float minScale = mPhotoView.getMinimumScale();
                float maxScale = mPhotoView.getMaximumScale();
                float randomScale = minScale + (r.nextFloat() * (maxScale - minScale));
                mPhotoView.setScale(randomScale, item.getItemId() == R.id.menu_scale_random_animate);

                showToast(String.format(SCALE_TOAST_STRING, randomScale));

                return true;
            case R.id.menu_matrix_restore:
                if (mCurrentDisplayMatrix == null)
                    showToast("You need to capture display matrix first");
                else
                    mPhotoView.setDisplayMatrix(mCurrentDisplayMatrix);
                return true;
            case R.id.menu_matrix_capture:
                mCurrentDisplayMatrix = new Matrix();
                mPhotoView.getDisplayMatrix(mCurrentDisplayMatrix);
                return true;
            }
            return false;
        }
    });
    mPhotoView = (PhotoView) findViewById(R.id.iv_photo);
    mCurrMatrixTv = (TextView) findViewById(R.id.tv_current_matrix);

    Drawable bitmap = ContextCompat.getDrawable(this, R.drawable.wallpaper);
    mPhotoView.setImageDrawable(bitmap);

    // Lets attach some listeners, not required though!
    mPhotoView.setOnMatrixChangeListener(new MatrixChangeListener());
    mPhotoView.setOnPhotoTapListener(new PhotoTapListener());
    mPhotoView.setOnSingleFlingListener(new SingleFlingListener());
}

From source file:uk.co.senab.photoview.sample.SimpleSampleActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_zoom_toggle:
        mAttacher.setZoomable(!mAttacher.canZoom());
        return true;

    case R.id.menu_scale_fit_center:
        mAttacher.setScaleType(ScaleType.FIT_CENTER);
        return true;

    case R.id.menu_scale_fit_start:
        mAttacher.setScaleType(ScaleType.FIT_START);
        return true;

    case R.id.menu_scale_fit_end:
        mAttacher.setScaleType(ScaleType.FIT_END);
        return true;

    case R.id.menu_scale_fit_xy:
        mAttacher.setScaleType(ScaleType.FIT_XY);
        return true;

    case R.id.menu_scale_scale_center:
        mAttacher.setScaleType(ScaleType.CENTER);
        return true;

    case R.id.menu_scale_scale_center_crop:
        mAttacher.setScaleType(ScaleType.CENTER_CROP);
        return true;

    case R.id.menu_scale_scale_center_inside:
        mAttacher.setScaleType(ScaleType.CENTER_INSIDE);
        return true;

    case R.id.menu_scale_random_animate:
    case R.id.menu_scale_random:
        Random r = new Random();

        float minScale = mAttacher.getMinimumScale();
        float maxScale = mAttacher.getMaximumScale();
        float randomScale = minScale + (r.nextFloat() * (maxScale - minScale));
        mAttacher.setScale(randomScale, item.getItemId() == R.id.menu_scale_random_animate);

        showToast(String.format(SCALE_TOAST_STRING, randomScale));

        return true;
    case R.id.menu_matrix_restore:
        if (mCurrentDisplayMatrix == null)
            showToast("You need to capture display matrix first");
        else// www.  j a v a 2s. c  om
            mAttacher.setDisplayMatrix(mCurrentDisplayMatrix);
        return true;
    case R.id.menu_matrix_capture:
        mAttacher.getDisplayMatrix(mCurrentDisplayMatrix);
        return true;
    case R.id.extract_visible_bitmap:
        try {
            Bitmap bmp = mAttacher.getVisibleRectangleBitmap();
            File tmpFile = File.createTempFile("photoview", ".png",
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            FileOutputStream out = new FileOutputStream(tmpFile);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/png");
            share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tmpFile));
            startActivity(share);
            Toast.makeText(this, String.format("Extracted into: %s", tmpFile.getAbsolutePath()),
                    Toast.LENGTH_SHORT).show();
        } catch (Throwable t) {
            t.printStackTrace();
            Toast.makeText(this, "Error occured while extracting bitmap", Toast.LENGTH_SHORT).show();
        }
        return true;
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.tafayor.selfcamerashot.camera.CameraMenu.java

private Action buildAdsAction(int id, int resId) {

    int tintColor;
    Random r = new Random();
    float h = r.nextFloat() * 365;
    float s = 0.9f;
    float l = 0.8f;
    tintColor = ColorUtils.HSLToColor(new float[] { h, s, l });
    final int glowColor = mContext.getResources().getColor(R.color.camera_btn_glowColor);
    Bitmap bmp;//from ww  w  . j  a  v a2s.c om
    Drawable icon;

    bmp = BitmapFactory.decodeResource(mContext.getResources(), resId);
    Drawable drawable = new BitmapDrawable(mContext.getResources(), bmp);
    icon = Util.tint(drawable, tintColor);

    bmp = GraphicsHelper.drawableToBitmap(icon);
    bmp = GraphicsHelper.addGlow(bmp, glowColor);
    icon = new BitmapDrawable(mContext.getResources(), bmp);

    return new Action(id, icon);
}

From source file:org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource.java

public static Object randomObject(int column, Random r, PrimitiveCategory[] primitiveCategories,
        PrimitiveTypeInfo[] primitiveTypeInfos, String[] alphabets, boolean addEscapables,
        String needsEscapeStr) {//from www  . j a va2s  .c  o  m
    PrimitiveCategory primitiveCategory = primitiveCategories[column];
    PrimitiveTypeInfo primitiveTypeInfo = primitiveTypeInfos[column];
    try {
        switch (primitiveCategory) {
        case BOOLEAN:
            return Boolean.valueOf(r.nextInt(1) == 1);
        case BYTE:
            return Byte.valueOf((byte) r.nextInt());
        case SHORT:
            return Short.valueOf((short) r.nextInt());
        case INT:
            return Integer.valueOf(r.nextInt());
        case LONG:
            return Long.valueOf(r.nextLong());
        case DATE:
            return RandomTypeUtil.getRandDate(r);
        case FLOAT:
            return Float.valueOf(r.nextFloat() * 10 - 5);
        case DOUBLE:
            return Double.valueOf(r.nextDouble() * 10 - 5);
        case STRING:
        case CHAR:
        case VARCHAR: {
            String result;
            if (alphabets != null && alphabets[column] != null) {
                result = RandomTypeUtil.getRandString(r, alphabets[column], r.nextInt(10));
            } else {
                result = RandomTypeUtil.getRandString(r);
            }
            if (addEscapables && result.length() > 0) {
                int escapeCount = 1 + r.nextInt(2);
                for (int i = 0; i < escapeCount; i++) {
                    int index = r.nextInt(result.length());
                    String begin = result.substring(0, index);
                    String end = result.substring(index);
                    Character needsEscapeChar = needsEscapeStr.charAt(r.nextInt(needsEscapeStr.length()));
                    result = begin + needsEscapeChar + end;
                }
            }
            switch (primitiveCategory) {
            case STRING:
                return result;
            case CHAR:
                return new HiveChar(result, ((CharTypeInfo) primitiveTypeInfo).getLength());
            case VARCHAR:
                return new HiveChar(result, ((VarcharTypeInfo) primitiveTypeInfo).getLength());
            default:
                throw new Error("Unknown primitive category " + primitiveCategory);
            }
        }
        case BINARY:
            return getRandBinary(r, 1 + r.nextInt(100));
        case TIMESTAMP:
            return RandomTypeUtil.getRandTimestamp(r);
        case INTERVAL_YEAR_MONTH:
            return getRandIntervalYearMonth(r);
        case INTERVAL_DAY_TIME:
            return getRandIntervalDayTime(r);
        case DECIMAL:
            return getRandHiveDecimal(r, (DecimalTypeInfo) primitiveTypeInfo);
        default:
            throw new Error("Unknown primitive category " + primitiveCategory);
        }
    } catch (Exception e) {
        throw new RuntimeException("randomObject failed on column " + column + " type " + primitiveCategory, e);
    }
}

From source file:org.jtransforms.utils.IOUtils.java

/**
 * Fills 1D matrix with random numbers./*from   w w w. j ava  2s. c o  m*/
* @param N  size
* @param m  1D matrix
*/
public static void fillMatrix_1D(long N, float[] m) {
    Random r = new Random(2);
    for (int i = 0; i < N; i++) {
        m[i] = r.nextFloat();
    }
}

From source file:com.samanamp.algorithms.RandomSelectionAlgorithm.java

public void runAlgoAndSimulation(int maxCost, int maxTime, int runs) {
    this.maxCost = maxCost;
    this.maxTime = maxTime;
    this.runs = runs;

    Random randomGen = new Random();
    randomGen.setSeed(System.currentTimeMillis());

    Node[] nodes = graph.vertexSet().toArray(new Node[graph.vertexSet().size()]);
    LinkedList<Node> selectedNodes = new LinkedList<Node>();
    Node tmpNode;/* ww  w.  ja va 2  s. com*/
    int arraySize = nodes.length;
    for (int currentCost = 0; currentCost < maxCost;) {
        tmpNode = nodes[((int) (randomGen.nextFloat() * arraySize))];
        if (tmpNode.cost + currentCost <= maxCost) {
            selectedNodes.add(tmpNode);
            currentCost += tmpNode.cost;
        }
    }
    System.out.println("#nodes selected: " + selectedNodes.size());
    runSimulation(selectedNodes);
}

From source file:org.jtransforms.utils.IOUtils.java

/**
 * Fills 1D matrix with random numbers./*from  ww  w  .  ja v a 2  s.  co m*/
* @param N  size
* @param m  1D matrix
*/
public static void fillMatrix_1D(long N, FloatLargeArray m) {
    Random r = new Random(2);
    for (long i = 0; i < N; i++) {
        m.setDouble(i, r.nextFloat());
    }
}

From source file:com.turt2live.xmail.mail.attachment.ItemAttachment.java

@Override
public void onGive(XMailEntity to, Mail mail) {
    if (to instanceof XMailPlayer && item.getType() == XMail.EXPLOSIVE_MATERIAL
            && item.getDurability() == XMail.EXPLOSIVE_DATA_VALUE) {
        int explosive = item.getAmount();
        int explosionSize = explosive > 16 ? 16 : explosive;
        if (explosionSize > 0) {
            Player target = (Player) to.getOwner();
            Location loc = target.getLocation();
            target.getWorld().createExplosion(loc.getX(), loc.getY(), loc.getZ(), explosionSize * 2, false,
                    false);/* w w  w. ja v a2  s  .  c  om*/
            Random random = new Random(System.currentTimeMillis());
            for (int i = 0; i < 50; i++) {
                target.playSound(loc, Sound.GHAST_SCREAM, 1.0f,
                        (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F);
            }
        }
    }
}