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:com.aipo.aws.ses.SES.java

/**
 * AmazonSimpleEmailService???/*  w ww.ja va2 s .c o  m*/
 * 
 * @return
 */
public static AmazonSimpleEmailService getClient() {
    AWSContext awsContext = AWSContext.get();
    if (awsContext == null) {
        throw new IllegalStateException("AWSContext is not initialized.");
    }
    AmazonSimpleEmailService client = new AmazonSimpleEmailServiceClient(awsContext.getAwsCredentials());
    String endpoint = awsContext.getSesEndpoint();
    if (endpoint != null && endpoint != "") {
        client.setEndpoint(endpoint);
    }
    return client;
}

From source file:Main.java

private static IllegalStateException newIllegalStateException(String charsetName,
        UnsupportedEncodingException e) {
    return new IllegalStateException(charsetName + ": " + e);
}

From source file:Main.java

/**
 * Stores the classes 'static final' field values as a map.
 * /*from   ww  w  .  j  av a2s.c o m*/
 * @param clazz
 *            The class containing static field values.
 * @return A map keyed by static field name to value.
 */
public static Map<String, Object> constantsAsMap(Class<?> clazz) {
    try {
        final Map<String, Object> constants = new HashMap<String, Object>();
        final int staticFinalMods = Modifier.STATIC | Modifier.FINAL;
        for (Field field : clazz.getFields()) {
            if (staticFinalMods == (field.getModifiers() & staticFinalMods)) {
                // this is a constant!
                constants.put(field.getName(), field.get(null));
            }
        }

        return constants;
    } catch (Exception e) {
        // wrap in general error
        throw new IllegalStateException("Unable to initialize class constants for: " + clazz);
    }
}

From source file:Main.java

public static <T> Set<Set<T>> extractSubSets(Set<T> initialSet, int subSetSize) {
    int nbSources = initialSet.size();
    int expectedNumberOfSets = expectedNumberOfSets(nbSources, subSetSize);
    Set<Set<T>> setOfSets = new HashSet<>(expectedNumberOfSets);
    if (nbSources == subSetSize) {
        // Already OK
        setOfSets.add(initialSet);//from ww  w. j  a v a 2s.co  m
        return setOfSets;
    }
    List<T> setAsList = new ArrayList<>(initialSet);
    int[] iterators = new int[subSetSize];
    for (int i = 0; i < iterators.length; i++) {
        iterators[i] = i;
    }
    while (setOfSets.size() != expectedNumberOfSets) {
        HashSet<T> result = new HashSet<>(subSetSize);
        for (int pos : iterators) {
            result.add(setAsList.get(pos));
        }
        if (result.size() != subSetSize) {
            throw new IllegalStateException("Hard!");
        }
        setOfSets.add(result);
        int maxPos = -1;
        for (int i = 0; i < iterators.length; i++) {
            int pos = iterators[i];
            if (pos == (nbSources - iterators.length + i)) {
                maxPos = i;
                break;
            }
        }
        if (maxPos == -1) {
            // Up last iterator
            iterators[iterators.length - 1]++;
        } else if (maxPos == 0) {
            // Finished
            if (setOfSets.size() != expectedNumberOfSets) {
                System.err.println("Something wrong!");
            }
        } else {
            // Up the one before maxPos and reinit the others
            iterators[maxPos - 1]++;
            for (int i = maxPos; i < iterators.length; i++) {
                iterators[i] = iterators[i - 1] + 1;
            }
        }
    }
    return setOfSets;
}

From source file:marytts.tools.analysis.CopySynthesis.java

/**
 * @param args// w  w w .  j  a va 2  s  .  c o m
 */
public static void main(String[] args) throws Exception {
    String wavFilename = null;
    String labFilename = null;
    String pitchFilename = null;
    String textFilename = null;

    String locale = System.getProperty("locale");
    if (locale == null) {
        throw new IllegalArgumentException("No locale given (-Dlocale=...)");
    }

    for (String arg : args) {
        if (arg.endsWith(".txt"))
            textFilename = arg;
        else if (arg.endsWith(".wav"))
            wavFilename = arg;
        else if (arg.endsWith(".ptc"))
            pitchFilename = arg;
        else if (arg.endsWith(".lab"))
            labFilename = arg;
        else
            throw new IllegalArgumentException("Don't know how to treat argument: " + arg);
    }

    // The intonation contour
    double[] contour = null;
    double frameShiftTime = -1;
    if (pitchFilename == null) { // need to create pitch contour from wav file 
        if (wavFilename == null) {
            throw new IllegalArgumentException("Need either a pitch file or a wav file");
        }
        AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename));
        AudioDoubleDataSource audio = new AudioDoubleDataSource(ais);
        PitchFileHeader params = new PitchFileHeader();
        params.fs = (int) ais.getFormat().getSampleRate();
        F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params);
        tracker.pitchAnalyze(audio);
        frameShiftTime = tracker.getSkipSizeInSeconds();
        contour = tracker.getF0Contour();
    } else { // have a pitch file -- ignore any wav file
        PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename);
        if (f0rw.contour == null) {
            throw new NullPointerException("Cannot read f0 contour from " + pitchFilename);
        }
        contour = f0rw.contour;
        frameShiftTime = f0rw.header.skipSizeInSeconds;
    }
    assert contour != null;
    assert frameShiftTime > 0;

    // The ALLOPHONES data and labels
    if (labFilename == null) {
        throw new IllegalArgumentException("No label file given");
    }
    if (textFilename == null) {
        throw new IllegalArgumentException("No text file given");
    }
    MaryTranscriptionAligner aligner = new MaryTranscriptionAligner();
    aligner.SetEnsureInitialBoundary(false);
    String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(),
            aligner.getEnsureInitialBoundary(), labFilename);
    MaryHttpClient mary = new MaryHttpClient();
    String text = FileUtils.readFileToString(new File(textFilename), "ASCII");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(bais);
    aligner.alignXmlTranscriptions(doc, labels);
    assert doc != null;

    // durations
    double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData();
    assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length;

    // Now add durations and f0 targets to document
    double prevEnd = 0;
    NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY);
    for (int i = 0; i < endTimes.length; i++) {
        Element e = (Element) ni.nextNode();
        if (e == null)
            throw new IllegalStateException("More durations than elements -- this should not happen!");
        double durInSeconds = endTimes[i] - prevEnd;
        int durInMillis = (int) (1000 * durInSeconds);
        if (e.getTagName().equals(MaryXML.PHONE)) {
            e.setAttribute("d", String.valueOf(durInMillis));
            e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString());
            // f0 targets at beginning, mid, and end of phone
            StringBuilder f0String = new StringBuilder();
            double startF0 = getF0(contour, frameShiftTime, prevEnd);
            if (startF0 != 0 && !Double.isNaN(startF0)) {
                f0String.append("(0,").append((int) startF0).append(")");
            }
            double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds);
            if (midF0 != 0 && !Double.isNaN(midF0)) {
                f0String.append("(50,").append((int) midF0).append(")");
            }
            double endF0 = getF0(contour, frameShiftTime, endTimes[i]);
            if (endF0 != 0 && !Double.isNaN(endF0)) {
                f0String.append("(100,").append((int) endF0).append(")");
            }
            if (f0String.length() > 0) {
                e.setAttribute("f0", f0String.toString());
            }
        } else { // boundary
            e.setAttribute("duration", String.valueOf(durInMillis));
        }
        prevEnd = endTimes[i];
    }
    if (ni.nextNode() != null) {
        throw new IllegalStateException("More elements than durations -- this should not happen!");
    }

    // TODO: add pitch values

    String acoustparams = DomUtils.document2String(doc);
    System.out.println("ACOUSTPARAMS:");
    System.out.println(acoustparams);
}

From source file:Main.java

public static byte[] toStringBytes(String str, String encoding) {
    if (str == null) {
        return null;
    }/*  ww w  .  j a  v  a2s  .  co  m*/
    try {
        return str.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
        String msg = "The encoding is invalid: encoding=" + encoding + " str=" + str;
        throw new IllegalStateException(msg);
    }
}

From source file:Main.java

private static void assertNotNull(String msg, Object o) {
    if (o == null) {
        throw new IllegalStateException(msg);
    }/*ww w  .  j  a  v a 2  s . c o  m*/
}

From source file:Main.java

/**
 * Ensure Bluetooth is turned on.//from w w  w  .  j  av  a  2s  . co m
 *
 * @throws IllegalStateException If {@code adapter} is null or Bluetooth state is not
 *             {@link BluetoothAdapter#STATE_ON}.
 */
static void checkAdapterStateOn(BluetoothAdapter adapter) {
    if (adapter == null || adapter.getState() != BluetoothAdapter.STATE_ON) {
        throw new IllegalStateException("BT Adapter is not turned ON");
    }
}

From source file:Main.java

public static String stripCDATA(String s) {
    s = s.trim();//from w  w  w  .  j a va 2s. c  o  m
    if (s.startsWith("<![CDATA[")) {
        s = s.substring(9);
        int i = s.indexOf("]]>");
        if (i == -1) {
            throw new IllegalStateException("argument starts with <![CDATA[ but cannot find pairing ]]>");
        }
        s = s.substring(0, i);
    }
    return s;
}

From source file:Main.java

public static String getUserAgent(Context context) {
    PackageInfo packageInfo;/* w w  w .j av  a2s  .c  om*/
    try {
        packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    } catch (NameNotFoundException e) {
        throw new IllegalStateException("getPackageInfo failed");
    }
    return String.format("%s/%s; %s/%s/%s/%s; %s/%s/%s", packageInfo.packageName, packageInfo.versionName,
            Build.BRAND, Build.DEVICE, Build.MODEL, Build.ID, Build.VERSION.SDK_INT, Build.VERSION.RELEASE,
            Build.VERSION.INCREMENTAL);
}