import groovy.transform.TypeChecked import javax.swing.JButton import javax.swing.JDialog import javax.swing.JFrame import javax.swing.JScrollPane import javax.swing.JTable import javax.swing.JTextField import javax.swing.RowFilter import javax.swing.event.ListSelectionListener import javax.swing.table.AbstractTableModel import javax.swing.table.TableModel import javax.swing.table.TableRowSorter import java.awt.BorderLayout import java.awt.Dialog import java.awt.Dimension import java.awt.event.ActionListener import java.awt.event.KeyListener @TypeChecked public class Q1 { public static void main(String[] args) { println showDialog("title", (1..100).collect { "qwe" + it }).join("; ") } public static List<String> showDialog(String title, List<String> options) { def selection = [] def dialog = new JDialog(null, title, Dialog.ModalityType.TOOLKIT_MODAL); dialog.defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE dialog.layout = new BorderLayout() def text = new JTextField() def button = new JButton("Select"); TableModel dataModel = [getColumnCount: { -> 1 }, getRowCount: { -> options.size() }, getValueAt : { int row, int col -> options[row] }] as AbstractTableModel def table = new JTable(dataModel); dialog.add(text, BorderLayout.PAGE_START) dialog.add(button, BorderLayout.PAGE_END) def scroll = new JScrollPane(table) dialog.add(scroll, BorderLayout.CENTER) button.addActionListener([actionPerformed: { dialog.dispose() }] as ActionListener) def sorter = new TableRowSorter(dataModel); table.selectionModel.addListSelectionListener([valueChanged: { selection = (0..options.size() - 1).collect { table.selectionModel.isSelectedIndex(it) ? options[it] : null }.findAll { it != null } button.text = selection.size() + " selected. " + selection.join(", ") }] as ListSelectionListener) table.setRowSorter(sorter) text.addKeyListener([keyPressed: {}, keyTyped: {}, keyReleased: { sorter.setRowFilter(RowFilter.regexFilter(text.getText(), 0)); sorter.sort() }] as KeyListener) dialog.size = dialog.preferredSize = new Dimension(200, 640) dialog.locationRelativeTo = null dialog.visible = true return selection } }
assert orthoCover([[a:1,b:2],[a:2,b:3,c:4],[a:4,b:5],[a:2,b:2]])==[[a:2, b:3, c:4], [a:4, b:5],[a:1, b:2]]
public List cartesian(Collection... collections) { collections = collections.collect { collection -> collection.collect { [it] } } def result = collections.first() collections.drop(1).each { collection -> result = result.collect { left -> collection.collect { right -> left + right } }.sum() } return result }
public static string Hash(string password) { using (var deriveBytes = new Rfc2898DeriveBytes(password, 16, 1000)) { return Convert.ToBase64String(new byte[1].Concat(deriveBytes.Salt).Concat(deriveBytes.GetBytes(32)).ToArray()); } } public static bool CheckHash(string hashBase64, string password) { var hash = Convert.FromBase64String(hashBase64); using (var deriveBytes = new Rfc2898DeriveBytes(password, hash.Skip(1).Take(16).ToArray(), 1000)) { return hash.Skip(1).Skip(16).Take(32).SequenceEqual(deriveBytes.GetBytes(32)); } }
def packFiles={List sources-> def baos=new ByteArrayOutputStream() def zipOut = new java.util.zip.ZipOutputStream(baos) zipOut.setLevel(java.util.zip.Deflater.NO_COMPRESSION) for (def source : sources) { zipOut.putNextEntry(new java.util.zip.ZipEntry(source.name)) zipOut.write(source.bytes) zipOut.closeEntry() } zipOut.flush() zipOut.close() return baos.toByteArray() }
import groovy.transform.TypeChecked; import sun.misc.IOUtils; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @TypeChecked class T { public static void main(String[] args) { def folder="C:\\Users\\dsorescu\\Documents\\My Received Files"; ZipFile zip=new ZipFile(folder+"\\"+"MY_SECRET_ZIP_FILE_NAME.zip"); zip.entries().each {ZipEntry entry-> System.out.println(entry.name); File f=new File(folder+"\\"+entry.name); f.parentFile.mkdirs(); if(entry.isDirectory()){ f.mkdir(); }else{ f.createNewFile(); FileOutputStream fos=new FileOutputStream(f); fos.write(IOUtils.readFully(zip.getInputStream(entry),-1,true)); fos.close(); } } } }
package eu.sorescu.db; import java.io.*; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.UUID; import groovy.json.JsonOutput; import groovy.json.internal.JsonParserCharArray; public class Heap { private static final long serialVersionUID = -5685880176240431312L; final File folder; private String joinedPath = ""; public Heap(String... path) throws IOException { if (path.length == 1) if (path[0].length() == 0) path = new String[0]; for (String aPath : path) this.joinedPath += "\\" + URLEncoder.encode(aPath, "UTF-8"); folder = new File("heap" + this.joinedPath + "\\"); } private File file(String arg0) { try { String encodedName = encode(arg0); return new File(folder, encodedName); } catch (IOException e) { throw new IllegalAccessError("heap://" + joinedPath + "/" + arg0); } } public Object[] list() { File[] files = folder.listFiles(); ArrayList<String> result = new ArrayList<>(); try { if (files != null) for (File file : files) if (file.isFile()) result.add(decode(file.getName())); } catch (IOException e) { throw new NullPointerException(e.toString()); } Object[] vector = result.toArray(new String[result.size()]); return vector; } public String[] listHeaps() throws IOException { File[] files = folder.listFiles(); ArrayList<String> result = new ArrayList<>(); if (files != null) for (File file : files) if (file.isDirectory()) result.add(decode(file.getName())); return result.toArray(new String[result.size()]); } // @Override public Object get(final Object arg0) { if (arg0 == null) throw new NullPointerException("d1012150913 Heap " + folder + ": argument null"); if (!(arg0 instanceof String)) throw new NullPointerException("d1012150914 Heap " + folder + ": " + arg0.getClass().getName() + " only String"); return get((String) arg0); } public Object get(final String arg0, Object defaultValue) { Object result = get(arg0); if (result == null) result = defaultValue; return result; } private Object get(final String arg0) { try { File f = file(arg0); byte[] data = Files.readAllBytes(f.toPath()); return new JsonParserCharArray().parse(data); } catch (Throwable ignored) { } return null; } public long getSize(String arg0) { try { return file(arg0).length(); } catch (Throwable t) { return 0; } } public boolean has(String arg0) { if (arg0 == null) return false; File file = file(arg0); return file != null && file(arg0).exists(); } public String put(Object value) { return put(null, value); } private static SimpleDateFormat TIME_STAMP = new SimpleDateFormat( "yyMMddhhmmssSSS"); public String put(String key, Object value) { if ((key == null) || (key.length() == 0)) key = UUID.randomUUID().toString() + "_" + TIME_STAMP.format(new Date()); write(file(key), value); return key; } public void delete(String arg0) { file(arg0).delete(); } private static void write(File file, Object value) { String ser = JsonOutput.prettyPrint(JsonOutput.toJson(value)); try { file.getParentFile().mkdirs(); file.createNewFile(); Files.write(file.toPath(), ser.getBytes(), StandardOpenOption.CREATE); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } } private static String encode(String k) throws UnsupportedEncodingException { return URLEncoder.encode(k, "UTF-8"); } private static String decode(String k) throws UnsupportedEncodingException { return URLDecoder.decode(k, "UTF-8"); } }
public static Class[] classes(Class scope) throws IOException, URISyntaxException { Path root = new File(JUnitExecutor.class.getResource("/").toURI()).toPath(); return Files.walk(root, FileVisitOption.FOLLOW_LINKS).map(path -> root.relativize(path)) .filter(path -> path.toString().endsWith(".class")) .map(path -> path.toString()) .map(path -> path.toString().substring(0, path.length() - 6).replace('\\', '.')) .map(path -> getClass(path)) .filter(clazz -> scope.isAssignableFrom(clazz)) .filter(clazz -> clazz != scope) .toArray(c -> new Class[c]); } private static Class getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new ClassFormatError(className); } }
public static void copyStream(InputStream is, OutputStream os) throws IOException { try ( ReadableByteChannel input = Channels.newChannel(is); WritableByteChannel output = Channels.newChannel(os) ) { final ByteBuffer buffer = ByteBuffer.allocateDirect(65536); while (input.read(buffer) != -1) { buffer.flip(); output.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) output.write(buffer); } }
new java.net.URL("ssh://user:password@host/?ls ~/desktop/").openConnection().getInputStream();