Example usage for java.lang IllegalStateException IllegalStateException

List of usage examples for java.lang IllegalStateException IllegalStateException

Introduction

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

Prototype

public IllegalStateException(Throwable cause) 

Source Link

Document

Constructs a new exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:cpcc.vvrte.services.task.AcoTspSimple.java

/**
 * @param costMatrix the cost matrix.//  www. j av a  2 s  .c  om
 * @param maxIterations the maximum number of iterations
 * @param boost the boost value.
 * @return the best path as a list of integers.
 */
public static List<Integer> calculateBestPath(double[][] costMatrix, int maxIterations, int boost) {
    if (costMatrix.length == 0 || costMatrix.length != costMatrix[0].length) {
        throw new IllegalStateException("Cost matrix heigth and width must be equal!");
    }

    double[][] pheromoneTrails = new double[costMatrix.length][costMatrix.length];

    for (int k = 0, l = costMatrix.length; k < l; ++k) {
        for (int j = 0; j < l; ++j) {
            pheromoneTrails[k][j] = 0;
        }
    }

    double bestLen = Double.POSITIVE_INFINITY;
    List<Integer> bestPath = new ArrayList<Integer>();

    for (int iteration = 0; iteration < maxIterations; iteration++) {
        List<Integer> path = generatePath(costMatrix, pheromoneTrails);
        double pathLen = realPathLength(costMatrix, path);

        if (pathLen < bestLen) {
            updatePheromoneTrails(pheromoneTrails, path, boost);
            bestLen = pathLen;
            bestPath = path;
        }

        evaporatePheromoneTrails(pheromoneTrails, (double) boost / (double) maxIterations);
    }

    return bestPath;
}

From source file:Main.java

public static String getStringFromDocument(Document doc) {
    DOMSource domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;// ww w .  j a  va 2s. c o m
    try {
        transformer = tf.newTransformer();
        transformer.transform(domSource, result);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    return writer.toString();
}

From source file:org.nuclos.common.tls.CustomSecureProtocolSocketFactory.java

private static SSLContext createCustomSSLContext() {
    try {/*from  w  w w .  jav a2s.c om*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new CustomX509TrustManager(null) }, null);
        return context;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new IllegalStateException(e);
    }
}

From source file:net.orfjackal.dimdwarf.testutils.Sandbox.java

public File createTempDir() {
    int counter = 0;
    File dir;/*ww w  . j  ava  2  s.c om*/
    do {
        counter++;
        dir = new File(sandboxDir, "temp_" + timestamp() + "_" + counter);
    } while (!dir.mkdir() && counter < SAFETY_LIMIT);

    if (!dir.isDirectory()) {
        throw new IllegalStateException("Unable to create directory: " + dir.getAbsolutePath());
    }
    return dir;
}

From source file:com.btkelly.gnag.utils.ViolationFormatter.java

/**
 * Use this method to create a formatted HTML string representing a violation that will be posted as an inline 
 * comment. Only intended for use when posting inline comments to GitHub.
 *///  w  w  w .j  a  v  a  2 s  . c  o  m
public static String getHtmlStringForInlineComment(@NotNull final Violation violation) {
    final Integer violationFileLineNumber = violation.getFileLineNumber();
    final String violationRelativeFilePath = violation.getRelativeFilePath();

    if (violationFileLineNumber == null || violationRelativeFilePath == null) {
        throw new IllegalStateException(
                "Should only call getHtmlStringForInlineViolationComment when violation location is known");
    }

    final HtmlStringBuilder builder = new HtmlStringBuilder();

    appendViolationReporterToBuilder(violation, builder);
    appendViolationNameToBuilder(violation, builder);
    appendViolationCommentToBuilderIfPresent(violation, builder);

    return builder.toString();
}

From source file:com.fusesource.examples.horo.model.StarSign.java

public static StarSign getInstance(String name) {
    Validate.notEmpty(name, "name is empty");
    StarSign starSign = null;//from   w w w .  j  a  v  a2 s .c o  m
    for (StarSign temp : values()) {
        if (temp.getName().toLowerCase().equals(name.toLowerCase())) {
            starSign = temp;
            break;
        }
    }
    if (starSign == null) {
        throw new IllegalStateException("Unable to find star sign for " + name);
    }
    return starSign;
}

From source file:Main.java

/**
 * Finds the most optimal size. The optimal size is when possible the same as
 * the camera resolution, if not is is it the best size between the camera solution and
 * MIN_SIZE_PIXELS/*from w  w w  .j  a v  a 2s.com*/
 * @param screenResolution
 * @param rawSupportedSizes
 *@param defaultCameraSize @return optimal preview size
 */
private static Point findBestSizeValue(Point screenResolution, List<Camera.Size> rawSupportedSizes,
        Camera.Size defaultCameraSize) {

    if (rawSupportedSizes == null) {
        Log.w(TAG, "Device returned no supported sizes; using default");
        if (defaultCameraSize == null) {
            throw new IllegalStateException("Parameters contained no size!");
        }
        return new Point(defaultCameraSize.width, defaultCameraSize.height);
    }

    // Sort by size, descending
    List<Camera.Size> supportedSizes = new ArrayList<>(rawSupportedSizes);
    Collections.sort(supportedSizes, new Comparator<Camera.Size>() {
        @Override
        public int compare(Camera.Size a, Camera.Size b) {
            int aPixels = a.height * a.width;
            int bPixels = b.height * b.width;
            if (bPixels > aPixels) {
                return -1;
            }
            if (bPixels < aPixels) {
                return 1;
            }
            return 0;
        }
    });

    if (Log.isLoggable(TAG, Log.INFO)) {
        StringBuilder sizesString = new StringBuilder();
        for (Camera.Size supportedSize : supportedSizes) {
            sizesString.append(supportedSize.width).append('x').append(supportedSize.height).append(' ');
        }
        Log.i(TAG, "Supported sizes: " + sizesString);
    }

    double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;

    // Remove sizes that are unsuitable
    Iterator<Camera.Size> it = supportedSizes.iterator();
    while (it.hasNext()) {
        Camera.Size supportedSize = it.next();
        int realWidth = supportedSize.width;
        int realHeight = supportedSize.height;
        if (realWidth * realHeight < MIN_SIZE_PIXELS) {
            it.remove();
            continue;
        }

        boolean isCandidatePortrait = realWidth < realHeight;
        int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
        int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
        double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight;
        double distortion = Math.abs(aspectRatio - screenAspectRatio);
        if (distortion > MAX_ASPECT_DISTORTION) {
            it.remove();
            continue;
        }

        if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) {
            Point exactPoint = new Point(realWidth, realHeight);
            Log.i(TAG, "Found size exactly matching screen size: " + exactPoint);
            return exactPoint;
        }
    }

    // If no exact match, use largest size. This was not a great idea on older devices because
    // of the additional computation needed. We're likely to get here on newer Android 4+ devices, where
    // the CPU is much more powerful.
    if (!supportedSizes.isEmpty()) {
        Camera.Size largestCameraSizes = supportedSizes.get(0);
        Point largestSize = new Point(largestCameraSizes.width, largestCameraSizes.height);
        Log.i(TAG, "Using largest suitable size: " + largestSize);
        return largestSize;
    }

    // If there is nothing at all suitable, return current size
    if (defaultCameraSize == null) {
        throw new IllegalStateException("Parameters contained no size!");
    }
    Point defaultSize = new Point(defaultCameraSize.width, defaultCameraSize.height);
    Log.i(TAG, "No suitable sizes, using default: " + defaultSize);

    return defaultSize;
}

From source file:me.ineson.testing.utils.GradleConfig.java

private static synchronized String readGradleConfig(String key) {
    if (GRADLE_PROPERTIES == null) {
        File filename = new File(SystemUtils.getUserHome(), ".gradle/gradle.properties");
        if (!filename.exists() || !filename.isFile() || !filename.canRead()) {
            throw new IllegalStateException("Failed to access gradle configuration: "
                    + filename.getAbsolutePath() + ", exists " + filename.exists() + ", isFile "
                    + filename.isFile() + ", canRead " + filename.canRead());
        }/*from  w w w. j  a v  a  2  s. c o  m*/
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(
                    "Failed to access gradle configuration: " + filename.getAbsolutePath(), e);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Failed to access gradle configuration: " + filename.getAbsolutePath(), e);
        }
        GRADLE_PROPERTIES = properties;
    }

    String fullKey = "systemProp." + key;
    String value = GRADLE_PROPERTIES.getProperty(fullKey);

    if (value != null) {
        System.setProperty(key, value);
    }

    return value;
}

From source file:com.jkoolcloud.tnt4j.streams.sample.custom.SampleIntegration.java

/**
 * Configure streams and parsers, and run each stream in its own thread.
 *
 * @param cfgFileName/*from   w ww  .  ja v  a 2  s. c o  m*/
 *            configuration file name
 */
public static void loadConfigAndRun(String cfgFileName) {
    try {
        StreamsConfigLoader cfg = StringUtils.isEmpty(cfgFileName) ? new StreamsConfigLoader()
                : new StreamsConfigLoader(cfgFileName);
        Collection<TNTInputStream<?, ?>> streams = cfg.getStreams();
        if (streams == null || streams.isEmpty()) {
            throw new IllegalStateException("No Activity Streams found in configuration"); // NON-NLS
        }

        ThreadGroup streamThreads = new ThreadGroup("Streams"); // NON-NLS
        StreamThread ft;
        for (TNTInputStream<?, ?> stream : streams) {
            ft = new StreamThread(streamThreads, stream,
                    String.format("%s:%s", stream.getClass().getSimpleName(), stream.getName())); // NON-NLS
            ft.start();
        }
    } catch (Exception e) {
        LOGGER.log(OpLevel.ERROR, String.valueOf(e.getLocalizedMessage()), e);
    }
}

From source file:me.aerovulpe.crawler.data.SimpleDiskCache.java

public static synchronized SimpleDiskCache open(File dir, int appVersion, long maxSize) throws IOException {
    if (usedDirs.contains(dir)) {
        throw new IllegalStateException("Cache dir " + dir.getAbsolutePath() + " was used before.");
    }//from www.ja  v a 2  s  .  c om
    usedDirs.add(dir);
    return new SimpleDiskCache(dir, appVersion, maxSize);
}