Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 35.84 KB | None | 0 0
  1. package Criptoconsola;
  2.  
  3. import java.io.*;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. import java.net.URL;
  7. import java.nio.file.*;
  8. import java.util.*;
  9.  
  10. import java.security.*;
  11. import java.security.spec.X509EncodedKeySpec;
  12. import javax.crypto.*;
  13. import javax.crypto.spec.*;
  14.  
  15. public class Criptoconsola {
  16.  
  17. static GestorDescarregas gd = new GestorDescarregas();
  18.  
  19. static final int tamanyBlocCopia = 512;
  20. static final int tamanyBlocHash = 512;
  21. static final int tamanyBlocEncriptacio = 128;
  22. static final int tamanyBlocDescarrega = 4;
  23. static final int tamanyBlocEncriptacioAsimetrica = 16;
  24.  
  25. static Process process;
  26.  
  27. static final String extensioXifrat = ".xifrat";
  28. static final String extensioXifratAsimetric = ".xifratAsimetric";
  29.  
  30. static final int longitutVectorInicialitzacio = 1024;
  31.  
  32. static final int tamanyBlocEnviament = 64;
  33. static final int portEnviament = 5;
  34.  
  35. public static void main(String[] args) throws Exception {
  36.  
  37. PrintStream o = System.out;
  38.  
  39. InputStreamReader r = new InputStreamReader(System.in);
  40. java.io.BufferedReader i = new BufferedReader(r);
  41.  
  42. o.println("+---------------------------------------------+");
  43. o.println("| Criptoconsola 1.0 |");
  44. o.println("+---------------------------------------------+");
  45. o.println("");
  46.  
  47. Path directoriTreball = obtenirDirectoriArrel();
  48. String separadorDirectoris = obtenirSeparadorDirectoris();
  49.  
  50. if (directoriTreball == null) {
  51. System.out.println("ERROR: No es pot obtenir el directori arrel");
  52. System.exit(-1);
  53. }
  54.  
  55. boolean fi = false;
  56.  
  57. while (!fi) {
  58. // Mostrar prompt
  59.  
  60. String ds = directoriTreball.toString();
  61. o.print(ds + ">");
  62.  
  63. // Obtenir linia de comanda
  64. String liniaComanda = i.readLine();
  65.  
  66. // Parsejar comanda
  67. String parts[] = liniaComanda.split(" ");
  68.  
  69. // Processar comanda
  70. String comanda = parts[0].toUpperCase();
  71.  
  72. if (comanda.equals("AJUDA")) {
  73. o.println("");
  74. o.println("AJUDA");
  75. o.println("");
  76. o.println(" Mostra aquesta ajuda");
  77. o.println("");
  78. o.println("COPIAR <nomfitxer1> <nomfitxer2>");
  79. o.println("");
  80. o.println(" Fa una copia del fitxer1 i la desa com fitxer2, sobreescrivint-lo si existeix");
  81. o.println("");
  82. o.println("ELIMINAR <nomfitxer>");
  83. o.println("");
  84. o.println(" Elimina el fitxer indicat. Demana confirmacio");
  85. o.println("");
  86. o.println("CD <nomdirectori>");
  87. o.println("");
  88. o.println(" Canvia el directori de treball al directori indicat");
  89. o.println("");
  90. o.println("DIR");
  91. o.println("");
  92. o.println(" Mostra els continguts del directori de treball");
  93. o.println("");
  94. o.println("HASH <nomfitxer>");
  95. o.println("");
  96. o.println(" Calcula i mostra el hash MD5 del fitxer");
  97. o.println("");
  98. o.println("ENCRIPTA <nomfitxer1> <nomfitxer2>");
  99. o.println("");
  100. o.println(" Encripta el fitxer1 i el deixa com fitxer2, sobreescrivint-lo si existeix. Demana una contrasenya");
  101. o.println("");
  102. o.println("SORTIR");
  103. o.println("");
  104. o.println(" Finalitza la sessio");
  105. o.println("");
  106.  
  107. } else if (comanda.equals("DIR")) {
  108. Object[] paths = Files.list(directoriTreball).toArray();
  109. //
  110. for (Object c : paths) {
  111. //Path p = (Path)paths[i];
  112.  
  113. System.out.println(c);
  114. }
  115.  
  116. } else if (comanda.equals("CD")) {
  117. String subdirectori = parts[1];
  118. File f = new File(directoriTreball + separadorDirectoris + subdirectori);
  119.  
  120. if (subdirectori.equals("..")) {
  121. if (f.isDirectory() && directoriTreball.getParent() == null) {
  122. System.out.println("Error: La ruta introducida no existe o es un fichero.");
  123. } else {
  124. directoriTreball = directoriTreball.getParent();
  125. }
  126. } else {
  127. if (!f.exists()) {
  128. System.out.println("La ruta introducida no existe");
  129. } else if (f.isDirectory()) {
  130. directoriTreball = directoriTreball.resolve(subdirectori);
  131. } else {
  132. System.out.println("Error: La ruta introducida es un fichero");
  133. }
  134.  
  135. }
  136.  
  137. } else if (comanda.equals("COPIAR")) {
  138. Scanner sc = new Scanner(System.in);
  139. boolean error = false;
  140.  
  141. String nomFitxer1 = parts[1];
  142. String nomFitxer2 = parts[2];
  143.  
  144. String rutaFitxer1 = directoriTreball.toString() + separadorDirectoris + nomFitxer1;
  145. String rutaFitxer2 = directoriTreball.toString() + separadorDirectoris + nomFitxer2;
  146. File f1 = new File(rutaFitxer1);
  147. File f2 = new File(rutaFitxer2);
  148.  
  149. if (!f1.exists()) {
  150. o.println("El fichero 1 no existe");
  151. error = true;
  152. } else if (!f1.canRead()) {
  153. o.println("El fichero 1 no tiene privilegio de lectura");
  154. error = true;
  155. } else if (!f2.createNewFile()) {
  156. o.println("El fichero 2 no se puede crear");
  157. error = true;
  158. } else if (f2.exists() && !f2.canWrite()) {
  159. o.println("El fichero 2 existe y no tiene privilegio de escritura");
  160. error = true;
  161. }
  162.  
  163. if (f2.exists() && f2.canWrite()) {
  164. System.out.println("Desea sobreescribir el fichero?");
  165. String respuesta = sc.nextLine();
  166. if (respuesta.toLowerCase() == "no") {
  167. error = false;
  168. o.println("No se sobrescribe.");
  169. } else {
  170. o.println("Sobreescribir archivo.");
  171. }
  172. }
  173.  
  174. if (error == false) {
  175. try {
  176. FileInputStream streamFitxer1 = new FileInputStream(rutaFitxer1);
  177. FileOutputStream streamFitxer2 = new FileOutputStream(rutaFitxer2);
  178.  
  179. byte[] bloc = new byte[tamanyBlocCopia];
  180.  
  181. boolean fiCopia = false;
  182. int llegits;
  183. while (!fiCopia) {
  184.  
  185. while ((llegits = streamFitxer1.read(bloc)) > 0) {
  186. streamFitxer2.write(bloc, 0, llegits);
  187. }
  188. fiCopia = true;
  189. }
  190.  
  191. streamFitxer1.close();
  192. streamFitxer2.close();
  193.  
  194. } catch (Exception e) {
  195. System.out.println("Error en la ejecucion");
  196. }
  197. }
  198.  
  199. } else if (comanda.equals("ELIMINAR")) {
  200. boolean encontrado = false;
  201. String nomFitxer = parts[1];
  202. String rutaFitxer = directoriTreball.toString() + separadorDirectoris + nomFitxer;
  203. Scanner sc = new Scanner(System.in);
  204.  
  205. File fitxer = new File(rutaFitxer);
  206. if (!fitxer.exists()) {
  207. System.out.println("El fichero no existe");
  208. } else {
  209. System.out.println("El fichero existe, desea borrarlo?");
  210. String respuesta = sc.nextLine();
  211. if (respuesta.toLowerCase().equals("si")) {
  212. encontrado = fitxer.delete();
  213. }
  214. }
  215. if (encontrado == false) {
  216. System.out.println("El fichero no ha sido borrado");
  217. }
  218.  
  219. } else if (comanda.equals("HASH")) {
  220. String nomFitxer = parts[1];
  221. String rutaFitxer = directoriTreball.toString() + separadorDirectoris + nomFitxer;
  222.  
  223. MessageDigest md = MessageDigest.getInstance("MD5");
  224. //
  225. FileInputStream streamFitxer = new FileInputStream(rutaFitxer);
  226. //
  227. boolean fiFitxer = false;
  228. //
  229. byte[] bloc = new byte[tamanyBlocHash];
  230. //
  231. while (!fiFitxer) {
  232. int llegits = streamFitxer.read(bloc);
  233. //
  234. if (llegits >= 0) {
  235. md.update(bloc, 0, llegits);
  236.  
  237. } else {
  238. fiFitxer = true;
  239. }
  240. //
  241. }
  242. //
  243. byte[] hash = md.digest();
  244. //
  245. String textHash = byteArrayToHexString(hash);
  246. //
  247. streamFitxer.close();
  248. //
  249. o.println("Resultat: " + textHash);
  250.  
  251. } else if (comanda.equals("ENCRIPTAR")) {
  252.  
  253. String nomFitxer1 = parts[1];
  254. String nomFitxer2 = nomFitxer1 + extensioXifrat;
  255.  
  256. String rutaFitxer1 = directoriTreball.toString() + separadorDirectoris + nomFitxer1;
  257. String rutaFitxer2 = directoriTreball.toString() + separadorDirectoris + nomFitxer2;
  258. //
  259. o.print("Escriu una contrasenya [16, 24 o 32 caracters]: ");
  260. //
  261. String textClau = i.readLine();
  262. //
  263. SecretKeySpec clau = new SecretKeySpec(textClau.getBytes(), "AES");
  264. //
  265. Cipher xifrador = Cipher.getInstance("AES/ECB/PKCS5Padding");
  266. //
  267. FileInputStream streamFitxer1 = new FileInputStream(rutaFitxer1);
  268. FileOutputStream streamFitxer2 = new FileOutputStream(rutaFitxer2);
  269. //
  270. xifrador.init(Cipher.ENCRYPT_MODE, clau);
  271. //
  272. boolean fiFitxer = false;
  273. int llegits;
  274. //
  275. byte[] blocClar = new byte[tamanyBlocEncriptacio];
  276. //
  277. while (!fiFitxer) {
  278. llegits = streamFitxer1.read(blocClar);
  279. //
  280. if (llegits >= 0) {
  281. byte[] blocXifrat = xifrador.update(blocClar, 0, llegits);
  282. streamFitxer2.write(blocXifrat);
  283. } else {
  284. fiFitxer = true;
  285. }
  286. }
  287. //
  288. streamFitxer1.close();
  289. streamFitxer2.close();
  290. //
  291. o.println("Fitxer encriptat correctament");
  292.  
  293. } else if (comanda.equals("DESENCRIPTAR")) {
  294. String nomFitxer1 = parts[1];
  295. String nomFitxer2 = nomFitxer1.substring(0, nomFitxer1.length() - extensioXifrat.length());
  296.  
  297. String rutaFitxer1 = directoriTreball.toString() + separadorDirectoris + nomFitxer1;
  298. String rutaFitxer2 = directoriTreball.toString() + separadorDirectoris + nomFitxer2;
  299.  
  300. o.print("Escriu la contrasenya: ");
  301. //
  302. String textClau = i.readLine();
  303. //
  304. SecretKeySpec clau = new SecretKeySpec(textClau.getBytes(), "AES");
  305. //
  306. Cipher xifrador = Cipher.getInstance("AES/ECB/PKCS5Padding");
  307. //
  308. FileInputStream streamFitxer1 = new FileInputStream(rutaFitxer1);
  309. FileOutputStream streamFitxer2 = new FileOutputStream(rutaFitxer2);
  310. //
  311. xifrador.init(Cipher.DECRYPT_MODE, clau);
  312. //
  313. boolean fiFitxer = false;
  314. int llegits;
  315. //
  316. byte[] blocXifrat = new byte[tamanyBlocEncriptacio];
  317. //
  318. while (!fiFitxer) {
  319. llegits = streamFitxer1.read(blocXifrat);
  320. //
  321. if (llegits >= 0) {
  322. byte[] blocClar = xifrador.update(blocXifrat, 0, llegits);
  323. streamFitxer2.write(blocClar);
  324. } else {
  325. fiFitxer = true;
  326. }
  327. }
  328. //
  329. streamFitxer1.close();
  330. streamFitxer2.close();
  331. //
  332. //
  333. o.println("Fitxer desencriptat correctament");
  334.  
  335. } else if (comanda.equals("GENERARCLAUS_ASIMETRIC")) {
  336. String nomFitxerClauPublica = parts[1];
  337. String nomFitxerClauPrivada = parts[2];
  338.  
  339. String rutaFitxerClauPublica = directoriTreball.toString() + separadorDirectoris + nomFitxerClauPublica;
  340. String rutaFitxerClauPrivada = directoriTreball.toString() + separadorDirectoris + nomFitxerClauPrivada;
  341.  
  342. FileOutputStream streamFitxer1 = new FileOutputStream(rutaFitxerClauPublica);
  343. FileOutputStream streamFitxer2 = new FileOutputStream(rutaFitxerClauPrivada);
  344.  
  345. // // Generem la clau publica i la privada
  346. //
  347. KeyPairGenerator generador = KeyPairGenerator.getInstance("RSA");
  348. //
  349. generador.initialize(1024);
  350. //
  351. KeyPair pair = generador.generateKeyPair();
  352. //
  353. PublicKey clauPublica = pair.getPublic();
  354. PrivateKey clauPrivada = pair.getPrivate();
  355. //
  356. byte[] bytesClauPublica = clauPublica.getEncoded();
  357. byte[] bytesClauPrivada = clauPrivada.getEncoded();
  358. //
  359. // // Escribim els bytes de cada clau als fitxers corresponents
  360. //
  361. streamFitxer1.write(bytesClauPublica);
  362. streamFitxer2.write(bytesClauPrivada);
  363. //
  364. //
  365. o.println("Generada clau publica i privada");
  366.  
  367. } else if (comanda.equals("ENCRIPTA_ASIMETRIC")) {
  368. String nomFitxerClar = parts[1];
  369. String nomFitxerClauPublica = parts[2];
  370.  
  371. String rutaFitxerClar = directoriTreball.toString() + separadorDirectoris + nomFitxerClar;
  372. String rutaFitxerClauPublica = directoriTreball.toString() + separadorDirectoris + nomFitxerClauPublica;
  373. String rutaFitxerXifrat = directoriTreball.toString() + separadorDirectoris + nomFitxerClar + extensioXifratAsimetric;
  374.  
  375. // // Obtenim els bytes de la clau publica del fitxer corresponent
  376. //
  377. File fitxerClauPublica = new File(rutaFitxerClauPublica);
  378. long tamanyFitxerClauPublica = fitxerClauPublica.length();
  379. //
  380. FileInputStream streamClauPublica = new FileInputStream(rutaFitxerClauPublica);
  381. //
  382. byte[] bytesClauPublica = new byte[(int) tamanyFitxerClauPublica];
  383. //
  384. boolean fiFitxer = false;
  385. int llegits = streamClauPublica.read(bytesClauPublica);
  386. //
  387. while (!fiFitxer) {
  388.  
  389. if (llegits >= 0) {
  390.  
  391. llegits = streamClauPublica.read(bytesClauPublica, llegits, (int) tamanyFitxerClauPublica - llegits);
  392. } else {
  393. fiFitxer = true;
  394. }
  395. //
  396. }
  397. //
  398. streamClauPublica.close();
  399. //
  400. // // Creem la clau publica a partir dels bytes
  401. //
  402. X509EncodedKeySpec especificacioClau = new X509EncodedKeySpec(bytesClauPublica);
  403. //
  404. KeyFactory fabricaClaus = KeyFactory.getInstance("RSA");
  405. //
  406. PublicKey clauPublica = fabricaClaus.generatePublic(especificacioClau);
  407. //
  408. // // Xifrem el fitxer clar
  409. //
  410. Cipher xifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  411. //
  412. xifrador.init(Cipher.PUBLIC_KEY, clauPublica);
  413. //
  414. FileInputStream streamFitxerClar = new FileInputStream(rutaFitxerClar);
  415. FileOutputStream streamFitxerXifrat = new FileOutputStream(rutaFitxerXifrat);
  416. //
  417. byte[] blocClar = new byte[tamanyBlocEncriptacioAsimetrica];
  418. fiFitxer = false;
  419. llegits = streamFitxerClar.read(blocClar);
  420. //
  421. while (!fiFitxer) {
  422.  
  423. if (llegits >= 0) {
  424.  
  425. byte[] blocXifrat = xifrador.update(blocClar, 0, llegits);
  426.  
  427. streamFitxerXifrat.write(blocXifrat);
  428. llegits = streamFitxerClar.read(blocClar);
  429.  
  430. } else {
  431. fiFitxer = true;
  432. }
  433. //
  434. }
  435. //
  436. byte[] bytesXifrats = xifrador.doFinal();
  437. streamFitxerXifrat.write(bytesXifrats);
  438. //
  439. streamFitxerClar.close();
  440. streamFitxerXifrat.close();
  441.  
  442. o.println("Fitxer encriptat correctament de forma asimetrica");
  443.  
  444. } else if (comanda.equals("DESENCRIPTA_ASIMETRIC")) {
  445. String nomFitxerXifrat = parts[1];
  446. String nomFitxerClauPrivada = parts[2];
  447.  
  448. String nomFitxerPrivat = nomFitxerXifrat.substring(0, nomFitxerXifrat.length() - extensioXifratAsimetric.length());
  449.  
  450. String rutaFitxerXifrat = directoriTreball.toString() + separadorDirectoris + nomFitxerPrivat;
  451. String rutaFitxerClauPublica = directoriTreball.toString() + separadorDirectoris + nomFitxerClauPrivada;
  452. String rutaFitxerClar = directoriTreball.toString() + separadorDirectoris + nomFitxerXifrat;
  453.  
  454. // Adapteu el codi de l'encriptat
  455. // // Obtenim els bytes de la clau publica del fitxer corresponent
  456. //
  457. File fitxerClauPrivada = new File(rutaFitxerClauPublica);
  458. long tamanyFitxerClauPrivada = fitxerClauPrivada.length();
  459. //
  460. FileInputStream streamClauPrivada = new FileInputStream(rutaFitxerClauPublica);
  461. //
  462. byte[] bytesClauPrivada = new byte[(int) tamanyFitxerClauPrivada];
  463. //
  464. boolean fiFitxer = false;
  465. int llegits = streamClauPrivada.read(bytesClauPrivada);
  466. //
  467. while (!fiFitxer) {
  468.  
  469. if (llegits >= 0) {
  470.  
  471. llegits = streamClauPrivada.read(bytesClauPrivada, llegits, (int) tamanyFitxerClauPrivada - llegits);
  472. } else {
  473. fiFitxer = true;
  474. }
  475. //
  476. }
  477. //
  478. streamClauPrivada.close();
  479. //
  480. // // Creem la clau publica a partir dels bytes
  481. //
  482. X509EncodedKeySpec especificacioClau = new X509EncodedKeySpec(bytesClauPrivada);
  483. //
  484. KeyFactory fabricaClaus = KeyFactory.getInstance("RSA");
  485. //
  486. PublicKey clauPrivada = fabricaClaus.generatePublic(especificacioClau);
  487. //
  488. // // Xifrem el fitxer clar
  489. //
  490. Cipher xifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  491. //
  492. xifrador.init(Cipher.PRIVATE_KEY, clauPrivada);
  493. //
  494. FileInputStream streamFitxerClar = new FileInputStream(rutaFitxerClar);
  495. FileOutputStream streamFitxerXifrat = new FileOutputStream(rutaFitxerXifrat);
  496. //
  497. byte[] blocXifrat = new byte[tamanyBlocEncriptacioAsimetrica];
  498. fiFitxer = false;
  499. llegits = streamFitxerClar.read(blocXifrat);
  500. //
  501. while (!fiFitxer) {
  502.  
  503. if (llegits >= 0) {
  504.  
  505. byte[] blocClar = xifrador.update(blocXifrat, 0, llegits);
  506.  
  507. streamFitxerXifrat.write(blocXifrat);
  508. llegits = streamFitxerClar.read(blocXifrat);
  509.  
  510. } else {
  511. fiFitxer = true;
  512. }
  513. //
  514. }
  515. //
  516. byte[] bytesXifrats = xifrador.doFinal();
  517. streamFitxerXifrat.write(bytesXifrats);
  518. //
  519. streamFitxerClar.close();
  520. streamFitxerXifrat.close();
  521.  
  522. o.println("Fitxer desencriptat correctament de forma asimetrica");
  523.  
  524. } // Altres comandes
  525. else if (comanda.equals("ENVIAR")) {
  526. String nomFitxer = parts[1];
  527. String nomServidor = parts[2];
  528.  
  529. String rutaFitxer = directoriTreball.toString() + separadorDirectoris + nomFitxer;
  530.  
  531. Socket socketClient = new Socket(nomServidor, portEnviament);
  532. //
  533. OutputStream streamEnviar = socketClient.getOutputStream();
  534. //
  535. FileInputStream streamFitxer = new FileInputStream(rutaFitxer);
  536.  
  537. byte[] bloc = new byte[tamanyBlocEnviament];
  538. int llegits = streamFitxer.read(bloc);
  539. boolean fiFitxer = false;
  540. // // Llegir blocs del fitxer i escriure'ls al stream d'enviament
  541. // // fins que s'arribi al final del fitxer
  542. while (!fiFitxer) {
  543. streamEnviar.write(bloc, 0, llegits);
  544. llegits = streamFitxer.read(bloc);
  545.  
  546. // ...
  547. }
  548. streamFitxer.close();
  549. socketClient.close();
  550.  
  551. } else if (comanda.equals("REBRE")) {
  552. String nomFitxer = parts[1];
  553.  
  554. String rutaFitxer = directoriTreball.toString() + separadorDirectoris + nomFitxer;
  555.  
  556. ServerSocket servidor = new ServerSocket(63);
  557. Socket socketServidor = servidor.accept();
  558.  
  559. InputStream streamRebre = socketServidor.getInputStream();
  560. FileOutputStream streamFitxer = new FileOutputStream(rutaFitxer);
  561.  
  562. byte[] bloc = new byte[tamanyBlocEnviament];
  563. int llegits = streamRebre.read(bloc);
  564. boolean fiRecepcio = false;
  565. // // Llegir blocs del stream de recepcio i escriure'ls al fitxer
  566. // // fins que s'arribi al final del stream de recepcio
  567. while (!fiRecepcio) {
  568. if (llegits >= 0) {
  569. streamFitxer.write(bloc, 0, llegits);
  570. llegits = streamRebre.read(bloc);
  571.  
  572. } else {
  573. fiRecepcio = true;
  574. }
  575.  
  576. }
  577. streamFitxer.close();
  578. socketServidor.close();
  579. servidor.close();
  580.  
  581. } else if (comanda.equals("EXECUTAR")) {
  582. String nomFitxerExecutable = parts[1];
  583.  
  584. String rutaFitxerExecutable = directoriTreball.toString() + separadorDirectoris + nomFitxerExecutable;
  585.  
  586. Runtime runtime = Runtime.getRuntime();
  587. Process proces = runtime.exec(rutaFitxerExecutable);
  588. //
  589. int codiSortida = proces.waitFor();
  590. //
  591. o.println("Programa terminat amb codi: " + codiSortida);
  592.  
  593. } else if (comanda.equals("EXECUTAR_AMB_PARAMETRES")) {
  594. String nomFitxerExecutable = parts[1];
  595.  
  596. String rutaFitxerExecutable = directoriTreball.toString() + separadorDirectoris + nomFitxerExecutable;
  597.  
  598. //// Construim la llista de parametres
  599. //
  600. ArrayList<String> arguments = new ArrayList();
  601. //
  602. arguments.add(rutaFitxerExecutable);
  603. //
  604. for (int i2 = 2; i2 < parts.length; i2++) {
  605. arguments.add(parts[i2]);
  606. }
  607. //
  608. ProcessBuilder pb = new ProcessBuilder();
  609. //
  610. //// Establim el directori de treball del proces
  611. //
  612. File f = directoriTreball.toFile();
  613. pb.directory(f);
  614. //
  615. //// Configurem els arguments i el nom del arxiu executable del proces
  616. //
  617. pb.command(arguments);
  618. //
  619. Process proces = pb.start();
  620. //
  621. //// Iniciem el proces
  622. //
  623. int codiSortida = proces.waitFor();
  624. //
  625. o.println("Programa terminat amb codi: " + codiSortida);
  626. //
  627. } else if (comanda.equals("EXECUTAR_AMB_REDIRECCIO")) {
  628. String nomFitxerExecutable = parts[1];
  629. String nomFitxerEntrada = parts[2];
  630. String nomFitxerSortida = parts[3];
  631.  
  632. String rutaFitxerExecutable = directoriTreball.toString() + separadorDirectoris + nomFitxerExecutable;
  633. String rutaFitxerEntrada = directoriTreball.toString() + separadorDirectoris + nomFitxerEntrada;
  634. String rutaFitxerSortida = directoriTreball.toString() + separadorDirectoris + nomFitxerSortida;
  635.  
  636. File e = new File(rutaFitxerEntrada);
  637. File s = new File(rutaFitxerSortida);
  638. //
  639. ProcessBuilder pb = new ProcessBuilder();
  640. //
  641. File f = directoriTreball.toFile();
  642. pb.directory(f);
  643. //
  644. pb.redirectInput(e);
  645. pb.redirectOutput(s);
  646. //
  647. pb.command(rutaFitxerExecutable);
  648. //
  649. Process proces = pb.start();
  650. //
  651. int codiSortida = proces.waitFor();
  652. //
  653. o.println("Programa terminat amb codi: " + codiSortida);
  654. } else if (comanda.equals("EXECUTAR_SEGON_PLA")) {
  655.  
  656. String nomFitxerExecutable = parts[1];
  657.  
  658. String rutaFitxerExecutable = directoriTreball.toString() + separadorDirectoris + nomFitxerExecutable;
  659.  
  660. boolean error = false;
  661.  
  662. //// Control d'errors
  663. //
  664. if (process != null) {
  665. if (process.isAlive()) {
  666. o.println("ERROR: Cal detenir el procés en segon pla iniciat prèviament");
  667. error = true;
  668. }
  669. //
  670. }
  671. //
  672. if (!error) {
  673. ProcessBuilder pb = new ProcessBuilder();
  674. //
  675. File f = directoriTreball.toFile();
  676. pb.directory(f);
  677. //
  678. pb.command(rutaFitxerExecutable);
  679. //
  680. process = pb.start();
  681. //
  682. o.println("Execucio en segon pla iniciada");
  683. //
  684. }
  685. } else if (comanda.equals("DETENIR_SEGON_PLA")) {
  686.  
  687. boolean error = false;
  688.  
  689. //// Control errors
  690. //
  691. if (process == null) {
  692. o.println("ERROR: No hi ha cap procés executant-se en segon pla");
  693. error = true;
  694. }
  695. //
  696. if (!error) {
  697. //
  698. if (!process.isAlive()) {
  699.  
  700. o.println("El procés en segon pla ja estava detingut");
  701. } else {
  702. process.destroy();
  703.  
  704. o.println("Esperant finalització");
  705.  
  706. int codigo = process.waitFor();
  707. o.println("Procés finalitzat");
  708. //
  709.  
  710. }
  711.  
  712. process = null;
  713. }
  714. } // Altres comandes
  715. else if (comanda.equals("COMPRIMIR")) {
  716. // long tempsInici = ...;
  717.  
  718. String nomFitxer = parts[1];
  719.  
  720. String nomFitxerComprimit = nomFitxer + extensioCompressio;
  721.  
  722. String rutaFitxer = directoriTreball.toString() + separadorDirectoris + nomFitxer;
  723. String rutaFitxerComprimit = directoriTreball.toString() + separadorDirectoris + nomFitxerComprimit;
  724.  
  725. // Obrim fitxer zip
  726. FileOutputStream fos = new FileOutputStream(rutaFitxerComprimit);
  727. ZipOutputStream zos = new ZipOutputStream(fos);
  728.  
  729. // Creem entrada fitxer zip
  730. ZipEntry ze = new ZipEntry(nomFitxer);
  731. zos.putNextEntry(ze);
  732.  
  733. // Passem les dades del fitxer d'entrada al zip
  734. FileInputStream fis = new FileInputStream(rutaFitxer);
  735.  
  736. byte[] bloc = new byte[tamanyBlocCompressio];
  737.  
  738. int llegits = fis.read(bloc);
  739.  
  740. while (llegits >= 0) {
  741. zos.write(bloc, 0, llegits);
  742.  
  743. llegits = fis.read(bloc);
  744. }
  745.  
  746. fis.close();
  747.  
  748. // Tanquem l'entrada
  749. zos.closeEntry();
  750.  
  751. // Tanquem el fitxer zip
  752. zos.close();
  753.  
  754. System.out.println(nomFitxer + " comprimit");
  755.  
  756. // long tempsUtilitzat = ...;
  757. System.out.println("---------------------");
  758. System.out.println("Compressio completada");
  759. // System.out.println("Temps utilitzat: " + + tempsUtilitzat / 1000.0 + " segons");
  760.  
  761. } else if (comanda.equals("COMPRIMIR_SEQUENCIAL")) {
  762. // long tempsInici = ...;
  763.  
  764. //for(int i2 = ...; i2 < ...; i2 ++)
  765. //{
  766. // String nomFitxer = ...;
  767. //
  768. // ...
  769. //
  770. // System.out.println(nomFitxer + " comprimit");
  771. //
  772. //}
  773. // long tempsUtilitzat = ...;
  774. System.out.println("---------------------");
  775. System.out.println("Compressio completada");
  776. // System.out.println("Temps utilitzat: " + + tempsUtilitzat / 1000.0 + " segons");
  777. } else if (comanda.equals("COMPRIMIR_PARALEL")) {
  778. // long tempsInici = ...;
  779.  
  780. // Thread []fils = new Thread[...];
  781. //
  782. //// Creem els fils
  783. //
  784. //for(int i2 = ...; i2 < ...; i2 ++)
  785. //{
  786. // String nomFitxer = ...;
  787. //
  788. // String nomFitxerComprimit = nomFitxer + extensioCompressio;
  789. //
  790. // String rutaFitxer = directoriTreball.toString() + separadorDirectoris + nomFitxer;
  791. // String rutaFitxerComprimit = directoriTreball.toString() + separadorDirectoris + nomFitxerComprimit;
  792. //
  793. // FilCompressio fc = new FilCompressio(...);
  794. // fils[...] = new Thread(...);
  795. //
  796. //}
  797. //
  798. //
  799. //// Iniciem els fils
  800. //
  801. //for(int i2 = ...; i2 < ...; i2 ++)
  802. //{
  803. // fils[...]....();
  804. //}
  805. //
  806. //// Esperem que els fils acabin
  807. //
  808. //for(int i2 = ...; i2 < ...; i2 ++)
  809. //{
  810. // fils[...]....();
  811. //}
  812. //
  813. //
  814. //long tempsUtilitzat = ...;
  815. //
  816. //System.out.println("---------------------");
  817. //System.out.println("Compressio completada");
  818. //System.out.println("Temps utilitzat: " + + tempsUtilitzat / 1000.0 + " segons");
  819. } else if (comanda.equals("DESCARREGAR")) {
  820. String urlEntrada = parts[1];
  821. String nomFitxerSortida = parts[2];
  822.  
  823. String rutaFitxerSortida = directoriTreball.toString() + separadorDirectoris + nomFitxerSortida;
  824.  
  825. //// Obrim la url
  826. //
  827. URL url = new URL(urlEntrada);
  828. InputStream streamEntrada = url.openStream();
  829. //
  830. OutputStream streamSortida = new FileOutputStream(rutaFitxerSortida);
  831.  
  832. //
  833. byte bloc[] = new byte[tamanyBlocDescarrega];
  834. //
  835. int bytesDescarregats = 0;
  836. int llegits = streamEntrada.read(bloc);
  837. //
  838. while (llegits >= 0) {
  839. streamSortida.write(bloc, 0, llegits);
  840.  
  841. //Comptabilitzem els bytes descarregats
  842. bytesDescarregats++;
  843.  
  844. llegits = streamEntrada.read(bloc);
  845. }
  846.  
  847. streamEntrada.close();
  848. streamSortida.close();
  849. //
  850. o.println("Descarrega finalitzada. Bytes descarregats " + bytesDescarregats);
  851.  
  852. } else if (comanda.equals("AFEGIR_DESCARREGA")) {
  853. String urlEntrada = parts[1];
  854. String nomFitxerSortida = parts[2];
  855.  
  856. String rutaFitxerSortida = directoriTreball.toString() + separadorDirectoris + nomFitxerSortida;
  857.  
  858. System.out.println(urlEntrada);
  859. System.out.println(rutaFitxerSortida);
  860. gd.IniciarDescarrega(urlEntrada, rutaFitxerSortida);
  861.  
  862. } else if (comanda.equals("ESTAT_DESCARREGAS")) {
  863. gd.ImprimirEstatDescarregues();
  864.  
  865. } else if (comanda.equals("SORTIR")) {
  866.  
  867. fi = true;
  868. }
  869. }
  870.  
  871. }
  872.  
  873. public static Path obtenirDirectoriArrel() {
  874. Path result;
  875.  
  876. Iterable<Path> roots = FileSystems.getDefault().getRootDirectories();
  877. Iterator<Path> itRoots = roots.iterator();
  878. if (itRoots.hasNext()) {
  879. result = itRoots.next();
  880. } else {
  881. result = null;
  882. }
  883.  
  884. return result;
  885.  
  886. }
  887.  
  888. public static String obtenirSeparadorDirectoris() {
  889. return FileSystems.getDefault().getSeparator();
  890.  
  891. }
  892.  
  893. static String byteArrayToHexString(byte[] bytes) {
  894. String r = "";
  895. for (int i = 0; i < bytes.length; i++) {
  896. r += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
  897. }
  898.  
  899. return r;
  900.  
  901. }
  902. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement