private org.apache.hadoop.fs.FileSystem instantiateFileSystem( Class<? extends org.apache.hadoop.fs.FileSystem> fsClass) throws IOException { try { return fsClass.newInstance(); } catch (ExceptionInInitializerError e) { throw new IOException( "The filesystem class '" + fsClass.getName() + "' throw an exception upon initialization.", e.getException()); } catch (Throwable t) { String errorMessage = InstantiationUtil.checkForInstantiationError(fsClass); if (errorMessage != null) { throw new IOException( "The filesystem class '" + fsClass.getName() + "' cannot be instantiated: " + errorMessage); } else { throw new IOException( "An error occurred while instantiating the filesystem class '" + fsClass.getName() + "'.", t); } } }
/** * Invoke the method on the instance, with any arguments specified, casting the result of invoking * the method to the expected return type. * * <p> * * <p>This method wraps {@link Method#invoke(Object, Object...)}, converting the checked * exceptions that {@link Method#invoke(Object, Object...)} specifies to runtime exceptions. * * <p> * * <p>If instructed, this method attempts to set the accessible flag of the method in a {@link * PrivilegedAction} before invoking the method. * * @param setAccessible flag indicating whether method should first be set as accessible * @param method the method to invoke * @param instance the instance to invoke the method * @param args the arguments to the method * @return the result of invoking the method, or null if the method's return type is void * @throws RuntimeException if this <code>Method</code> object enforces Java language access * control and the underlying method is inaccessible or if the underlying method throws an * exception or if the initialization provoked by this method fails. * @throws IllegalArgumentException if the method is an instance method and the specified <code> * instance</code> argument is not an instance of the class or interface declaring the * underlying method (or of a subclass or implementor thereof); if the number of actual and * formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, * after possible unwrapping, a parameter value cannot be converted to the corresponding * formal parameter type by a method invocation conversion. * @throws NullPointerException if the specified <code>instance</code> is null and the method is * an instance method. * @throws ClassCastException if the result of invoking the method cannot be cast to the * expectedReturnType * @throws ExceptionInInitializerError if the initialization provoked by this method fails. * @see Method#invoke(Object, Object...) */ public static <T> T invokeMethod( boolean setAccessible, Method method, Class<T> expectedReturnType, Object instance, Object... args) { if (setAccessible && !method.isAccessible()) { setAccessible(method); } try { return expectedReturnType.cast(method.invoke(instance, args)); } catch (IllegalAccessException ex) { throw new RuntimeException(buildInvokeMethodErrorMessage(method, instance, args), ex); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException(buildInvokeMethodErrorMessage(method, instance, args), ex); } catch (InvocationTargetException ex) { throw new RuntimeException( buildInvokeMethodErrorMessage(method, instance, args), ex.getCause()); } catch (NullPointerException ex) { NullPointerException ex2 = new NullPointerException(buildInvokeMethodErrorMessage(method, instance, args)); ex2.initCause(ex.getCause()); throw ex2; } catch (ExceptionInInitializerError e) { ExceptionInInitializerError e2 = new ExceptionInInitializerError(buildInvokeMethodErrorMessage(method, instance, args)); e2.initCause(e.getCause()); throw e2; } }
private void prepareSuite() { Class<?> benchmarkClass; try { benchmarkClass = getClassByName(suiteClassName); } catch (ExceptionInInitializerError e) { throw new ExceptionFromUserCodeException(e.getCause()); } catch (ClassNotFoundException ignored) { throw new NoSuchClassException(suiteClassName); } Object s; try { Constructor<?> constructor = benchmarkClass.getDeclaredConstructor(); constructor.setAccessible(true); s = constructor.newInstance(); } catch (InstantiationException ignore) { throw new AbstractBenchmarkException(benchmarkClass); } catch (NoSuchMethodException ignore) { throw new NoParameterlessConstructorException(benchmarkClass); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // shouldn't happen since we setAccessible(true) } catch (InvocationTargetException e) { throw new ExceptionFromUserCodeException(e.getCause()); } if (s instanceof Benchmark) { this.suite = (Benchmark) s; } else { throw new DoesntImplementBenchmarkException(benchmarkClass); } }
public void testBroken3() { try { Broken3Enum.RED.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } }
public TestSubmissionEmail getPort() { String EPPath = "/soa-infra/services/default/Lab2ptEmailFormatter/testsubmissionemail_client_ep"; /* String devServer = "http://soadev.cap.org:8001"; String tstServer = "http://soatst.cap.org:8001"; String ssPc = "http://dw764760cf1v9k1.cap.org:8001"; String soapUI = "http://localhost:8088"; // String surl = tstServer + EPPath; */ String soaServer = null; try { String server = InfraConfig.getString("org.cap.submission.emailFormatter.server"); String port = InfraConfig.getString("org.cap.submission.emailFormatter.port"); soaServer = "http://" + server + ":" + port; } catch (ExceptionInInitializerError e) { System.err.println( "Error: Unable to get email formatter server name, org.cap.submission.emailFormatter.server"); System.err.println(e.getMessage()); soaServer = null; } catch (NoClassDefFoundError e) { System.err.println( "Error: Unable to locate InfraConfig class to get email formatter server name, org.cap.submission.emailFormatter.server"); System.err.println(e.getMessage()); soaServer = null; } String surl = soaServer + EPPath; TestSubmissionEmail port = null; URL url; try { URL baseUrl = new File(".").toURL(); url = new URL(baseUrl, surl + "?wsdl"); // System.out.println("getMailPort:" + url); // 1st argument service URI, refer to wsdl document above // 2nd argument is service name, refer to wsdl document above QName qname = new QName( "http://xmlns.oracle.com/Lab2ptEmailFormatter_jws/Lab2ptEmailFormatter/TestSubmissionEmail", "testsubmissionemail_client_ep"); Testsubmissionemail_client_ep service = new Testsubmissionemail_client_ep(url, qname); port = service.getTestSubmissionEmail_pt(); BindingProvider bp = (BindingProvider) port; Map<String, Object> context = bp.getRequestContext(); Object oldAddress = context.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, surl); } catch (MalformedURLException e) { System.out.println("Failed to create wsdlLocationURL using " + surl); } return port; }
/** * Get the value of the field, on the specified instance, casting the value of the field to the * expected type. * * <p> * * <p>This method wraps {@link Field#get(Object)}, converting the checked exceptions that {@link * Field#get(Object)} specifies to runtime exceptions. * * @param <T> the type of the field's value * @param field the field to operate on * @param instance the instance from which to retrieve the value * @param expectedType the expected type of the field's value * @return the value of the field * @throws RuntimeException if the underlying field is inaccessible. * @throws IllegalArgumentException if the specified <code>instance</code> is not an instance of * the class or interface declaring the underlying field (or a subclass or implementor * thereof). * @throws NullPointerException if the specified <code>instance</code> is null and the field is an * instance field. * @throws ExceptionInInitializerError if the initialization provoked by this method fails. */ public static <T> T getFieldValue(Field field, Object instance, Class<T> expectedType) { try { return Reflections.cast(field.get(instance)); } catch (IllegalAccessException e) { throw new RuntimeException(buildGetFieldValueErrorMessage(field, instance), e); } catch (NullPointerException ex) { NullPointerException ex2 = new NullPointerException(buildGetFieldValueErrorMessage(field, instance)); ex2.initCause(ex.getCause()); throw ex2; } catch (ExceptionInInitializerError e) { ExceptionInInitializerError e2 = new ExceptionInInitializerError(buildGetFieldValueErrorMessage(field, instance)); e2.initCause(e.getCause()); throw e2; } }
public FullPalletTestJC() { ArrayList<CSIColor> list = new ArrayList<CSIColor>(); for (int i = 0; i < CSIColor.FULL_PALLET.length; i++) { list.add(CSIColor.FULL_PALLET[i]); } Collections.sort(list); try { mainInterface = new WSwingConsoleInterface("CSIColor Test", false); } catch (ExceptionInInitializerError eiie) { System.out.println("Fatal Error Initializing Swing Console Box"); eiie.printStackTrace(); System.exit(-1); } int x = 0, times = 0; CSIColor tempColor = CSIColor.WHITE, backColor = CSIColor.BLACK; for (int k = 0; k < mainInterface.ydim; k++) { for (int i = 0; i < mainInterface.xdim; i++) { if (!(x < list.size())) { x = 0; times++; } tempColor = list.get(x); x++; switch (times) { case 0: backColor = CSIColor.BLACK; break; case 1: backColor = CSIColor.GRAY; break; case 2: backColor = CSIColor.WHITE; break; case 3: backColor = CSIColor.BLACK; times = 0; } mainInterface.print(i, k, 'Q', new CSIColor(tempColor), new CSIColor(backColor)); } } }
@AdviseWith(adviceClasses = {PropsUtilAdvice.class}) @Test public void testClassInitializationFailed() { System.setProperty(PropsKeys.INTRABAND_IMPL, "NoSuchClass"); try { MPIHelperUtil.getMPI(); Assert.fail(); } catch (ExceptionInInitializerError eiie) { Throwable throwable = eiie.getCause(); Assert.assertSame(RuntimeException.class, throwable.getClass()); Assert.assertEquals("Unable to instantiate NoSuchClass", throwable.getMessage()); } finally { System.clearProperty(PropsKeys.INTRABAND_IMPL); } }
public MySQLConnection() { String url = PATH + DATABASE; try { Class.forName(DRIVER); connection = DriverManager.getConnection(url, USER, PASSWORD); if (connection != null) System.out.println("Conexion establecida con la base de datos."); else System.out.println("ERROR: Conexion nula."); } catch (ClassNotFoundException e) { System.out.println("ERROR: Driver de la base de datos no encontrado."); e.printStackTrace(); } catch (ExceptionInInitializerError e) { System.out.println("ERROR: Driver de la base de datos no inicializado."); e.printStackTrace(); } catch (SQLException e) { System.out.println("ERROR: Fallo al conectar con la base de datos."); e.printStackTrace(); } }
/** * Sets the value of a field on the instance to the specified value. * * <p> * * <p>This method wraps {@link Field#set(Object, Object)}, converting the checked exceptions that * {@link Field#set(Object, Object)} specifies to runtime exceptions. * * <p> * * <p>If instructed, this method attempts to set the accessible flag of the method in a {@link * PrivilegedAction} before invoking the method. * * @param field the field on which to operate, or null if the field is static * @param instance the instance on which the field value should be set upon * @param value the value to set the field to * @throws RuntimeException if the underlying field is inaccessible. * @throws IllegalArgumentException if the specified <code>instance</code> is not an instance of * the class or interface declaring the underlying field (or a subclass or implementor * thereof), or if an unwrapping conversion fails. * @throws NullPointerException if the specified <code>instance</code> is null and the field is an * instance field. * @throws ExceptionInInitializerError if the initialization provoked by this method fails. * @see Field#set(Object, Object) */ public static void setFieldValue( boolean setAccessible, Field field, Object instance, Object value) { if (setAccessible && !field.isAccessible()) { setAccessible(field); } try { field.set(instance, value); } catch (IllegalAccessException e) { throw new RuntimeException(buildSetFieldValueErrorMessage(field, instance, value), e); } catch (NullPointerException ex) { NullPointerException ex2 = new NullPointerException(buildSetFieldValueErrorMessage(field, instance, value)); ex2.initCause(ex.getCause()); throw ex2; } catch (ExceptionInInitializerError e) { ExceptionInInitializerError e2 = new ExceptionInInitializerError(buildSetFieldValueErrorMessage(field, instance, value)); e2.initCause(e.getCause()); throw e2; } }
/** * This is used by standalone tools to force static initialization of DatabaseDescriptor, and fail * if configuration is bad. */ public static void initDatabaseDescriptor() { try { DatabaseDescriptor.forceStaticInitialization(); } catch (ExceptionInInitializerError e) { Throwable cause = e.getCause(); boolean logStackTrace = !(cause instanceof ConfigurationException) || ((ConfigurationException) cause).logStackTrace; System.out.println( "Exception (" + cause.getClass().getName() + ") encountered during startup: " + cause.getMessage()); if (logStackTrace) { cause.printStackTrace(); System.exit(3); } else { System.err.println(cause.getMessage()); System.exit(3); } } }
private void processConfigurationModules(final Class<?> cmb) { for (final Field f : cmb.getFields()) { if (ReflectionUtilities.isCoercable(ConfigurationModule.class, f.getType())) { final int mod = f.getModifiers(); boolean ok = true; if (Modifier.isPrivate(mod)) { System.err.println("Found private ConfigurationModule " + f); ok = false; } if (!Modifier.isFinal(mod)) { System.err.println("Found non-final ConfigurationModule " + f); ok = false; } if (!Modifier.isStatic(f.getModifiers())) { System.err.println("Found non-static ConfigurationModule " + f); ok = false; } if (ok) { // System.err.println("OK: " + f); try { f.setAccessible(true); final String fS = ReflectionUtilities.getFullName(f); if (!modules.containsKey(f)) { modules.put(f, (ConfigurationModule) (f.get(null))); try { modules.get(f).assertStaticClean(); } catch (final ClassHierarchyException e) { System.err.println(fS + ": " + e.getMessage()); } for (final Entry<String, String> e : modules.get(f).toStringPairs()) { // System.err.println("e: " + e.getKey() + "=" + e.getValue()); try { final Node n = ch.getNode(e.getKey()); if (!setters.contains(e.getKey(), fS)) { setters.put(e.getKey(), fS); } if (n instanceof ClassNode) { final ClassNode<?> cn = (ClassNode<?>) n; if (!knownClasses.contains(cn)) { knownClasses.add(cn); } } } catch (final NameResolutionException ex) { // } try { final String s = e.getValue(); final Node n = ch.getNode(s); if (!usages.contains(ReflectionUtilities.getFullName(f), s)) { // System.err.println("Added usage: " + ReflectionUtilities.getFullName(f) + // "=" + s); usages.put(s, ReflectionUtilities.getFullName(f)); } if (n instanceof ClassNode) { final ClassNode<?> cn = (ClassNode<?>) n; if (!knownClasses.contains(cn)) { System.err.println("Added " + cn + " to known classes"); knownClasses.add(cn); } } } catch (final NameResolutionException ex) { // } } } } catch (final ExceptionInInitializerError e) { System.err.println( "Field " + ReflectionUtilities.getFullName(f) + ": " + e.getCause().getMessage()); } catch (final IllegalAccessException e) { throw new RuntimeException(e); } } } } }
/** * {@linkplain #registerServiceProvider Registers} all factories given by the supplied iterator. * * @param factories The factories (or "service providers") to register. * @param category the category under which to register the providers. * @param message A buffer where to write the logging message. * @return {@code true} if at least one factory has been registered. */ private <T> boolean register( final Iterator<T> factories, final Class<T> category, final StringBuilder message) { boolean newServices = false; final String lineSeparator = System.getProperty("line.separator", "\n"); while (factories.hasNext()) { T factory; try { factory = factories.next(); } catch (OutOfMemoryError error) { // Makes sure that we don't try to handle this error. throw error; } catch (NoClassDefFoundError error) { /* * A provider can't be registered because of some missing dependencies. * This occurs for example when trying to register the WarpTransform2D * math transform on a machine without JAI installation. Since the factory * may not be essential (this is the case of WarpTransform2D), just skip it. */ loadingFailure(category, error, false); continue; } catch (ExceptionInInitializerError error) { /* * If an exception occured during class initialization, log the cause. * The ExceptionInInitializerError alone doesn't help enough. */ final Throwable cause = error.getCause(); if (cause != null) { loadingFailure(category, cause, true); } throw error; } catch (Error error) { if (!Classes.getShortClassName(error).equals("ServiceConfigurationError")) { // We want to handle sun.misc.ServiceConfigurationError only. Unfortunatly, we // need to rely on reflection because this error class is not a commited API. // TODO: Check if the error is catchable with JSE 6. throw error; } /* * Failed to register a factory for a reason probably related to the plugin * initialisation. It may be some factory-dependent missing resources. */ loadingFailure(category, error, true); continue; } if (category.isAssignableFrom(factory.getClass())) { final Class<? extends T> factoryClass = factory.getClass().asSubclass(category); /* * If the factory implements more than one interface and an * instance were already registered, reuse the same instance * instead of duplicating it. */ final T replacement = getServiceProviderByClass(factoryClass); if (replacement != null) { factory = replacement; // Need to register anyway, because the category may not be // the same. } if (registerServiceProvider(factory, category)) { /* * The factory is now registered. Add it to the message to * be logged. We will log all factories together in a single * log event because some registration (e.g. * MathTransformProviders) would be otherwise quite verbose. */ message.append(lineSeparator); message.append(" "); message.append(factoryClass.getName()); newServices = true; } } } return newServices; }
/** * Method deserialize reads all "properties" from file specified by filename and writes it to * object of class T using setters. Method use properties with setters. Properties without setters * ignored. */ public T deserialize(String filename, Class<T> clazz) throws SerializationException, NullPointerException, IOException { if (null == filename) { throw new NullPointerException("FileName is null."); } else if (null == clazz) { throw new NullPointerException("Class for deserialization is null."); } Properties propertiesTable = new Properties(); Reader reader = null; try { reader = new BufferedReader(new FileReader(filename)); propertiesTable.load(reader); } catch (IllegalArgumentException e) { throw new SerializationException("Have problems loading properties. Bad format."); } finally { if (null != reader) { reader.close(); } } List<PropertiesAnalyzer.Property> propertiesList = analyzer.getProperties(clazz); Constructor<T> constructor; T t; try { constructor = clazz.getConstructor(); t = constructor.newInstance(); } catch (NoSuchMethodException e) { throw new SerializationException( "No default constructor for class " + clazz.getName() + ". " + e.getMessage()); } catch (IllegalAccessException e) { throw new SerializationException("Illegal access to default constructor. " + e.getMessage()); } catch (InstantiationException e) { throw new SerializationException( "Default constructor represents an abstract class in " + clazz.getName() + "." + e.getMessage()); } catch (InvocationTargetException e) { throw new SerializationException( "Default constructor throws an exception. " + e.getMessage()); } catch (ExceptionInInitializerError e) { throw new SerializationException( "Initialization provoked by default constructor fails. " + e.getMessage()); } for (PropertiesAnalyzer.Property property : propertiesList) { try { String key = property.getName(); String value = propertiesTable.getProperty(key); Class propertyClass = property.getGetter().getReturnType(); Object castedValue = null; if (null == value) { continue; } else if (propertyClass.equals(Integer.class) || propertyClass.equals(int.class)) { castedValue = Integer.parseInt(value); } else if (propertyClass.equals(Byte.class) || propertyClass.equals(byte.class)) { castedValue = Byte.parseByte(value); } else if (propertyClass.equals(Short.class) || propertyClass.equals(short.class)) { castedValue = Short.parseShort(value); } else if (propertyClass.equals(Long.class) || propertyClass.equals(long.class)) { castedValue = Long.parseLong(value); } else if (propertyClass.equals(Float.class) || propertyClass.equals(float.class)) { castedValue = Float.parseFloat(value); } else if (propertyClass.equals(Double.class) || propertyClass.equals(double.class)) { castedValue = Double.parseDouble(value); } else if (propertyClass.equals(Boolean.class) || propertyClass.equals(boolean.class)) { castedValue = Boolean.parseBoolean(value); } else if (propertyClass.equals(Character.class) || propertyClass.equals(char.class)) { if (value.length() > 0) { castedValue = value.charAt(0); } } else if (propertyClass.equals(String.class)) { castedValue = value; } else { throw new SerializationException( "Unsupported class for deserialization: " + propertyClass.getName()); } property.getSetter().invoke(t, castedValue); } catch (NumberFormatException e) { throw new SerializationException("Can't deserialize a value: " + e.getMessage()); } catch (IllegalAccessException e) { throw new SerializationException("Illegal access to setter. " + e.getMessage()); } catch (InvocationTargetException e) { throw new SerializationException("Setter throw an exception. " + e.getMessage()); } catch (IllegalArgumentException e) { throw new SerializationException( "Getter return value and setter input value have different types. " + e.getMessage()); } catch (ExceptionInInitializerError e) { throw new SerializationException( "Initialization provoked by this method fails. " + e.getMessage()); } } return t; }
/** * Parses the command line. The user must specify at least one class to optimize and the directory * in which to place the optimized class files. The methods of the specified classes are then * optimized according to the command line options. * * @see ClassEditor * @see ClassFileLoader * @see ClassFile * @see MethodEditor * @see MethodInfo * @see CompactArrayInitializer * @see FlowGraph */ public static void main(final String[] args) { try { Main.loader = new ClassFileLoader(); List classes = new ArrayList(args.length); // The classes to // optimize boolean gotdir = false; // Has an output directory been specified? Main.ARGS = args; for (int i = 0; i < args.length; i++) { if (args[i].equals("-v") || args[i].equals("-verbose")) { Main.VERBOSE = true; Main.loader.setVerbose(true); } else if (args[i].equals("-debug")) { Main.DEBUG = true; Main.loader.setVerbose(true); ClassFileLoader.DEBUG = true; CompactArrayInitializer.DEBUG = true; ClassEditor.DEBUG = true; FlowGraph.DEBUG = true; DominatorTree.DEBUG = true; Tree.DEBUG = true; CodeGenerator.DEBUG = true; Liveness.DEBUG = true; SSA.DEBUG = true; SSAGraph.DEBUG = true; PersistentCheckElimination.DEBUG = true; ValueNumbering.DEBUG = true; ValueFolding.DEBUG = true; ClassHierarchy.DEBUG = true; TypeInference.DEBUG = true; SSAPRE.DEBUG = true; StackPRE.DEBUG = true; ExprPropagation.DEBUG = true; DeadCodeElimination.DEBUG = true; CodeGenerator.DB_OPT_STACK = true; } else if (args[i].equals("-trace")) { Main.TRACE = true; } else if (args[i].equals("-db")) { if (++i >= args.length) { System.err.println("** No debugging option specified"); Main.usage(); } if (args[i].equals("bc")) { CodeArray.DEBUG = true; } else if (args[i].equals("cfg")) { FlowGraph.DEBUG = true; } else if (args[i].equals("ssa")) { SSA.DEBUG = true; SSAGraph.DEBUG = true; } else if (args[i].equals("graphs")) { FlowGraph.DB_GRAPHS = true; } else if (args[i].startsWith("-")) { i--; } else { System.err.println("** Unknown debugging option: " + args[i]); Main.usage(); } } else if (args[i].equals("-debugvf")) { ValueFolding.DUMP = true; } else if (args[i].equals("-debugbc")) { BloatContext.DEBUG = true; } else if (args[i].equals("-help")) { Main.usage(); } else if (args[i].equals("-noanno")) { Main.ANNO = false; } else if (args[i].equals("-anno")) { Main.ANNO = true; } else if (args[i].equals("-print-flow-graph")) { FlowGraph.PRINT_GRAPH = true; } else if (args[i].equals("-preserve-debug")) { MethodEditor.PRESERVE_DEBUG = true; } else if (args[i].equals("-nouse-stack-vars")) { Tree.USE_STACK = false; } else if (args[i].equals("-use-stack-vars")) { Tree.USE_STACK = true; } else if (args[i].equals("-unique-handlers")) { MethodEditor.UNIQUE_HANDLERS = true; } else if (args[i].equals("-nocompact-array-init")) { Main.COMPACT_ARRAY_INIT = false; } else if (args[i].equals("-compact-array-init")) { Main.COMPACT_ARRAY_INIT = true; } else if (args[i].equals("-nostack-alloc")) { Main.STACK_ALLOC = false; } else if (args[i].equals("-stack-alloc")) { Main.STACK_ALLOC = true; } else if (args[i].equals("-no-verify")) { Main.VERIFY = false; } else if (args[i].equals("-peel-loops")) { if (++i >= args.length) { Main.usage(); } final String n = args[i]; if (n.equals("all")) { FlowGraph.PEEL_LOOPS_LEVEL = FlowGraph.PEEL_ALL_LOOPS; } else { try { FlowGraph.PEEL_LOOPS_LEVEL = Integer.parseInt(n); if (FlowGraph.PEEL_LOOPS_LEVEL < 0) { Main.usage(); } } catch (final NumberFormatException ex) { Main.usage(); } } } else if (args[i].equals("-color")) { Liveness.UNIQUE = false; } else if (args[i].equals("-nocolor")) { Liveness.UNIQUE = true; } else if (args[i].equals("-only-method")) { if (++i >= args.length) { Main.usage(); } Main.METHOD = args[i]; } else if (args[i].equals("-classpath")) { if (++i >= args.length) { Main.usage(); } final String classpath = args[i]; Main.loader.setClassPath(classpath); } else if (args[i].equals("-classpath/p")) { if (++i >= args.length) { Main.usage(); } final String classpath = args[i]; Main.loader.prependClassPath(classpath); } else if (args[i].equals("-skip")) { if (++i >= args.length) { Main.usage(); } String pkg = args[i]; // Account for class file name on command line if (pkg.endsWith(".class")) { pkg = pkg.substring(0, pkg.lastIndexOf('.')); } Main.SKIP.add(pkg.replace('.', '/')); } else if (args[i].equals("-only")) { if (++i >= args.length) { Main.usage(); } String pkg = args[i]; // Account for class file name on command line if (pkg.endsWith(".class")) { pkg = pkg.substring(0, pkg.lastIndexOf('.')); } Main.ONLY.add(pkg.replace('.', '/')); } else if (args[i].equals("-nodce")) { Main.DCE = false; } else if (args[i].equals("-noprop")) { Main.PROP = false; } else if (args[i].equals("-noappre")) { SSAPRE.NO_ACCESS_PATHS = true; } else if (args[i].equals("-nopre")) { Main.PRE = false; } else if (args[i].equals("-dce")) { Main.DCE = true; } else if (args[i].equals("-prop")) { Main.PROP = true; } else if (args[i].equals("-appre")) { SSAPRE.NO_ACCESS_PATHS = false; } else if (args[i].equals("-pre")) { Main.PRE = true; } else if (args[i].equals("-closure")) { Main.CLOSURE = true; } else if (args[i].equals("-opt-stack-1")) { Main.OPT_STACK_1 = true; CodeGenerator.OPT_STACK = true; } else if (args[i].equals("-opt-stack-2")) { Main.OPT_STACK_2 = true; MethodEditor.OPT_STACK_2 = true; } else if (args[i].equals("-diva")) { Main.DIVA = true; } else if (args[i].equals("-no-thread")) { SSAPRE.NO_THREAD = true; } else if (args[i].equals("-no-precise")) { SSAPRE.NO_PRECISE = true; } else if (args[i].equals("-relax-loading")) { ClassHierarchy.RELAX = true; } else if (args[i].equals("-f") || args[i].equals("-force")) { Main.FORCE = true; } else if (args[i].startsWith("-")) { System.err.println("No such option: " + args[i]); Main.usage(); } else if (i == args.length - 1) { // Last argument is the name of the output directory final File f = new File(args[i]); if (f.exists() && !f.isDirectory()) { System.err.println("No such directory: " + f.getPath()); System.exit(2); } if (!f.exists()) { f.mkdirs(); } if (!f.exists()) { System.err.println("Couldn't create directory: " + f.getPath()); System.exit(2); } // Tell class loader to put optimized classes in f directory Main.loader.setOutputDir(f); gotdir = true; } else { // The argument must be a class name... classes.add(args[i]); } } if (!gotdir) { System.err.println("No output directory specified"); Main.usage(); } if (classes.size() == 0) { System.err.println("** No classes specified"); Main.usage(); } // Use the CachingBloatingContext Main.context = new CachingBloatContext(Main.loader, classes, Main.CLOSURE); boolean errors = false; final Iterator iter = classes.iterator(); // Now that we've parsed the command line, load the classes into the // class loader while (iter.hasNext()) { final String name = (String) iter.next(); try { Main.context.loadClass(name); } catch (final ClassNotFoundException ex) { System.err.println("Couldn't find class: " + ex.getMessage()); errors = true; } } if (errors) { System.exit(1); } if (!Main.CLOSURE) { final Iterator e = classes.iterator(); // Edit only the classes that were specified on the command line while (e.hasNext()) { final String name = (String) e.next(); Main.editClass(name); } } else { // Edit all the classes in the class file editor and their // superclasses classes = null; if (Main.TRACE) { System.out.println("Computing closure " + Main.dateFormat.format(new Date())); } final Iterator e = Main.context.getHierarchy().classes().iterator(); while (e.hasNext()) { final Type t = (Type) e.next(); if (t.isObject()) { Main.editClass(t.className()); } } } } catch (final ExceptionInInitializerError ex) { ex.printStackTrace(); System.out.println(ex.getException()); } }
/** * Process and loop until told to stop. A callback_done will stop the loop and will return a * result. Otherwise null is returned. */ public Object run() throws CommandException { Object result = null; boolean shutdown = false; boolean closeWhenDone = true; Commands.ValueObject valueObject = new Commands.ValueObject(); // Working value object so not continually recreated. InvokableValueSender valueSender = new InvokableValueSender(); // Working valuesender so not continually recreated. try { boolean doLoop = true; /** * Note: In the cases below you will see a lot of finally clauses that null variables out. * This is because this is a long running loop, and variables declared within blocks are not * garbage collected until the method is terminated, so these variables once set would never * be GC'd. The nulling at the end of the case makes sure that any of those objects set are * now available for garbage collection when necessary. */ while (doLoop && isConnected()) { byte cmd = 0; try { if (LINUX_1_3) socket.setSoTimeout(1000); // Linux 1.3 bug, see comment on LINUX_1_3 cmd = in.readByte(); if (LINUX_1_3 && isConnected()) socket.setSoTimeout(0); // Linux 1.3 bug, see comment on LINUX_1_3 } catch (InterruptedIOException e) { continue; // Timeout, try again } switch (cmd) { case Commands.QUIT_CONNECTION: doLoop = false; break; // Close this connection case Commands.TERMINATE_SERVER: doLoop = false; shutdown = true; // Shutdown everything break; case Commands.GET_CLASS: String className = in.readUTF(); Class aClass = null; Class superClass = null; String superClassName = null; boolean added = false; try { aClass = Class.forName( className); // Turns out using JNI format for array type will work fine. added = server.getIdentityID(aClass, valueObject); boolean isInterface = aClass.isInterface(); boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers()); superClass = aClass.getSuperclass(); superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$ out.writeByte(Commands.GET_CLASS_RETURN); out.writeInt(valueObject.objectID); out.writeBoolean(isInterface); out.writeBoolean(isAbstract); out.writeUTF(superClassName); out.flush(); } catch (ClassNotFoundException e) { valueObject.set(); Commands.sendErrorCommand(out, Commands.GET_CLASS_NOT_FOUND, valueObject); } catch (ExceptionInInitializerError e) { sendException(e.getException(), valueObject, out); } catch (LinkageError e) { sendException(e, valueObject, out); } catch (Throwable e) { // Something bad, did we add a class? If we did remove it from the table. if (added) server.removeObject(server.getObject(valueObject.objectID)); throw e; } finally { // clear out for GC to work. className = null; aClass = null; superClass = null; superClassName = null; valueObject.set(); } break; case Commands.GET_CLASS_FROM_ID: int classID = in.readInt(); try { aClass = (Class) server.getObject(classID); boolean isInterface = aClass.isInterface(); boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers()); superClass = aClass.getSuperclass(); superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$ out.writeByte(Commands.GET_CLASS_ID_RETURN); out.writeUTF(aClass.getName()); out.writeBoolean(isInterface); out.writeBoolean(isAbstract); out.writeUTF(superClassName); out.flush(); } catch (ClassCastException e) { valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); } finally { // clear out for GC to work. aClass = null; superClass = null; superClassName = null; valueObject.set(); } break; case Commands.GET_OBJECT_DATA: int objectID = in.readInt(); Object anObject = null; try { anObject = server.getObject(objectID); valueObject.setObjectID(objectID, server.getIdentityID(anObject.getClass())); Commands.writeValue(out, valueObject, true); } catch (ClassCastException e) { valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); } finally { anObject = null; // Clear out for GC to work valueObject.set(); } break; case Commands.RELEASE_OBJECT: int id = in.readInt(); server.removeObject(server.getObject(id)); break; case Commands.NEW_INIT_STRING: classID = in.readInt(); // ID Of class to do new upon. String initString = in.readUTF(); // The init string. Object newValue = null; Class theClass = null; try { theClass = (Class) server.getObject(classID); if (theClass == null) { // The class wasn't found. So imply ClassNotFound exception. throw new ClassNotFoundException(); } InitializationStringParser parser = null; try { parser = InitializationStringParser.createParser(initString); newValue = parser.evaluate(); boolean primitive = parser.isPrimitive(); // If expected class is Void.TYPE, that means don't test the type of the result // to verify if correct type, just return what it really is. if (theClass != Void.TYPE && primitive != theClass.isPrimitive()) { valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); continue; // Goto next command. } if (primitive) { try { // Need to do special tests for compatibility and assignment. sendObject( newValue, classID != Commands.VOID_TYPE ? classID : server.getIdentityID(parser.getExpectedType()), valueObject, out, true); // This will make sure it goes out as the correct primitive type } catch (ClassCastException e) { // The returned type is not of the correct type for what is expected. valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); continue; // Goto next command } } else { if (newValue != null) { // Test to see if they are compatible. (Null can be assigned to any object, // so that is why it was tested out above). // If expected class is Void.TYPE, that means don't test the type of the result // to verify if correct type, just return what it really is. if (theClass != Void.TYPE && !theClass.isInstance(newValue)) { // The returned type is not of the correct type for what is expected. valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); continue; // Goto next command } } sendObject( newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Send out as an object. } } catch (InitializationStringEvaluationException e) { if (e instanceof EvaluationException) { // Want to return the real exception. sendException(e.getOriginalException(), valueObject, out); } else { // Couldn't be evaluated, return an error for this. setExceptionIntoValue(e.getOriginalException(), valueObject); Commands.sendErrorCommand(out, Commands.CANNOT_EVALUATE_STRING, valueObject); } } finally { parser = null; // Clear out for GC to work } } catch (Throwable e) { sendException(e, valueObject, out); } finally { // Clear out for GC to work initString = null; theClass = null; newValue = null; valueObject.set(); } break; case Commands.INVOKE: Object target = null; Object[] parms = null; Class returnType = null; java.lang.reflect.Method aMethod = null; try { int methodID = in.readInt(); // ID of method to invoke aMethod = (java.lang.reflect.Method) server.getObject(methodID); // Method to invoke Commands.readValue(in, valueObject); target = getInvokableObject(valueObject); Commands.readValue(in, valueObject); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); parms = (Object[]) valueSender.getArray(); } else { // It is all objects or null, so it should be an Object[] or null. If not, then this // is an error. parms = (Object[]) valueObject.anObject; } if (!aMethod.isAccessible()) aMethod.setAccessible( true); // We will allow all to occur. Let access control be handled by IDE and // compiler. newValue = aMethod.invoke(target, parms); returnType = aMethod.getReturnType(); if (returnType.isPrimitive()) { int returnTypeID = server.getIdentityID(returnType); // Need to tell sendObject the correct primitive type. sendObject(newValue, returnTypeID, valueObject, out, true); } else { sendObject( newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Just send the object back. sendObject knows how to iterpret the type } } catch (CommandException e) { throw e; // Throw it again. These we don't want to come up as an exception proxy. // These should end the thread. } catch (java.lang.reflect.InvocationTargetException e) { // This is a wrappered exception. Return the wrappered one so it looks like // it was the real one. (Sometimes the method being invoked is on a // java.lang.reflect.Constructor.newInstance, // which in turn is an InvocationTargetException, so we will go until we don't have an // InvocationTargetException. Throwable t = e; do { t = ((java.lang.reflect.InvocationTargetException) t).getTargetException(); } while (t instanceof java.lang.reflect.InvocationTargetException); sendException(t, valueObject, out); } catch (Throwable e) { sendException(e, valueObject, out); // Turn it into a exception proxy on the client. } finally { // Clear out for GC to work valueObject.set(); parms = null; target = null; aMethod = null; returnType = null; newValue = null; valueSender.clear(); } break; case Commands.INVOKE_WITH_METHOD_PASSED: aClass = null; String methodName = null; Class[] parmTypes = null; target = null; parms = null; returnType = null; aMethod = null; try { Commands.readValue(in, valueObject); aClass = (Class) getInvokableObject(valueObject); // The class that has the method. methodName = in.readUTF(); Commands.readValue(in, valueObject); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); parmTypes = (Class[]) valueSender.getArray(); } else { // It null, so it should be an null. If not, then this is an error. parmTypes = null; } aMethod = aClass.getMethod(methodName, parmTypes); // Now we get the info for the invocation of the method and execute it. Commands.readValue(in, valueObject); target = getInvokableObject(valueObject); Commands.readValue(in, valueObject); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); parms = (Object[]) valueSender.getArray(); } else { // It is all objects or null, so it should be an Object[] or null. If not, then this // is an error. parms = (Object[]) valueObject.anObject; } if (!aMethod.isAccessible()) aMethod.setAccessible( true); // We will allow all to occur. Let access control be handled by IDE and // compiler. newValue = aMethod.invoke(target, parms); returnType = aMethod.getReturnType(); if (returnType.isPrimitive()) { int returnTypeID = server.getIdentityID(returnType); // Need to tell sendObject the correct primitive type. sendObject(newValue, returnTypeID, valueObject, out, true); } else { sendObject( newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Just send the object back. sendObject knows how to iterpret the type } } catch (CommandException e) { throw e; // Throw it again. These we don't want to come up as an exception proxy. // These should end the thread. } catch (java.lang.reflect.InvocationTargetException e) { // This is a wrappered exception. Return the wrappered one so it looks like // it was the real one. (Sometimes the method being invoked is on a // java.lang.reflect.Constructor.newInstance, // which in turn is an InvocationTargetException, so we will go until we don't have an // InvocationTargetException. Throwable t = e; do { t = ((java.lang.reflect.InvocationTargetException) t).getTargetException(); } while (t instanceof java.lang.reflect.InvocationTargetException); sendException(t, valueObject, out); } catch (Throwable e) { sendException(e, valueObject, out); // Turn it into a exception proxy on the client. } finally { aClass = null; methodName = null; parmTypes = null; // Clear out for GC to work valueObject.set(); parms = null; target = null; aMethod = null; returnType = null; newValue = null; valueSender.clear(); } break; case Commands.GET_ARRAY_CONTENTS: try { target = server.getObject(in.readInt()); // Array to get the ids for. valueObject.setArrayIDS( new ArrayContentsRetriever(target), Array.getLength(target), Commands.OBJECT_CLASS); Commands.writeValue(out, valueObject, true); // Write it back as a value command. } catch (CommandException e) { throw e; // Throw it again. These we don't want to come up as an exception proxy. // These should end the thread. } catch (Throwable e) { sendException(e, valueObject, out); // Turn it into a exception proxy on the client. } finally { target = null; valueObject.set(); } break; case Commands.CALLBACK_DONE: try { if (connectionThread != null) { valueObject.set(); Commands.sendErrorCommand(out, Commands.UNKNOWN_COMMAND_SENT, valueObject); } else { try { Commands.readBackValue(in, valueObject, Commands.NO_TYPE_CHECK); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); result = valueSender.getArray(); } else { result = getInvokableObject(valueObject); } doLoop = false; // We need to terminate and return result closeWhenDone = false; // Don't close, we will continue. } catch (CommandErrorException e) { // There was an command error on the other side. This means // connection still good, but don't continue the callback processing. doLoop = false; // We need to terminate and return result closeWhenDone = false; // Don't close, we will continue. throw e; // Let it go on out. } } } finally { valueObject.set(); valueSender.clear(); } break; case Commands.ERROR: try { // Got an error command. Don't know what to do but read the // value and simply print it out. Commands.readValue(in, valueObject); result = getInvokableObject(valueObject); System.out.println("Error sent to server: Result=" + result); // $NON-NLS-1$ } finally { valueObject.set(); } break; case Commands.EXPRESSION_TREE_COMMAND: try { processExpressionCommand(valueObject, valueSender); } finally { valueObject.set(); valueSender.clear(); } break; default: // Unknown command. We don't know how long it is, so we need to shut the connection // down. System.err.println("Error: Invalid cmd send to server: Cmd=" + cmd); // $NON-NLS-1$ doLoop = false; closeWhenDone = true; break; } } } catch (EOFException e) { // This is ok. It means that the connection on the other side was terminated. // So just accept this and go down. } catch (CommandException e) { throw e; } catch (SocketException e) { if (socket != null) throw new UnexpectedExceptionCommandException( false, e); // socket null means a valid close request } catch (Throwable e) { e.printStackTrace(); } finally { if (closeWhenDone) { try { for (Iterator itr = expressionProcessors.values().iterator(); itr.hasNext(); ) { ExpressionProcesserController exp = (ExpressionProcesserController) itr.next(); exp.close(); } } finally { expressionProcessors.clear(); } if (in != null) try { in.close(); } catch (Exception e) { } in = null; if (out != null) try { out.close(); } catch (Exception e) { } out = null; close(); } } if (closeWhenDone && connectionThread != null) server.removeConnectionThread(connectionThread); if (shutdown) server.requestShutdown(); return result; }
public Vector<SyndEntry> crawl() { if (feedid == 1301) { int z = 0; z++; } SyndFeedInput input = new SyndFeedInput(); XmlReader reader = null; Vector<SyndEntry> ret = new Vector<SyndEntry>(); Document doc; try { /* * Document doc = Jsoup.parse(feedurl,10000); * getLogger().info(doc.toString()); */ SyndFeed feed = null; try { feed = input.build(reader = new XmlReader(feedurl)); } catch (Exception fe) { try { System.err.println("from url: " + feedurl); fe.printStackTrace(); doc = Jsoup.parse(feedurl, 10000); feed = input.build(new StringReader(doc.toString())); getLogger().info("Could fix it woith jsoup"); } catch (ExceptionInInitializerError ed) { System.err.println("from url: " + feedurl); ed.printStackTrace(); try { URL url = feedurl; String feedpage = FeedCrawler.readPage(url); feedpage = feedpage .replaceAll("\\&ldquo;", "\"") .replaceAll("“", "\"") .replaceAll("\\&rdquo;", "\"") .replaceAll("”", "\""); System.out.println(feedpage); // feedpage=feedpage.replaceAll("\\&ldquo;", "\""); // reader=new XmlReader(new InputSource(new // StringReader(feedpage)).getCharacterStream()); feed = input.build(new InputSource(new StringReader(feedpage))); getLogger().info("Could fix it with complicatedreader"); } catch (URISyntaxException e) { // TODO Auto-generated catch block System.err.println("from url: " + feedurl); e.printStackTrace(); System.out.println("URL does not work: " + feedurl); } catch (FeedException e) { // TODO Auto-generated catch block System.err.println("from url: " + feedurl); e.printStackTrace(); System.out.println("URL does not work: " + feedurl); } catch (Exception ex) { System.err.println("from url: " + feedurl); ex.printStackTrace(); System.out.println("URL does not work: " + feedurl); } } } for (Iterator<SyndEntry> i = feed.getEntries().iterator(); i.hasNext(); ) { SyndEntry entry = (SyndEntry) i.next(); System.out.println("\t INFOR: Entry\t" + entry.getUri()); if (!entry.getUri().startsWith("http")) { System.out.println("\t ERROR: \t" + entry.getLink()); System.out.println("\t DEBUG: \t" + feedurl); System.out.println("\t FIX: \t"); if (domain.length() > 0) { entry.setLink(domain + entry.getLink()); entry.setUri(domain + entry.getUri()); ret.add(entry); } } else ret.add(entry); getLogger().info(entry.getTitle()); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block getLogger().info("Feed error: " + feedurl); getLogger().info("try with jsoup"); System.err.println("from url: " + feedurl); e.printStackTrace(); try { doc = Jsoup.parse(feedurl, 10000); } catch (IOException e1) { // TODO Auto-generated catch block System.err.println("from url: " + feedurl); e1.printStackTrace(); } } catch (FeedException fe) { getLogger().info("Even jsoup did not work: " + feedurl); System.err.println("from url: " + feedurl); fe.printStackTrace(); } catch (IOException e) { getLogger().info("Feed error: " + feedurl); getLogger().info("try with jsoup"); // TODO Auto-generated catch block System.err.println("from url: " + feedurl); e.printStackTrace(); try { doc = Jsoup.parse(feedurl, 10000); } catch (IOException e2) { // TODO Auto-generated catch block System.err.println("from url: " + feedurl); e2.printStackTrace(); try { getLogger().info("try with jsoup"); doc = Jsoup.parse(feedurl, 10000); getLogger().info(doc.toString()); } catch (IOException e1) { // TODO Auto-generated catch block getLogger().info("once again, jsoup cant do it"); System.err.println("from url: " + feedurl); e1.printStackTrace(); } } } finally { if (reader != null) try { reader.close(); } catch (IOException eg) { getLogger().info("Feed error: " + feedurl); // TODO Auto-generated catch block System.err.println("from url: " + feedurl); eg.printStackTrace(); } } return ret; }
public static void main(String args[]) throws IOException { ConsoleSystemInterface console = null; try { WSwingConsoleInterface.xdim = 100; WSwingConsoleInterface.ydim = 100; console = new WSwingConsoleInterface(); } catch (ExceptionInInitializerError e) { System.out.println("*** Unable to initialize interface."); e.printStackTrace(); System.exit(-1); } InputStream is = Main.class.getResourceAsStream("Tile.json"); long startTime = System.currentTimeMillis(); TileRepository.getInstance().initialize(is); long endTime = System.currentTimeMillis(); System.out.println(endTime - startTime); List<String> tileIds = new ArrayList<>(); tileIds.add("grass"); tileIds.add("tree"); tileIds.add("stone"); TileSet tileSet = new TileSet(tileIds); IMapBuilder mapBuilder = new StreamMapBuilder(tileSet, Main.class.getResourceAsStream("TestMap.txt")); TileMap m = mapBuilder.build(); List<TileMap> floors = new ArrayList<>(); floors.add(m); Dungeon dungeon = new Dungeon(floors); GameObject g1 = new GameObject(0, "guy1"); GameObject g2 = new GameObject(1, "guy2"); g1.addComponent(new LocationComponent(g1, new Point(1, 1), 0)); g2.addComponent(new LocationComponent(g1, new Point(5, 5), 0)); dungeon.addGameObject(g1); dungeon.addGameObject(g2); ((LocationComponent) g1.getGameComponent(LocationComponent.class.getName())) .setFloorLocation(new Point(2, 1)); Random rand = new Random(); int heroX = 1; int heroY = 1; int villainX = 8; int villainY = 8; Entity hero = new Entity("Hero", 100, 100, 18, 10, 5); Entity villain = new Entity("Villain", 50, 50, 10, 10, 6); boolean stop = false; while (!stop) { console.cls(); printMap(m, console); console.print(villainX, villainY, villainChar, ConsoleSystemInterface.RED); console.print(heroX, heroY, heroChar, ConsoleSystemInterface.WHITE); console.print(60, 0, "Hero Hp: " + hero.getMaxHealth() + "/" + hero.getHealth()); console.print(60, 1, "Villain Hp: " + villain.getMaxHealth() + "/" + villain.getHealth()); console.refresh(); CharKey dir = console.inkey(); if (dir.isUpArrow() && m.getTile(heroY - 1, heroX).isPassable()) { heroY--; } if (dir.isDownArrow() && m.getTile(heroY + 1, heroX).isPassable()) { heroY++; } if (dir.isLeftArrow() && m.getTile(heroY, heroX - 1).isPassable()) { heroX--; } if (dir.isRightArrow() && m.getTile(heroY, heroX + 1).isPassable()) { heroX++; } if (dir.code == CharKey.a) { if (adjacent(heroX, villainX, heroY, villainY)) { if (attack(hero, villain)) { villainChar = '='; } } else { System.out.println("Can not attack villain"); } } if (dir.code == CharKey.q) { stop = true; } if (villain.getHealth() > 0) { if (adjacent(heroX, villainX, heroY, villainY)) { if (attack(villain, hero)) { heroChar = '='; } } else { int villainDir = rand.nextInt(4); if (villainDir == 0) { if (m.getTile(villainY - 1, villainX).isPassable()) { villainY--; } } if (villainDir == 1) { if (m.getTile(villainY + 1, villainX).isPassable()) { villainY++; } } if (villainDir == 2) { if (m.getTile(villainY, villainX - 1).isPassable()) { villainX--; } } if (villainDir == 3) { if (m.getTile(villainY, villainX + 1).isPassable()) { villainX++; } } } } } m = null; console = null; System.exit(0); }