public static void main(String args[]) throws IOException { ServerSocket sSocket = new ServerSocket(sPort, 10); // Arguments Handling if (args.length != 1) { System.out.println("Must specify a file-path argument."); } else { String currentDir = System.getProperty("user.dir"); filePath = currentDir + "/src/srcFile/" + args[0]; filename = args[0]; } // Get list of chunks owned chunkOwned(); // Call FileSplitter FileSplitter fs = new FileSplitter(); fs.split(filePath); System.out.println("Waiting for connection"); while (true) { Socket connection = sSocket.accept(); System.out.println("Connection received from " + connection.getInetAddress().getHostName()); new Thread(new MultiThreadServer(connection)).start(); } }
public boolean export(String src) { boolean result = true; String fs = System.getProperty("file.separator"); String contents = getSticker(); try { File file = new File(this.name + "." + src); FileWriter fwrite = new FileWriter(file, true); fwrite.write(contents); fwrite.close(); JOptionPane.showMessageDialog( null, Local.getString("Document was sucessfully created in your Memoranda folder =D")); // Original message said: "Documento creado con exito en su carpeta Memoranda =D" } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog( null, Local.getString("We have failed to create your document =(...")); // Original message said: "NO Logramos crear su documento =(..." } return result; }
// Send File public void sendFile(String chunkName) throws IOException { OutputStream os = null; String currentDir = System.getProperty("user.dir"); chunkName = currentDir + "/src/srcFile/" + chunkName; File myFile = new File(chunkName); byte[] arrby = new byte[(int) myFile.length()]; try { FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(arrby, 0, arrby.length); os = csocket.getOutputStream(); System.out.println("Sending File."); os.write(arrby, 0, arrby.length); os.flush(); System.out.println("File Sent."); // os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // os.close(); } }
private static Charset getDefaultCharset() { try { String encoding = System.getProperty("file.encoding"); return Charset.forName(encoding); } catch (UnsupportedCharsetException e) { return Charset.forName("UTF-8"); } }
public String getSticker() { Map stickers = EventsManager.getStickers(); String result = ""; String nl = System.getProperty("line.separator"); for (Iterator i = stickers.keySet().iterator(); i.hasNext(); ) { String id = (String) i.next(); result += (String) (((Element) stickers.get(id)).getValue()) + nl; } return result; }
@Override public void run() { try { out = new ObjectOutputStream(csocket.getOutputStream()); out.flush(); in = new ObjectInputStream(csocket.getInputStream()); // Look for chunks String currentDir = System.getProperty("user.dir"); File folder = new File(currentDir + "/src/srcFile"); File[] listOfFiles = folder.listFiles(); int fileCount = 0; OutputStream os; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && listOfFiles[i] .getName() .toLowerCase() .contains("chunk")) { // 0 1 10 11 12 13 14 2 20 21 22 23 3 4 5 .... fileCount++; String chunkName = listOfFiles[i].getName().toString(); chunkId = chunkName.substring(chunkName.lastIndexOf('.') + 6); xPayload(chunkId); if ((connTo.equals("2") && Integer.parseInt(chunkId) % noDev == 0) || (connTo.equals("3") && (Integer.parseInt(chunkId) - 1) % noDev == 0) || (connTo.equals("4") && (Integer.parseInt(chunkId) - 2) % noDev == 0) || (connTo.equals("5") && (Integer.parseInt(chunkId) - 3) % noDev == 0) || (connTo.equals("6") && (Integer.parseInt(chunkId) - 4) % noDev == 0)) { System.out.println(chunkName); sendFile(chunkName); } } } xPayload("-1"); System.out.println("All chunks sent."); } catch (IOException ioException) { ioException.printStackTrace(); } finally { // Close connections try { in.close(); out.close(); csocket.close(); System.out.println("Thread closed."); } catch (IOException ioException) { System.out.println("Client " + devId + " disconnected."); } } }
@Override public void close() throws BlockStoreException { try { buffer.force(); if (System.getProperty("os.name").toLowerCase().contains("win")) { log.info("Windows mmap hack: Forcing buffer cleaning"); WindowsMMapHack.forceRelease(buffer); } buffer = null; // Allow it to be GCd and the underlying file mapping to go away. randomAccessFile.close(); } catch (IOException e) { throw new BlockStoreException(e); } }
// List chunks in possession public static void chunkOwned() { // Look for chunks String currentDir = System.getProperty("user.dir"); File folder = new File(currentDir); File[] listOfFiles = folder.listFiles(); int fileCount = 0; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().contains("chunk")) { fileCount = fileCount + 1; } } String[] chunkOwnedArray1 = new String[fileCount]; fileCount = 0; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().contains("chunk")) { String chunkName = listOfFiles[i].getName().toString(); String chunkIdOwned = chunkName.substring(chunkName.lastIndexOf('.') + 6); chunkOwnedArray1[fileCount] = chunkIdOwned; fileCount++; } } chunkOwnedArray = chunkOwnedArray1; }
private void runOnDtlsTransport(StreamConnector connector) throws IOException { DtlsControlImpl dtlsControl = (DtlsControlImpl) getTransportManager().getDtlsControl(this); DtlsTransformEngine engine = dtlsControl.getTransformEngine(); final DtlsPacketTransformer transformer = (DtlsPacketTransformer) engine.getRTPTransformer(); byte[] receiveBuffer = new byte[SCTP_BUFFER_SIZE]; if (LOG_SCTP_PACKETS) { System.setProperty( ConfigurationService.PNAME_SC_HOME_DIR_LOCATION, System.getProperty("java.io.tmpdir")); System.setProperty( ConfigurationService.PNAME_SC_HOME_DIR_NAME, SctpConnection.class.getName()); } synchronized (this) { // FIXME local SCTP port is hardcoded in bridge offer SDP (Jitsi // Meet) sctpSocket = Sctp.createSocket(5000); assocIsUp = false; acceptedIncomingConnection = false; } // Implement output network link for SCTP stack on DTLS transport sctpSocket.setLink( new NetworkLink() { @Override public void onConnOut(SctpSocket s, byte[] packet) throws IOException { if (LOG_SCTP_PACKETS) { LibJitsi.getPacketLoggingService() .logPacket( PacketLoggingService.ProtocolName.ICE4J, new byte[] {0, 0, 0, (byte) debugId}, 5000, new byte[] {0, 0, 0, (byte) (debugId + 1)}, remoteSctpPort, PacketLoggingService.TransportName.UDP, true, packet); } // Send through DTLS transport transformer.sendApplicationData(packet, 0, packet.length); } }); if (logger.isDebugEnabled()) { logger.debug("Connecting SCTP to port: " + remoteSctpPort + " to " + getEndpoint().getID()); } sctpSocket.setNotificationListener(this); sctpSocket.listen(); // FIXME manage threads threadPool.execute( new Runnable() { @Override public void run() { SctpSocket sctpSocket = null; try { // sctpSocket is set to null on close sctpSocket = SctpConnection.this.sctpSocket; while (sctpSocket != null) { if (sctpSocket.accept()) { acceptedIncomingConnection = true; break; } Thread.sleep(100); sctpSocket = SctpConnection.this.sctpSocket; } if (isReady()) { notifySctpConnectionReady(); } } catch (Exception e) { logger.error("Error accepting SCTP connection", e); } if (sctpSocket == null && logger.isInfoEnabled()) { logger.info( "SctpConnection " + getID() + " closed" + " before SctpSocket accept()-ed."); } } }); // Notify that from now on SCTP connection is considered functional sctpSocket.setDataCallback(this); // Setup iceSocket DatagramSocket datagramSocket = connector.getDataSocket(); if (datagramSocket != null) { this.iceSocket = new IceUdpSocketWrapper(datagramSocket); } else { this.iceSocket = new IceTcpSocketWrapper(connector.getDataTCPSocket()); } DatagramPacket rcvPacket = new DatagramPacket(receiveBuffer, 0, receiveBuffer.length); // Receive loop, breaks when SCTP socket is closed try { do { iceSocket.receive(rcvPacket); RawPacket raw = new RawPacket(rcvPacket.getData(), rcvPacket.getOffset(), rcvPacket.getLength()); raw = transformer.reverseTransform(raw); // Check for app data if (raw == null) continue; if (LOG_SCTP_PACKETS) { LibJitsi.getPacketLoggingService() .logPacket( PacketLoggingService.ProtocolName.ICE4J, new byte[] {0, 0, 0, (byte) (debugId + 1)}, remoteSctpPort, new byte[] {0, 0, 0, (byte) debugId}, 5000, PacketLoggingService.TransportName.UDP, false, raw.getBuffer(), raw.getOffset(), raw.getLength()); } // Pass network packet to SCTP stack sctpSocket.onConnIn(raw.getBuffer(), raw.getOffset(), raw.getLength()); } while (true); } finally { // Eventually, close the socket although it should happen from // expire(). synchronized (this) { assocIsUp = false; acceptedIncomingConnection = false; if (sctpSocket != null) { sctpSocket.close(); sctpSocket = null; } } } }
public class RehandshakeFinished { /* * Enables logging of the SSLEngine operations. */ private static boolean logging = true; /* * Enables the JSSE system debugging system property: * * -Djavax.net.debug=all * * This gives a lot of low-level information about operations underway, * including specific handshake messages, and might be best examined * after gaining some familiarity with this application. */ private static boolean debug = false; private static SSLContext sslc; private SSLEngine clientEngine; // client Engine private ByteBuffer clientOut; // write side of clientEngine private ByteBuffer clientIn; // read side of clientEngine private SSLEngine serverEngine; // server Engine private ByteBuffer serverOut; // write side of serverEngine private ByteBuffer serverIn; // read side of serverEngine /* * For data transport, this example uses local ByteBuffers. This * isn't really useful, but the purpose of this example is to show * SSLEngine concepts, not how to do network transport. */ private ByteBuffer cTOs; // "reliable" transport client->server private ByteBuffer sTOc; // "reliable" transport server->client /* * The following is to set up the keystores. */ private static String pathToStores = "../../../../../../../etc"; private static String keyStoreFile = "keystore"; private static String trustStoreFile = "truststore"; private static String passwd = "passphrase"; private static String keyFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + keyStoreFile; private static String trustFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + trustStoreFile; private static Exception loadException = null; static { try { KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ts = KeyStore.getInstance("JKS"); char[] passphrase = "passphrase".toCharArray(); ks.load(new FileInputStream(keyFilename), passphrase); ts.load(new FileInputStream(trustFilename), passphrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passphrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ts); SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); sslc = sslCtx; } catch (Exception e) { loadException = e; } } /* * Main entry point for this test. */ public static void main(String args[]) throws Exception { if (debug) { System.setProperty("javax.net.debug", "all"); } if (loadException != null) { throw loadException; } // Prime the session cache with a good session // Second connection should be a simple session resumption. if ((new RehandshakeFinished().runTest()) != new RehandshakeFinished().runRehandshake()) { throw new Exception("Sessions not equivalent"); } System.out.println("Test Passed."); } private void checkResult( SSLEngine engine, SSLEngineResult result, HandshakeStatus rqdHsStatus, boolean consumed, boolean produced) throws Exception { HandshakeStatus hsStatus = result.getHandshakeStatus(); if (hsStatus == HandshakeStatus.NEED_TASK) { Runnable runnable; while ((runnable = engine.getDelegatedTask()) != null) { runnable.run(); } hsStatus = engine.getHandshakeStatus(); } if (hsStatus != rqdHsStatus) { throw new Exception("Required " + rqdHsStatus + ", got " + hsStatus); } int bc = result.bytesConsumed(); int bp = result.bytesProduced(); if (consumed) { if (bc <= 0) { throw new Exception("Should have consumed bytes"); } } else { if (bc > 0) { throw new Exception("Should not have consumed bytes"); } } if (produced) { if (bp <= 0) { throw new Exception("Should have produced bytes"); } } else { if (bp > 0) { throw new Exception("Should not have produced bytes"); } } } private SSLSession runRehandshake() throws Exception { log("\n\n=============================================="); log("Staring actual test."); createSSLEngines(); createBuffers(); SSLEngineResult result; log("Client's ClientHello"); checkResult( clientEngine, clientEngine.wrap(clientOut, cTOs), HandshakeStatus.NEED_UNWRAP, false, true); cTOs.flip(); checkResult( serverEngine, serverEngine.unwrap(cTOs, serverIn), HandshakeStatus.NEED_WRAP, true, false); cTOs.compact(); log("Server's ServerHello/ServerHelloDone"); checkResult( serverEngine, serverEngine.wrap(serverOut, sTOc), HandshakeStatus.NEED_WRAP, false, true); sTOc.flip(); checkResult( clientEngine, clientEngine.unwrap(sTOc, clientIn), HandshakeStatus.NEED_UNWRAP, true, false); sTOc.compact(); log("Server's CCS"); checkResult( serverEngine, serverEngine.wrap(serverOut, sTOc), HandshakeStatus.NEED_WRAP, false, true); sTOc.flip(); checkResult( clientEngine, clientEngine.unwrap(sTOc, clientIn), HandshakeStatus.NEED_UNWRAP, true, false); sTOc.compact(); log("Server's FINISHED"); checkResult( serverEngine, serverEngine.wrap(serverOut, sTOc), HandshakeStatus.NEED_UNWRAP, false, true); sTOc.flip(); checkResult( clientEngine, clientEngine.unwrap(sTOc, clientIn), HandshakeStatus.NEED_WRAP, true, false); sTOc.compact(); log("Client's CCS"); checkResult( clientEngine, clientEngine.wrap(clientOut, cTOs), HandshakeStatus.NEED_WRAP, false, true); cTOs.flip(); checkResult( serverEngine, serverEngine.unwrap(cTOs, serverIn), HandshakeStatus.NEED_UNWRAP, true, false); cTOs.compact(); log("Client's FINISHED should trigger FINISHED messages all around."); checkResult( clientEngine, clientEngine.wrap(clientOut, cTOs), HandshakeStatus.FINISHED, false, true); cTOs.flip(); checkResult( serverEngine, serverEngine.unwrap(cTOs, serverIn), HandshakeStatus.FINISHED, true, false); cTOs.compact(); return clientEngine.getSession(); } /* * Run the test. * * Sit in a tight loop, both engines calling wrap/unwrap regardless * of whether data is available or not. We do this until both engines * report back they are closed. * * The main loop handles all of the I/O phases of the SSLEngine's * lifetime: * * initial handshaking * application data transfer * engine closing * * One could easily separate these phases into separate * sections of code. */ private SSLSession runTest() throws Exception { boolean dataDone = false; createSSLEngines(); createBuffers(); SSLEngineResult clientResult; // results from client's last operation SSLEngineResult serverResult; // results from server's last operation /* * Examining the SSLEngineResults could be much more involved, * and may alter the overall flow of the application. * * For example, if we received a BUFFER_OVERFLOW when trying * to write to the output pipe, we could reallocate a larger * pipe, but instead we wait for the peer to drain it. */ while (!isEngineClosed(clientEngine) || !isEngineClosed(serverEngine)) { log("================"); clientResult = clientEngine.wrap(clientOut, cTOs); log("client wrap: ", clientResult); runDelegatedTasks(clientResult, clientEngine); serverResult = serverEngine.wrap(serverOut, sTOc); log("server wrap: ", serverResult); runDelegatedTasks(serverResult, serverEngine); cTOs.flip(); sTOc.flip(); log("----"); clientResult = clientEngine.unwrap(sTOc, clientIn); log("client unwrap: ", clientResult); runDelegatedTasks(clientResult, clientEngine); serverResult = serverEngine.unwrap(cTOs, serverIn); log("server unwrap: ", serverResult); runDelegatedTasks(serverResult, serverEngine); cTOs.compact(); sTOc.compact(); /* * After we've transfered all application data between the client * and server, we close the clientEngine's outbound stream. * This generates a close_notify handshake message, which the * server engine receives and responds by closing itself. */ if (!dataDone && (clientOut.limit() == serverIn.position()) && (serverOut.limit() == clientIn.position())) { /* * A sanity check to ensure we got what was sent. */ checkTransfer(serverOut, clientIn); checkTransfer(clientOut, serverIn); log("\tClosing clientEngine's *OUTBOUND*..."); clientEngine.closeOutbound(); dataDone = true; } } return clientEngine.getSession(); } /* * Using the SSLContext created during object creation, * create/configure the SSLEngines we'll use for this test. */ private void createSSLEngines() throws Exception { /* * Configure the serverEngine to act as a server in the SSL/TLS * handshake. Also, require SSL client authentication. */ serverEngine = sslc.createSSLEngine(); serverEngine.setUseClientMode(false); serverEngine.setNeedClientAuth(true); /* * Similar to above, but using client mode instead. */ clientEngine = sslc.createSSLEngine("client", 80); clientEngine.setUseClientMode(true); } /* * Create and size the buffers appropriately. */ private void createBuffers() { /* * We'll assume the buffer sizes are the same * between client and server. */ SSLSession session = clientEngine.getSession(); int appBufferMax = session.getApplicationBufferSize(); int netBufferMax = session.getPacketBufferSize(); /* * We'll make the input buffers a bit bigger than the max needed * size, so that unwrap()s following a successful data transfer * won't generate BUFFER_OVERFLOWS. * * We'll use a mix of direct and indirect ByteBuffers for * tutorial purposes only. In reality, only use direct * ByteBuffers when they give a clear performance enhancement. */ clientIn = ByteBuffer.allocate(appBufferMax + 50); serverIn = ByteBuffer.allocate(appBufferMax + 50); cTOs = ByteBuffer.allocateDirect(netBufferMax); sTOc = ByteBuffer.allocateDirect(netBufferMax); clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); } /* * If the result indicates that we have outstanding tasks to do, * go ahead and run them in this thread. */ private static void runDelegatedTasks(SSLEngineResult result, SSLEngine engine) throws Exception { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable; while ((runnable = engine.getDelegatedTask()) != null) { log("\trunning delegated task..."); runnable.run(); } HandshakeStatus hsStatus = engine.getHandshakeStatus(); if (hsStatus == HandshakeStatus.NEED_TASK) { throw new Exception("handshake shouldn't need additional tasks"); } log("\tnew HandshakeStatus: " + hsStatus); } } private static boolean isEngineClosed(SSLEngine engine) { return (engine.isOutboundDone() && engine.isInboundDone()); } /* * Simple check to make sure everything came across as expected. */ private static void checkTransfer(ByteBuffer a, ByteBuffer b) throws Exception { a.flip(); b.flip(); if (!a.equals(b)) { throw new Exception("Data didn't transfer cleanly"); } else { log("\tData transferred cleanly"); } a.position(a.limit()); b.position(b.limit()); a.limit(a.capacity()); b.limit(b.capacity()); } /* * Logging code */ private static boolean resultOnce = true; private static void log(String str, SSLEngineResult result) { if (!logging) { return; } if (resultOnce) { resultOnce = false; System.out.println( "The format of the SSLEngineResult is: \n" + "\t\"getStatus() / getHandshakeStatus()\" +\n" + "\t\"bytesConsumed() / bytesProduced()\"\n"); } HandshakeStatus hsStatus = result.getHandshakeStatus(); log( str + result.getStatus() + "/" + hsStatus + ", " + result.bytesConsumed() + "/" + result.bytesProduced() + " bytes"); if (hsStatus == HandshakeStatus.FINISHED) { log("\t...ready for application data"); } } private static void log(String str) { if (logging) { System.out.println(str); } } }
public static void main(String[] args) throws Throwable { final int itrs = Integer.getInteger("iterations", 100000); // final int itrs = Integer.getInteger("iterations", 12); final int size = Integer.getInteger("size", 2048); final int subsize = Integer.getInteger("subsize", 128); final int maxchar = Integer.getInteger("maxchar", 128); final String regex = System.getProperty("filter"); final Pattern filter = (regex == null) ? null : Pattern.compile(regex); final boolean useSecurityManager = Boolean.getBoolean("SecurityManager"); if (useSecurityManager) System.setSecurityManager(new PermissiveSecurityManger()); final Random rnd = new Random(); String[] csns = new String[] { "Big5", "Johab", "EUC_CN", "EUC_KR", "MS932", "MS936", "MS949", "MS950", "GBK", "Big5_HKSCS", "Big5_HKSCS_2001", "Big5_Solaris", "MS950_HKSCS", "MS950_HKSCS_XP", "IBM1364", "IBM1381", "IBM1383", "IBM930", "IBM933", "IBM935", "IBM937", "IBM939", "IBM942", "IBM943", "IBM948", "IBM949", "IBM950", "IBM970", }; ArrayList<long[]> sum = new ArrayList<>(); for (final String csn : csns) { final Charset cs = Charset.forName(csn); List<Integer> cps = new ArrayList<>(0x4000); int off = 0; int cp = 0; int n = 0; CharsetEncoder enc = cs.newEncoder(); while (cp < 0x10000 && n < cps.size()) { if (enc.canEncode((char) cp)) { cps.add(cp); n++; } cp++; } Collections.shuffle(cps); char[] ca = new char[cps.size()]; for (int i = 0; i < cps.size(); i++) ca[i] = (char) (int) cps.get(i); System.out.printf("%n--------%s---------%n", csn); for (int sz = 8; sz <= 2048; sz *= 2) { System.out.printf(" [len=%d]%n", sz); final char[] chars = Arrays.copyOf(ca, sz); final String str = new String(chars); final byte[] bs = str.getBytes(cs); Job[] jobs = { new Job("String decode: csn") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) new String(bs, csn); } }, new Job("String decode: cs") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) new String(bs, cs); } }, new Job("String encode: csn") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) str.getBytes(csn); } }, new Job("String encode: cs") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) str.getBytes(cs); } }, }; sum.add(time(jobs)); } } }
static boolean onSolarisOrLinux() { String osName = System.getProperty("os.name"); return osName.startsWith("SunOS") || osName.startsWith("Linux"); }
/** * This class contains some static methods to retrieve information on the Pokepon package itself. * THIS IS A VERY DELICATE CLASS: HANDLE WITH CARE! * * @author Giacomo Parolini */ public class Meta { public static final char DIRSEP = '/'; // probably superfluous /** * Working directory of the pokepon class tree; if game is launched from JAR, this is the * directory where the JAR resides; else, it is the directory containing 'pokepon'. */ private static Path cwd; static { String tmp = Meta.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // Strip the leading slash if on windows if (tmp.matches("^/[A-Z]:/.*")) { tmp = tmp.substring(1); } cwd = Paths.get(tmp); } private static URL cwdURL; public static final boolean LAUNCHED_FROM_JAR = cwd.toString().endsWith(".jar"); /** Are we on Windows or on POSIX os? */ public static final boolean IS_WINDOWS = System.getProperty("os.name").toUpperCase().contains("WIN"); /** Directory containing variable data (teams, confs, ...) */ public static final String APPDATA_DIR = (IS_WINDOWS ? System.getenv("APPDATA") + DIRSEP : System.getenv("HOME") + DIRSEP + ".") + "pokepon"; static { // if launched from a jar, use the parent as cwd if (LAUNCHED_FROM_JAR) cwd = cwd.getParent(); if (Debug.on) printDebug("[Meta] cwd: " + cwd + "\nLaunched from jar: " + LAUNCHED_FROM_JAR); } private static String cwdStr = "file://" + cwd.toString(); public static URL getCwd() { if (cwdURL != null) return cwdURL; try { cwdURL = new URL(cwdStr); return cwdURL; } catch (MalformedURLException e) { return null; } } public static Path getCwdPath() { return cwd; } private static URL getSubURL(final String subdir) { if (LAUNCHED_FROM_JAR) { if (Debug.pedantic) printDebug( "[Meta.getSubURL(" + POKEPON_ROOTDIR + DIRSEP + subdir + ")]: " + Meta.class.getClassLoader().getResource(POKEPON_ROOTDIR + DIRSEP + subdir)); return Meta.class.getClassLoader().getResource(POKEPON_ROOTDIR + DIRSEP + subdir); } else { try { return new URL( getCwd().getProtocol() + "://" + getCwd().getPath() + DIRSEP + POKEPON_ROOTDIR + DIRSEP + subdir); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } private static URL getAppDataURL(final String subdir) { try { if (Debug.pedantic) printDebug( "[Meta.getAppDataURL(" + subdir + ")]: " + "file://" + APPDATA_DIR + DIRSEP + subdir); return new URL("file://" + APPDATA_DIR + DIRSEP + subdir); } catch (MalformedURLException e) { throw new RuntimeException(e); } } /** Returns the URL of the package root */ public static URL getRootURL() { return getSubURL(""); } /** Returns the URL of the pony directory. */ public static URL getPonyURL() { return getSubURL(PONY_DIR); } /** Returns the URL of the move directory. */ public static URL getMoveURL() { return getSubURL(MOVE_DIR); } /** Returns the URL of the item directory. */ public static URL getItemURL() { return getSubURL(ITEM_DIR); } /** Returns the URL of the ability directory. */ public static URL getAbilityURL() { return getSubURL(ABILITY_DIR); } /** Returns the URL of the save directory. NOTE: this is in local AppData */ public static URL getSaveURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(SAVE_DIR) : getSubURL("data" + DIRSEP + SAVE_DIR); } /** Returns the URL of the battle directory. */ public static URL getBattleURL() { return getSubURL(BATTLE_DIR); } /** Returns the URL of the data directory. NOTE: this is in local AppData */ public static URL getDataURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(DATA_DIR) : getSubURL("data"); } /** Returns the URL of the resources directory */ public static URL getResourcesURL() { return getSubURL(RESOURCE_DIR); } /** Returns the URL of the sprites directory */ public static URL getSpritesURL() { return getSubURL(SPRITE_DIR); } /** Returns the URL of the tokens directory */ public static URL getTokensURL() { return getSubURL(TOKEN_DIR); } /** Returns the URL of the hazards directory */ public static URL getHazardsURL() { return getSubURL(HAZARD_DIR); } /** Returns the URL of the net directory */ public static URL getNetURL() { return getSubURL(NET_DIR); } /** Returns the URL of the audiofiles directory */ public static URL getAudioURL() { return getSubURL(AUDIO_DIR); } /** Returns the URL of the battle records directory. THIS IS IN APPDATA */ public static URL getBattleRecordsURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(BATTLE_RECORDS_DIR) : getSubURL("data" + DIRSEP + BATTLE_RECORDS_DIR); } /** Takes a string and hides its extension */ public static String hideExtension(final String str) { String[] arr = str.split("\\."); if (arr.length <= 1) return str; // there was no "." in str. StringBuilder sb = new StringBuilder(""); for (int i = 0; i < arr.length - 1; ++i) { if (sb.length() > 0) sb.append("."); sb.append(arr[i]); } return sb.toString(); } /** * Given a simple class name, returns the package to which it belongs (stripped of the initial * "pokepon.") or null if no file is found; NOTE: the only searched packages are pony, move, * ability and item. */ public static String getPackage(final String className) { if (findSubclassesNames(complete(PONY_DIR), Pony.class).contains(className)) return "pony"; if (findSubclassesNames(complete(MOVE_DIR), Move.class).contains(className)) return "move"; if (findSubclassesNames(complete(ABILITY_DIR), Ability.class).contains(className)) return "ability"; if (findSubclassesNames(complete(ITEM_DIR), Item.class).contains(className)) return "item"; return null; } /** * Takes a path name and appends it to POKEPON_ROOTDIR to return a valid "relatively absolute" * path (id est: absolute relatively to the java classpath directory) */ public static String complete(final String path) { return POKEPON_ROOTDIR + DIRSEP + path; } /** * This is used to cross-platform-ly locate resources in JAR file; to safely find a resource, do: * getClass().getResource(Meta.complete2(Meta.SOME_DIR)+"/"+resourceName); */ public static String complete2(String path) { String cmp = DIRSEP + complete(path); if (cmp.matches("^/[A-Z]:/.*")) return cmp.substring(1); else return cmp; } /** * Convert all special tags in a string to local URL (e.g [sprite: NameOfPony] => * file://path/to/local/sprite.png); allowed special tags are: sprite, type, movetype * * @return The converted string */ public static String toLocalURL(final String msg) { StringBuilder converted = new StringBuilder(); boolean parsingTag = false; boolean inTagName = true; StringBuilder tagName = new StringBuilder(10); StringBuilder tagArg = new StringBuilder(30); for (int i = 0; i < msg.length(); ++i) { char c = msg.charAt(i); switch (c) { case '[': if (!parsingTag) { parsingTag = true; } else { if (inTagName) tagName.append(c); else tagArg.append(c); } break; case ']': if (parsingTag) { parsingTag = false; converted.append( convertLocalURLTag(tagName.toString().trim(), tagArg.toString().trim())); tagName.setLength(0); tagArg.setLength(0); inTagName = true; } else { converted.append(c); } break; case ':': if (parsingTag) { if (inTagName) inTagName = false; else tagArg.append(c); } else { converted.append(c); } break; default: if (parsingTag) { if (inTagName) tagName.append(c); else tagArg.append(c); } else { converted.append(c); } } } return converted.toString(); } private static String convertLocalURLTag(final String name, final String arg) { if (name.equals("sprite")) { try { Pony tmp = PonyCreator.create(arg); return "" + tmp.getFrontSprite(); } catch (ReflectiveOperationException e) { printDebug("[Meta.toLocalURL] Error creating pony " + arg + ": " + e); e.printStackTrace(); } } else if (name.equals("type")) { try { return "" + pokepon.enums.Type.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating type " + arg); e.printStackTrace(); } } else if (name.equals("movetype")) { try { return "" + Move.MoveType.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating movetype " + arg); e.printStackTrace(); } } return ""; } /** * Searches for the directory 'dirPath'; if not found, tries to create it, then returns a File * object for that directory. */ public static File ensureDirExists(final String dirPath) { File dirpath = new File(dirPath); if (!dirpath.isDirectory()) { if (!dirpath.exists()) { printDebug("[Meta] " + dirpath + " does not exist: creating it..."); try { Files.createDirectories(Paths.get(dirpath.getPath())); return dirpath; } catch (IOException e) { printDebug("[Meta] Exception while creating directory:"); e.printStackTrace(); return null; } } else { printDebug( "[Meta] Error: path `" + dirpath + "' is not a valid directory path, and could not create it."); return null; } } else return dirpath; } /** * Checks if a given file exists and, if not, create it by copying a default template from * resources; used to create default conf files. * * @param file The path of the file that needs to exist * @param template The path of the template for the file */ public static void ensureFileExists(final String file, final String template) { if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) { if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one."); InputStream stream = Meta.class.getResourceAsStream(template); if (stream == null) { printDebug( "[ WARNING ] template for " + template + " not found. Won't create a default " + file + "."); } else { int readBytes; byte[] buffer = new byte[4096]; try (OutputStream outStream = new FileOutputStream(new File(file))) { while ((readBytes = stream.read(buffer)) > 0) { outStream.write(buffer, 0, readBytes); } if (Debug.on) printDebug("[Meta] created default file " + file + " from " + template + "."); } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException ignore) { } } } } else { if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + "."); } } /** Path of the Pokepon root directory, relative to the java classpath */ public static final String POKEPON_ROOTDIR = "pokepon"; // These are relative to POKEPON_ROOTDIR public static final String PONY_DIR = "pony"; public static final String MOVE_DIR = "move"; public static final String HAZARD_DIR = "move" + DIRSEP + "hazard"; public static final String BATTLE_DIR = "battle"; public static final String MAIN_DIR = "main"; public static final String ENUM_DIR = "enums"; public static final String ITEM_DIR = "item"; public static final String ABILITY_DIR = "ability"; public static final String RESOURCE_DIR = "resources"; public static final String SPRITE_DIR = "resources" + DIRSEP + "sprites"; public static final String TOKEN_DIR = "resources" + DIRSEP + "tokens"; public static final String AUDIO_DIR = "resources" + DIRSEP + "audio"; public static final String NET_DIR = "net"; public static final String ANIMATION_DIR = "gui" + DIRSEP + "animation"; // These are in APPDATA when the game is launched from jar (i.e. in release version) public static final String DATA_DIR = ""; public static final String SAVE_DIR = "teams"; public static final String BATTLE_RECORDS_DIR = "battle_records"; public static void main(String[] args) { consoleHeader(" META "); printMsg("Rootdir:\t" + getRootURL()); printMsg("PonyURL:\t" + getPonyURL()); printMsg("MoveURL:\t" + getMoveURL()); printMsg("HazardURL:\t" + getHazardsURL()); printMsg("BattleURL:\t" + getBattleURL()); printMsg("ItemURL:\t" + getItemURL()); printMsg("AbilityURL:\t" + getAbilityURL()); printMsg("ResourcesURL:\t" + getResourcesURL()); printMsg("SpritesURL:\t" + getSpritesURL()); printMsg("TokensURL:\t" + getTokensURL()); printMsg("AudioURL:\t" + getAudioURL()); printMsg("NetURL: \t" + getNetURL()); printMsg("DataURL:\t" + getDataURL()); printMsg("SaveURL:\t" + getSaveURL()); } }
public class SHA1Verification { public static final String dirname = "D:" + System.getProperty("file.separator") + "testdir"; public static void main(String[] args) { if (!new File(dirname).exists()) createTestFiles(); runTests(); } public static void createTestFiles() { try { System.out.println("Creating test files ... "); Random rand = new Random(); String rootname = "f-"; long[] sizes = {0, 1, 50000000}; File testdir = new File(dirname); FileUtil.mkdirs(testdir); for (int i = 0; i < sizes.length; i++) { long size = sizes[i]; File file = new File(testdir, rootname + String.valueOf(size)); System.out.println(file.getName() + "..."); FileChannel fc = new RandomAccessFile(file, "rw").getChannel(); long position = 0; while (position < size) { long remaining = size - position; if (remaining > 1024000) remaining = 1024000; byte[] buffer = new byte[new Long(remaining).intValue()]; rand.nextBytes(buffer); ByteBuffer bb = ByteBuffer.wrap(buffer); position += fc.write(bb); } fc.close(); } System.out.println("DONE\n"); } catch (Exception e) { Debug.printStackTrace(e); } } public static void runTests() { try { // SHA1 sha1Jmule = new SHA1(); MessageDigest sha1Sun = MessageDigest.getInstance("SHA-1"); SHA1 sha1Gudy = new SHA1(); // SHA1Az shaGudyResume = new SHA1Az(); ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); File dir = new File(dirname); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { FileChannel fc = new RandomAccessFile(files[i], "r").getChannel(); System.out.println("Testing " + files[i].getName() + " ..."); while (fc.position() < fc.size()) { fc.read(buffer); buffer.flip(); byte[] raw = new byte[buffer.limit()]; System.arraycopy(buffer.array(), 0, raw, 0, raw.length); sha1Gudy.update(buffer); sha1Gudy.saveState(); ByteBuffer bb = ByteBuffer.wrap(new byte[56081]); sha1Gudy.digest(bb); sha1Gudy.restoreState(); sha1Sun.update(raw); buffer.clear(); } byte[] sun = sha1Sun.digest(); sha1Sun.reset(); byte[] gudy = sha1Gudy.digest(); sha1Gudy.reset(); if (Arrays.equals(sun, gudy)) { System.out.println(" SHA1-Gudy: OK"); } else { System.out.println(" SHA1-Gudy: FAILED"); } buffer.clear(); fc.close(); System.out.println(); } } catch (Throwable e) { Debug.printStackTrace(e); } } }
/* * Prevents construction of a FileManager object * without using the getInstance method */ private FileManager() { this.setBasePath(System.getProperty("user.home")); }