/** * Loads the grid in memory. * * <p>If file cannot be loaded, the cause is logged at {@link Level#SEVERE severe level}. * * @param location the NTv2 file absolute path * @return the grid, or {@code null} on error * @throws FactoryException */ private GridShiftFile loadNTv2Grid(URL location) throws FactoryException { InputStream in = null; try { GridShiftFile grid = new GridShiftFile(); in = new BufferedInputStream(location.openStream()); grid.loadGridShiftFile(in, false); // Load full grid in memory in.close(); return grid; } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); return null; } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); return null; } catch (IllegalArgumentException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); throw new FactoryException(e.getLocalizedMessage(), e); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { // never mind } } }
/** * Test whether an XPath is valid. It seems the Xalan has no easy way to check, so this creates a * dummy test document, then tries to evaluate the xpath against it. * * @param xpathString XPath String to validate * @param showDialog weather to show a dialog * @return returns true if valid, valse otherwise. */ public static boolean validXPath(String xpathString, boolean showDialog) { String ret = null; boolean success = true; Document testDoc = null; try { testDoc = XPathUtil.makeDocumentBuilder(false, false, false, false).newDocument(); Element el = testDoc.createElement("root"); // $NON-NLS-1$ testDoc.appendChild(el); XPathUtil.validateXPath(testDoc, xpathString); } catch (IllegalArgumentException e) { log.warn(e.getLocalizedMessage()); success = false; ret = e.getLocalizedMessage(); } catch (ParserConfigurationException e) { success = false; ret = e.getLocalizedMessage(); } catch (TransformerException e) { success = false; ret = e.getLocalizedMessage(); } if (showDialog) { JOptionPane.showMessageDialog( null, (success) ? JMeterUtils.getResString("xpath_assertion_valid") : ret, // $NON-NLS-1$ (success) ? JMeterUtils.getResString("xpath_assertion_valid") : JMeterUtils //$NON-NLS-1$ .getResString("xpath_assertion_failed"), (success) ? JOptionPane.INFORMATION_MESSAGE // $NON-NLS-1$ : JOptionPane.ERROR_MESSAGE); } return success; }
@ExceptionHandler(IllegalArgumentException.class) ResponseEntity<String> sendBadRequestException(IllegalArgumentException ex) { LOGGER.warn( "Exception was thrown, with cause " + ex.getCause() + "\nMessage: " + ex.getLocalizedMessage(), ex); return new ResponseEntity<>(ex.getLocalizedMessage(), HttpStatus.BAD_REQUEST); }
protected BufferedImage getWindowedImage(ImageListViewCell displayedCell) { BufferedImage windowedImage = tryWindowRawImage(displayedCell); if (windowedImage != null) { return windowedImage; } else { // TODO: caching of windowed images, probably using // displayedCell.getDisplayedModelElement().getImageKey() and the windowing parameters // as the cache key BufferedImage srcImg = displayedCell.getDisplayedModelElement().getImage().getBufferedImage(); // TODO: use the model element's RawImage instead of the BufferedImage when possible /// * if (srcImg.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY) { try { windowedImage = windowMonochrome( displayedCell, srcImg, displayedCell.getWindowLocation(), displayedCell.getWindowWidth()); } catch (IllegalArgumentException e) { // TODO: store message somehow so ILVInitStateController can render it // either into ILVModelElt#errorInfo (in which case errorInfo would be a warning for // initialized elements), // or, probably better, into a new attribute in the cell logger.warn("couldn't window grayscale image: " + e.getLocalizedMessage() /*, e*/); return srcImg; } } else if (srcImg.getColorModel().getColorSpace().isCS_sRGB()) { try { windowedImage = windowRGB(srcImg, displayedCell.getWindowLocation(), displayedCell.getWindowWidth()); } catch (IllegalArgumentException e) { // TODO: store message somehow so ILVInitStateController can render it (see // windowMonochrome above) logger.warn("couldn't window RGB image: " + e.getLocalizedMessage() /*, e*/); return srcImg; } } else { throw new IllegalStateException( "don't know how to window image with color space " + srcImg.getColorModel().getColorSpace()); // TODO: do something cleverer here? Like, create windowedImage // with a color space that's "compatible" to srcImg (using // some createCompatibleImage() method in BufferedImage or elsewhere), // window all bands of that, and let the JRE figure out how to draw the result? } // */ // windowedImage = windowWithRasterOp(srcImg, windowLocation, windowWidth); // windowedImage = srcImg; return windowedImage; } }
/** * This method creates the constraint instance. * * @param constraintStructure the constraint's structure (bConstraint clss in blender 2.49). * @param ownerOMA the old memory address of the constraint's owner * @param influenceIpo the ipo curve of the influence factor * @param blenderContext the blender context * @throws BlenderFileException this exception is thrown when the blender file is somehow * corrupted */ protected Constraint createConstraint( Structure constraintStructure, Long ownerOMA, Ipo influenceIpo, BlenderContext blenderContext) throws BlenderFileException { String constraintClassName = this.getConstraintClassName(constraintStructure, blenderContext); Class<? extends Constraint> constraintClass = constraintClasses.get(constraintClassName); if (constraintClass != null) { try { return (Constraint) constraintClass.getDeclaredConstructors()[0].newInstance( constraintStructure, ownerOMA, influenceIpo, blenderContext); } catch (IllegalArgumentException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (SecurityException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (InstantiationException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (IllegalAccessException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (InvocationTargetException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } } else { throw new BlenderFileException("Unknown constraint type: " + constraintClassName); } }
@SuppressWarnings("deprecation") public static List<ObjectIdentifier> processSubObjectIdentifiers( List<us.kbase.workspace.SubObjectIdentity> subObjectIds) { final List<ObjectIdentifier> objs = new LinkedList<ObjectIdentifier>(); int objcount = 1; for (final us.kbase.workspace.SubObjectIdentity soi : subObjectIds) { final ObjectIdentifier oi; try { oi = processObjectIdentifier( new ObjectIdentity() .withWorkspace(soi.getWorkspace()) .withWsid(soi.getWsid()) .withName(soi.getName()) .withObjid(soi.getObjid()) .withVer(soi.getVer()) .withRef(soi.getRef())); checkAddlArgs(soi.getAdditionalProperties(), soi.getClass()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Error on SubObjectIdentity #" + objcount + ": " + e.getLocalizedMessage(), e); } SubsetSelection paths = new SubsetSelection( soi.getIncluded(), longToBoolean(soi.getStrictMaps(), SubsetSelection.STRICT_MAPS_DEFAULT), longToBoolean(soi.getStrictArrays(), SubsetSelection.STRICT_ARRAYS_DEFAULT)); objs.add(new ObjIDWithRefPathAndSubset(oi, null, paths)); objcount++; } return objs; }
/** * Program entry point. * * @param args program arguments */ public static void main(String[] args) { try { // configure Orekit Autoconfiguration.configureOrekit(); // input/out File input = new File(VisibilityCircle.class.getResource("/visibility-circle.in").toURI().getPath()); File output = new File(input.getParentFile(), "visibility-circle.csv"); new VisibilityCircle().run(input, output, ","); System.out.println("visibility circle saved as file " + output); } catch (URISyntaxException use) { System.err.println(use.getLocalizedMessage()); System.exit(1); } catch (IOException ioe) { System.err.println(ioe.getLocalizedMessage()); System.exit(1); } catch (IllegalArgumentException iae) { System.err.println(iae.getLocalizedMessage()); System.exit(1); } catch (OrekitException oe) { System.err.println(oe.getLocalizedMessage()); System.exit(1); } }
/** * Creates a string explaining why this is not a legitimate OpenDJ installation. Null if this is * in fact a valid installation. * * @return localized message indicating the reason this is not an OpenDJ installation */ public String getInvalidityReason() { try { validateRootDirectory(rootDirectory); return null; } catch (IllegalArgumentException e) { return e.getLocalizedMessage(); } }
@Test public void testGetCustomVariableIntegerLessThan1() { try { cvl.get(0); fail("Exception should have been throw."); } catch (IllegalArgumentException e) { assertEquals("Index must be greater than 0.", e.getLocalizedMessage()); } }
@Test public void testAddCustomVariableIndexLessThan1() { try { cvl.add(new CustomVariable("a", "b"), 0); fail("Exception should have been throw."); } catch (IllegalArgumentException e) { assertEquals("Index must be greater than 0.", e.getLocalizedMessage()); } }
public Resolution split() throws JSONException { JSONObject json = new JSONObject(); json.put("success", Boolean.FALSE); String error = null; if (appLayer == null) { error = "Invalid parameters"; } else if (unauthorized) { error = "Not authorized"; } else { FeatureSource fs = null; try { if (this.splitFeatureFID == null) { throw new IllegalArgumentException("Split feature ID is null"); } if (this.toSplitWithFeature == null) { throw new IllegalArgumentException("Split line is null"); } fs = this.layer.getFeatureType().openGeoToolsFeatureSource(); if (!(fs instanceof SimpleFeatureStore)) { throw new IllegalArgumentException("Feature source does not support editing"); } this.store = (SimpleFeatureStore) fs; List<FeatureId> ids = this.splitFeature(); if (ids.size() < 2) { throw new IllegalArgumentException("Split failed, check that geometries overlap"); } json.put("fids", ids); json.put("success", Boolean.TRUE); } catch (IllegalArgumentException e) { log.warn("Split error", e); error = e.getLocalizedMessage(); } catch (Exception e) { log.error(String.format("Exception splitting feature %s", this.splitFeatureFID), e); error = e.toString(); if (e.getCause() != null) { error += "; cause: " + e.getCause().toString(); } } finally { if (fs != null) { fs.getDataStore().dispose(); } } } if (error != null) { json.put("error", error); } return new StreamingResolution("application/json", new StringReader(json.toString())); }
/** Verifies that an NDArray will not allow bad/dangerous constructor args. */ public void testNDArraySafety() { float[][] f = new float[15][]; int[] dims = new int[] {15, 20}; try { NDArray<float[][]> ndarray = new NDArray<float[][]>(f, dims); ndarray.getDimensions(); throw new AssertionError("NDArray should have failed instantiation"); } catch (IllegalArgumentException e) { assert e.getLocalizedMessage() != null; // System.out.println("NDArray blocked bad type args"); } float[] d = new float[200]; try { NDArray<float[]> ndarray = new NDArray<float[]>(d, dims); ndarray.getDimensions(); throw new AssertionError("NDArray should have failed instantiation"); } catch (IllegalArgumentException e) { assert e.getLocalizedMessage() != null; // System.out.println("NDArray blocked bad dimensions args"); } }
@Override public ModelNode buildRequest(CommandContext ctx) throws OperationFormatException { DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); ParsedArguments args = ctx.getParsedArguments(); if (ctx.isDomainMode()) { String profile = this.profile.getValue(args); if (profile == null) { throw new OperationFormatException("--profile argument value is missing."); } builder.addNode("profile", profile); } final String name; try { name = this.name.getValue(args); } catch (IllegalArgumentException e) { throw new OperationFormatException(e.getLocalizedMessage()); } builder.addNode("subsystem", "jms"); builder.addNode("queue", name); builder.setOperationName("add"); ModelNode entriesNode = builder.getModelNode().get("entries"); final String entriesStr = this.entries.getValue(args); if (entriesStr == null) { entriesNode.add(name); } else { String[] split = entriesStr.split(","); for (int i = 0; i < split.length; ++i) { String entry = split[i].trim(); if (!entry.isEmpty()) { entriesNode.add(entry); } } } final String selector = this.selector.getValue(args); if (selector != null) { builder.addProperty("selector", selector); } final String durable = this.durable.getValue(args); if (durable != null) { builder.addProperty("durable", durable); } return builder.buildRequest(); }
@Override protected void onPause() { super.onPause(); if (mAdView != null) { mAdView.pause(); } if (requestReceiver != null) { try { this.unregisterReceiver(requestReceiver); } catch (IllegalArgumentException e) { Log.e(LOG_TAG, e.getLocalizedMessage(), e); } } }
/** * Create an MABoss from the given entity with the given max health. * * @param entity an entity * @param maxHealth a max health value */ public MABoss(LivingEntity entity, double maxHealth) { try { entity.setMaxHealth(maxHealth); entity.setHealth(maxHealth); } catch (IllegalArgumentException ex) { // Spigot... *facepalm* Messenger.severe( "Can't set health to " + maxHealth + ", using default health. If you are running Spigot, set 'maxHealth' higher in your Spigot settings."); Messenger.severe(ex.getLocalizedMessage()); } this.entity = entity; this.dead = false; }
@Test public void test_assertConfigurationIsValid_syntaxError() throws Exception { ContainerConfiguration configuration = new ContainerConfiguration(); configuration.setParameter(SecurityServiceConfig.SECURITY_SERVICE_CONFIG, "ads:"); SecurityServiceConfig config = new SecurityServiceConfig(configuration); try { AdsSecurityManager.assertConfigurationIsValid(config); fail(); } catch (IllegalArgumentException e) { assertEquals( "La configuration ads est invalide.\n" + "Veuillez vérifier la valeur de la propriété SecurityService.config.", e.getLocalizedMessage()); } }
public void handleMessage(Message msg) { if (!doTask) return; /** * currentPosView = getChildAt(dragCurPos - getFirstVisiblePosition()); if (currentPosView * != null) currentPosView.setBackgroundDrawable(null); /* */ int position; if (!downing) { position = getFirstVisiblePosition(); if (position == 0) { doTask = false; } else { position -= 5; } } else { position = getLastVisiblePosition(); if (position == getCount() - 1) { doTask = false; } else { position += 5; } } if (SDK8 && method != null) try { method.invoke(DDGridView.this, position); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block FileManager.error( "IllegalArgumentException: " + e.getLocalizedMessage() + "\n" + e.getMessage()); method = null; setSelection(position); } catch (IllegalAccessException e) { // TODO Auto-generated catch block FileManager.error( "IllegalAccessException: " + e.getLocalizedMessage() + "\n" + e.getMessage()); method = null; setSelection(position); } catch (InvocationTargetException e) { // TODO Auto-generated catch block FileManager.error( "InvocationTargetException: " + e.getLocalizedMessage() + "\n" + e.getMessage()); method = null; setSelection(position); } else setSelection(position); if (!doTask) ha.removeMessages(0); }
/** * Checks if a given resource is a valid NTv2 file without fully loading it. * * <p>If file is not valid, the cause is logged at {@link Level#WARNING warning level}. * * @param location the NTv2 file absolute path * @return true if file has NTv2 format, false otherwise */ protected boolean isNTv2GridFileValid(URL url) { RandomAccessFile raf = null; InputStream is = null; try { // Loading as RandomAccessFile doesn't load the full grid // in memory, but is a quick method to see if file format // is NTv2. if (url.getProtocol().equals("file")) { File file = DataUtilities.urlToFile(url); if (!file.exists() || !file.canRead()) { throw new IOException(Errors.format(ErrorKeys.FILE_DOES_NOT_EXIST_$1, file)); } raf = new RandomAccessFile(file, "r"); // will throw an exception if not a valid file new GridShiftFile().loadGridShiftFile(raf); } else { InputStream in = new BufferedInputStream(url.openConnection().getInputStream()); // will throw an exception if not a valid file new GridShiftFile().loadGridShiftFile(in, false); } return true; // No exception thrown => valid file. } catch (IllegalArgumentException e) { // This usually means resource is not a valid NTv2 file. // Let exception message describe the cause. LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e); return false; } catch (IOException e) { LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e); return false; } finally { try { if (raf != null) raf.close(); } catch (IOException e) { } try { if (is != null) is.close(); } catch (IOException e) { } } }
private void updateURIField() { synchronized (lock) { if (uriUserInput || uriFieldUpdate) { return; } uriFieldUpdate = true; } final String uri = computeMongoURIString(); try { uriField.setText(new MongoClientURI(uri).getURI()); clearNotificationLineSupport(); } catch (IllegalArgumentException ex) { error(ex.getLocalizedMessage()); } changeSupport.fireChange(); uriFieldUpdate = false; }
/* (non-Javadoc) * @see android.support.v4.app.Fragment#onStop() */ @Override public void onStop() { Log.v(TAG, "onStop : enter"); super.onStop(); // Unregister for broadcast if (null != connectReceiver) { try { getActivity().unregisterReceiver(connectReceiver); // connectReceiver = null; } catch (IllegalArgumentException e) { Log.e(TAG, e.getLocalizedMessage(), e); } } Log.v(TAG, "onStop : exit"); }
public void setPropertyValue(String fieldName, Object newValue) { PropertyHolder pp = properties.get(fieldName); if (pp == null) throw new NullPointerException( "Can not find property '" + fieldName + "' in bean " + obj.getClass().getName()); Method m = pp.getWriteMethod(); if (m == null) throw new NullPointerException( "Can not find set method '" + fieldName + "' in bean " + obj.getClass().getName()); try { m.invoke(obj, new Object[] {newValue}); } catch (IllegalArgumentException e) { StringBuilder sb = new StringBuilder("IllegalArgumentException:") .append(e.getLocalizedMessage()) .append('\n'); sb.append(obj.getClass().getName()) .append('\t') .append(fieldName) .append('\t') .append(newValue.getClass().getName()); throw new IllegalArgumentException(sb.toString()); } catch (IllegalAccessException e) { StringBuilder sb = new StringBuilder("IllegalAccessException:").append(e.getLocalizedMessage()).append('\n'); sb.append(obj.getClass().getName()) .append('\t') .append(fieldName) .append('\t') .append(newValue); throw new IllegalArgumentException(sb.toString()); } catch (InvocationTargetException e) { StringBuilder sb = new StringBuilder("InvocationTargetException:") .append(e.getLocalizedMessage()) .append('\n'); sb.append(obj.getClass().getName()) .append('\t') .append(fieldName) .append('\t') .append(newValue); throw new IllegalArgumentException(sb.toString()); } }
/** @see de.willuhn.jameica.gui.Part#paint(org.eclipse.swt.widgets.Composite) */ public void paint(Composite parent) throws RemoteException { button = GUI.getStyleFactory().createButton(parent); button.setText(this.title == null ? "" : this.title); button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); if (this.icon != null) button.setImage(SWTUtil.getImage(this.icon)); try { if (this.isDefault) parent.getShell().setDefaultButton(button); } catch (IllegalArgumentException ae) { // Kann unter MacOS wohl passieren. Siehe Mail von // Jan Lolling vom 22.09.2006. Mal schauen, ob wir // Fehlertext: "Widget has the wrong parent" // Wir versuchen es mal mit der Shell der GUI. try { GUI.getShell().setDefaultButton(button); } catch (IllegalArgumentException ae2) { // Geht auch nicht? Na gut, dann lassen wir es halt bleiben Logger.warn("unable to set default button: " + ae2.getLocalizedMessage()); } } button.setEnabled(this.enabled); button.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { GUI.startSync( new Runnable() { public void run() { try { action.handleAction(context); } catch (ApplicationException e) { Application.getMessagingFactory() .sendMessage( new StatusBarMessage(e.getMessage(), StatusBarMessage.TYPE_ERROR)); } } }); } }); }
/* * (non-Javadoc) * * @see org.smslib.smsserver.AInterface#getMessagesToSend() */ @Override public Collection<OutboundMessage> getMessagesToSend() throws Exception { Collection<OutboundMessage> messageList = new ArrayList<OutboundMessage>(); File[] outFiles = this.outDirectory.listFiles( new FileFilter() { public boolean accept(File f) { /* Read only unprocessed files with an .xml suffix */ return (f.getAbsolutePath().endsWith(".xml") && !getMessageCache().containsValue(f)); } }); for (int i = 0; i < outFiles.length; i++) { try { /* Process each document and add message to the list */ OutboundMessage msg = readDocument(outFiles[i]); if (msg == null) { throw new IllegalArgumentException("Missing required fieldes!"); } messageList.add(msg); getMessageCache().put(msg.getMessageId(), outFiles[i]); } catch (IllegalArgumentException e) { getService() .getLogger() .logWarn( "Skipping outgoing file " + outFiles[i].getAbsolutePath() + ": File is not valid: " + e.getLocalizedMessage(), null, null); File brokenFile = new File(this.outBrokenDirectory, outFiles[i].getName()); if (!outFiles[i].renameTo(brokenFile)) getService() .getLogger() .logError("Can't move " + outFiles[i] + " to " + brokenFile, null, null); } } return messageList; }
/** * See if we can connect to the server specified by the parameter cvsRootStr * * @param cvsrootStr * @return true if the connection could be made */ public static TeamworkCommandResult validateConnection(String cvsrootStr) { TeamworkCommandResult status = null; Connection connection = null; try { CVSRoot cvsroot = CVSRoot.parse(cvsrootStr); connection = getConnection(cvsroot); if (connection != null) { connection.verify(); status = new TeamworkCommandResult(); } } catch (AuthenticationException e) { // problem verifying connection status = new TeamworkCommandError(e.getMessage(), e.getLocalizedMessage()); } catch (IllegalArgumentException iae) { // problem parsing CVSRoot status = new TeamworkCommandError(iae.getMessage(), iae.getLocalizedMessage()); } return status; }
private static ObjectIdentifier buildObjectIdentifier( final ObjectSpecification o, ObjectIdentifier oi, final int objcount) { final SubsetSelection paths = getObjectPaths(o); final List<ObjectIdentifier> refchain; try { final RefChainResult res = processRefChains(o); if (res == null) { refchain = null; } else if (res.isToPath) { refchain = new LinkedList<>(); if (res.path.size() > 1) { refchain.addAll(res.path.subList(1, res.path.size())); } refchain.add(oi); oi = res.path.get(0); } else { refchain = res.path; } } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Error on ObjectSpecification #" + objcount + ": " + e.getLocalizedMessage(), e); } final boolean searchDAG = longToBoolean(o.getFindReferencePath()); if (paths == null && refchain == null && !searchDAG) { return oi; } else if (paths == null) { if (searchDAG) { return new ObjectIDWithRefPath(oi); } else { return new ObjectIDWithRefPath(oi, refchain); } } else { if (searchDAG) { return new ObjIDWithRefPathAndSubset(oi, paths); } else { return new ObjIDWithRefPathAndSubset(oi, refchain, paths); } } }
public static List<ObjectIdentifier> processObjectSpecifications( final List<ObjectSpecification> objects) { if (objects == null) { throw new NullPointerException("The object specification list cannot be null"); } if (objects.isEmpty()) { throw new IllegalArgumentException("No object specifications provided"); } final List<ObjectIdentifier> objs = new LinkedList<ObjectIdentifier>(); int objcount = 1; for (final ObjectSpecification o : objects) { if (o == null) { throw new NullPointerException("Objects in the object specification list cannot be null"); } final ObjectIdentifier oi; try { mutateObjSpecByRefString(o); oi = processObjectIdentifier( new ObjectIdentity() .withWorkspace(o.getWorkspace()) .withWsid(o.getWsid()) .withName(o.getName()) .withObjid(o.getObjid()) .withVer(o.getVer()) .withRef(o.getRef())); checkAddlArgs(o.getAdditionalProperties(), o.getClass()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Error on ObjectSpecification #" + objcount + ": " + e.getLocalizedMessage(), e); } objs.add(buildObjectIdentifier(o, oi, objcount)); objcount++; } return objs; }
/** * Sets the player's current texture pack * * @param player The player whose texture pack is being set * @param pack The name of the texture pack */ public void setPack(Player player, String pack) { try { String url; if (pack == null || (url = packs.get(pack)) == null) { getPlayers().set(player.getName().toLowerCase(), null); savePlayers(); return; } player.setTexturePack(url); String message = "You have selected the " + ChatColor.GREEN + pack + ChatColor.RESET + " pack."; if (player.getListeningPluginChannels().contains("SimpleNotice")) { player.sendPluginMessage( this, "SimpleNotice", message.getBytes(java.nio.charset.Charset.forName("UTF-8"))); } else { player.sendMessage(message); } getPlayers().set(player.getName().toLowerCase(), pack); savePlayers(); } catch (IllegalArgumentException e) { player.sendMessage(ChatColor.RED + "The supplied pack name was invalid."); warn(e.getLocalizedMessage()); } }
@Override public LinkedList<String> paintMap(Graphics2D g, GetMap gm, Style style) throws MissingDimensionValue, InvalidDimensionValue { LinkedList<Query> queries = new LinkedList<Query>(); LinkedList<String> warnings = collectQueries(style, gm, queries); Java2DRenderer renderer = new Java2DRenderer( g, gm.getWidth(), gm.getHeight(), gm.getBoundingBox(), gm.getPixelSize()); Java2DTextRenderer textRenderer = new Java2DTextRenderer(renderer); // TODO @SuppressWarnings({"rawtypes", "unchecked"}) XPathEvaluator<Feature> evaluator = (XPathEvaluator) new TypedObjectNodeXPathEvaluator(); if (queries.isEmpty()) { LOG.warn("No queries were generated. Is the configuration correct?"); return warnings; } FeatureInputStream rs = null; try { rs = datastore.query(queries.toArray(new Query[queries.size()])); // TODO Should this always be done on this level? What about min and maxFill values? rs = new ThreadedFeatureInputStream(rs, 100, 20); int max = gm.getRenderingOptions().getMaxFeatures(getName()); int cnt = 0; double resolution = gm.getResolution(); // TODO get rid of resolution handling on this code level completely // if ( !gm.getCoordinateSystem().equals( datastore.getStorageSRS() ) ) { // try { // Envelope b = new GeometryTransformer( datastore.getStorageSRS() ).transform( // gm.getBoundingBox() ); // resolution = Utils.calcResolution( b, gm.getWidth(), gm.getHeight() ); // } catch ( IllegalArgumentException e ) { // LOG.warn( "Calculating the resolution failed: '{}'", e.getLocalizedMessage() ); // LOG.trace( "Stack trace:", e ); // } catch ( TransformationException e ) { // LOG.warn( "Calculating the resolution failed: '{}'", e.getLocalizedMessage() ); // LOG.trace( "Stack trace:", e ); // } catch ( UnknownCRSException e ) { // LOG.warn( "Calculating the resolution failed: '{}'", e.getLocalizedMessage() ); // LOG.trace( "Stack trace:", e ); // } // } for (Feature f : rs) { try { render(f, evaluator, style, renderer, textRenderer, gm.getScale(), resolution); } catch (IllegalArgumentException e) { LOG.warn("Unable to render feature, probably a curve had multiple/non-linear segments."); LOG.warn("Error message was: {}", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } if (max > 0 && ++cnt == max) { LOG.debug("Reached max features of {} for layer '{}', stopping.", max, this); break; } } } catch (FilterEvaluationException e) { LOG.warn("A filter could not be evaluated. The error was '{}'.", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } catch (FeatureStoreException e) { LOG.warn( "Data could not be fetched from the feature store. The error was '{}'.", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } finally { if (rs != null) { rs.close(); } } return warnings; }
private <T extends RealFieldElement<T>> RungeKuttaStepInterpolator convertInterpolator( final RungeKuttaFieldStepInterpolator<T> fieldInterpolator, final FirstOrderFieldDifferentialEquations<T> eqn) { RungeKuttaStepInterpolator regularInterpolator = null; try { String interpolatorName = fieldInterpolator.getClass().getName(); String integratorName = interpolatorName.replaceAll("Field", ""); @SuppressWarnings("unchecked") Class<RungeKuttaStepInterpolator> clz = (Class<RungeKuttaStepInterpolator>) Class.forName(integratorName); regularInterpolator = clz.newInstance(); double[][] yDotArray = null; java.lang.reflect.Field fYD = RungeKuttaFieldStepInterpolator.class.getDeclaredField("yDotK"); fYD.setAccessible(true); @SuppressWarnings("unchecked") T[][] fieldYDotk = (T[][]) fYD.get(fieldInterpolator); yDotArray = new double[fieldYDotk.length][]; for (int i = 0; i < yDotArray.length; ++i) { yDotArray[i] = new double[fieldYDotk[i].length]; for (int j = 0; j < yDotArray[i].length; ++j) { yDotArray[i][j] = fieldYDotk[i][j].getReal(); } } double[] y = new double[yDotArray[0].length]; EquationsMapper primaryMapper = null; EquationsMapper[] secondaryMappers = null; java.lang.reflect.Field fMapper = AbstractFieldStepInterpolator.class.getDeclaredField("mapper"); fMapper.setAccessible(true); @SuppressWarnings("unchecked") FieldEquationsMapper<T> mapper = (FieldEquationsMapper<T>) fMapper.get(fieldInterpolator); java.lang.reflect.Field fStart = FieldEquationsMapper.class.getDeclaredField("start"); fStart.setAccessible(true); int[] start = (int[]) fStart.get(mapper); primaryMapper = new EquationsMapper(start[0], start[1]); secondaryMappers = new EquationsMapper[mapper.getNumberOfEquations() - 1]; for (int i = 0; i < secondaryMappers.length; ++i) { secondaryMappers[i] = new EquationsMapper(start[i + 1], start[i + 2]); } AbstractIntegrator dummyIntegrator = new AbstractIntegrator("dummy") { @Override public void integrate(ExpandableStatefulODE equations, double t) { Assert.fail("this method should not be called"); } @Override public void computeDerivatives(final double t, final double[] y, final double[] yDot) { T fieldT = fieldInterpolator.getCurrentState().getTime().getField().getZero().add(t); T[] fieldY = MathArrays.buildArray( fieldInterpolator.getCurrentState().getTime().getField(), y.length); for (int i = 0; i < y.length; ++i) { fieldY[i] = fieldInterpolator.getCurrentState().getTime().getField().getZero().add(y[i]); } T[] fieldYDot = eqn.computeDerivatives(fieldT, fieldY); for (int i = 0; i < yDot.length; ++i) { yDot[i] = fieldYDot[i].getReal(); } } }; regularInterpolator.reinitialize( dummyIntegrator, y, yDotArray, fieldInterpolator.isForward(), primaryMapper, secondaryMappers); T[] fieldPreviousY = fieldInterpolator.getPreviousState().getState(); for (int i = 0; i < y.length; ++i) { y[i] = fieldPreviousY[i].getReal(); } regularInterpolator.storeTime(fieldInterpolator.getPreviousState().getTime().getReal()); regularInterpolator.shift(); T[] fieldCurrentY = fieldInterpolator.getCurrentState().getState(); for (int i = 0; i < y.length; ++i) { y[i] = fieldCurrentY[i].getReal(); } regularInterpolator.storeTime(fieldInterpolator.getCurrentState().getTime().getReal()); } catch (ClassNotFoundException cnfe) { Assert.fail(cnfe.getLocalizedMessage()); } catch (InstantiationException ie) { Assert.fail(ie.getLocalizedMessage()); } catch (IllegalAccessException iae) { Assert.fail(iae.getLocalizedMessage()); } catch (NoSuchFieldException nsfe) { Assert.fail(nsfe.getLocalizedMessage()); } catch (IllegalArgumentException iae) { Assert.fail(iae.getLocalizedMessage()); } return regularInterpolator; }
public ArrayList<Pair<String, Counter<String>>> compileUsageForAllColumns( int minLength, int maxLength, int maxLines) { if (maxLines < 0) maxLines = Integer.MAX_VALUE; int nTillReport = 100000; int nObjsRead = 0; int nObjsReadTotal = 0; ArrayList<Pair<String, Counter<String>>> returnCounts = new ArrayList<Pair<String, Counter<String>>>(); try { int objNumCol = DumpColumnConfigInfo.getMuseumIdColumnIndex(); DumpColumnConfigInfo[] colDumpInfo = null; try { colDumpInfo = DumpColumnConfigInfo.getAllColumnInfo(columnNames); } catch (IllegalArgumentException iae) { String msg = "Mismatched columns between metadata configuration and metadata file.\n" + iae.getLocalizedMessage(); debug(0, msg); throw new RuntimeException(msg); } int nCols = columnNames.length; boolean[] skipCol = new boolean[nCols]; int[] countIndexes = new int[nCols]; for (int iCol = 0; iCol < nCols; iCol++) { if (!(skipCol[iCol] = !colDumpInfo[iCol].columnMinedForAnyFacet())) { countIndexes[iCol] = returnCounts.size(); returnCounts.add( new Pair<String, Counter<String>>(columnNames[iCol], new Counter<String>())); } else { countIndexes[iCol] = -1; } } resetToLine1(); Pair<Integer, ArrayList<String>> objInfo = null; while ((objInfo = getNextObjectAsColumns()) != null) { int currID = objInfo.getFirst(); ArrayList<String> objStrings = objInfo.getSecond(); assert (objStrings.size() == nCols) : "Bad parse for obj:" + currID; // Have a complete line. Check for validity String objNumStr = objStrings.get(objNumCol); if (DumpColumnConfigInfo.objNumIsValid(objNumStr)) { nObjsReadTotal++; if (++nObjsRead >= nTillReport) { nObjsRead = 0; debug(1, "MDR.compileUsageForAllColumns: read: " + nObjsReadTotal + " objects"); } for (int iCol = 1; iCol < nCols; iCol++) { if (skipCol[iCol]) // Do not bother with misc cols continue; String source = objStrings.get(iCol); if ((source.length() >= minLength) && (source.length() < maxLength)) { ArrayList<Pair<String, ArrayList<String>>> tokenList = ConfigStringUtils.prepareSourceTokens(source, colDumpInfo[iCol]); for (Pair<String, ArrayList<String>> pair : tokenList) { String subtoken = pair.getFirst().trim(); if (subtoken.length() > 1) returnCounts.get(countIndexes[iCol]).getSecond().incrementCount(subtoken, 1); } } } } } } catch (RuntimeException e) { e.printStackTrace(); } return returnCounts; }