Pobieranie prezentacji. Proszę czekać

Pobieranie prezentacji. Proszę czekać

1 Praktyczne narzędzia i skrypty © Krzysztof Barteczko, PJWSTK 2010 - 2012.

Podobne prezentacje


Prezentacja na temat: "1 Praktyczne narzędzia i skrypty © Krzysztof Barteczko, PJWSTK 2010 - 2012."— Zapis prezentacji:

1 1 Praktyczne narzędzia i skrypty © Krzysztof Barteczko, PJWSTK 2010 - 2012

2 2 Argumenty wiersza poleceń Dostępne jako tablica o zarezerwowanej nazwie args. Podawane w wywołaniu: java Program arg1 arg2... arg3 Spacje w argumentach? - zastosuj ".." Przykład == Test.groovy: args.each { println it } printl args[2]

3 3 Operacje na plikach i katalogach Jak często użyteczne: porządkowanie, wyszukiwanie, backupowanie. Poznaliśmy w wykładzie "Pliki". Groovy jest tu wyjątkowo przydatny, co zobaczymy na paru praktycznych przykładach.

4 4 Pliki, katalogi: przykład 1 Zadanie: wyszukać w bieżącym katalogu i wszystkich jego podkatalogach pliki o podanym rozszerzeniu i zawierające teksty pasujące do podanego wzorca. Znalezione pliki pokazać na liście, wybór elementu listy ma pokazywać zawartość pliku w edytorze obok listy.

5 5 Możliwe rozwiązanie (ext, txtpattern) = args dir = new File('.') found = [] dir.eachFileRecurse { if (it.name.endsWith(ext) && it.text.find(~txtpattern)) found << it } if (!found) System.exit(-1) new SwingBuilder().edt { lookAndFeel('nimbus') f = frame(pack: true, visible: true, defaultCloseOperation: EXIT_ON_CLOSE) { hbox() { scrollPane(border: titledBorder('Files')) { list(id: 'fl', listData: found, mouseReleased: { val = fl.selectedValue if (!val) return f.title = val.toString() ta.text = val.text } ) } scrollPane(border: titledBorder('Text')) { textArea(id: 'ta', rows: 15, columns: 40, font: new Font('Monospaced', Font.PLAIN, 14)) }

6 6 Wynik 1 groovy.groovy if

7 7 Pliki, katalogi: przykład 2 Zmiana nazw grupy plików. dir = new File('.') (pattern, replace) = new File(args[0]).text.readLines() files = [] newNames = [] dir.eachFileMatch(~pattern) { files << it newNames << it.name.replaceAll(pattern, replace) } files.eachWithIndex { f, i -> println f.name + ' rename to ' + newNames[i] } println 'Perform renaming ? [y/.]:' ans = new Scanner(System.in).next() if (ans == 'y') { files.eachWithIndex { f, i -> f.renameTo(new File(newNames[i])) } (\w+)(\.ppt) $1pl$2

8 8 Uruchamianie procesów String cmd = '...' out = new StringBuffer() err = new StringBuffer() Process p = cmd.execute() p.consumeProcessOutput(out, err) p.waitForOrKill(time) // p.exitCode() - kod zakończenia // out - zawartość stdout // err - zawartość stderr // p.text - inny sposób uzyskania stdout Konieczne, gdy dużo wyników na konsoli.

9 9 Najprostszy sposób integracji Program (Test1.rexx) napisany w REXXie, wyniki na konsoli. say "Hello from Rexx"import static javax.swing.JOptionPane.*; cmd = 'regina Test1.rexx' p = cmd.execute() showMessageDialog(null, p.text) Program Test2.rexx pisze do pliku. parse arg outFileName sleep 3 /* here doing some hard work */ call lineout outFileName, 'Hello from Rexx' call stream outFileName, 'c', 'close' import static javax.swing.JOptionPane.*; file = new File('results.txt') cmd = 'regina Test2.rexx ' + file.canonicalPath p = cmd.execute() while(true) { if (file.exists()) break println 'Not ready yet..' sleep 1000 } showMessageDialog(null, file.text)

10 10 Przykład: proste przetwarzanie PDF import java.awt.* def drive = new File('.').canonicalPath[0] def dir = new File("$drive:/vouchery") def cmd = /$drive:\Utils\xpdf-3.02pl2-win32\pdftotext.exe -layout -enc UTF-8/ def tmpname = 'temp.txt' def list = [] dir.eachFile { if (it.name.endsWith('.pdf')) { println it.name def cmdexec = cmd + ' ' + it.canonicalPath + ' ' + tmpname Process proc = cmdexec.execute() proc.waitForOrKill(10000) def cont = new File(tmpname).text if (cont.contains('Madrid')) list << it } list.each { Desktop.desktop.open(it) }

11 11 Groovy Templates The template framework in Groovy consists of a TemplateEngine abstract base class that engines must implement and a Template interface that the resulting templates they generate must implement. Included with Groovy are several template engines: * SimpleTemplateEngine - for basic templates * GStringTemplateEngine - stores the template as writable closures (useful for streaming scenarios) * XmlTemplateEngine - works well when the template and output are valid XML Z dokumentacji Groovy

12 12 Prosty przykład Dear $name, see you on $lang meeting in $city next week. Best regards, Chris import groovy.text.SimpleTemplateEngine def pMap = [John: 'Java', Sam: 'Groovy', Alice: 'Rexx'] def cities = [Rexx: 'Loa Angeles', Groovy: 'New York', Java: 'Miami'] def engine = new SimpleTemplateEngine() def template = engine.createTemplate(new File('Templ1.tpl').text) pMap.each { pers, lang -> def binding = [ name: pers, lang: lang, city: cities[lang] ] def lettFile = new File("letter2$pers") template.make(binding).writeTo(lettFile.newWriter()) } File Templ1.tpl Trzy pliki powstały z dostosowaną dla adresatów treścią

13 13 Przykład Mailera class Sender { def static send(adr, sub, msg, attlist = null) { sendMail transport: 'smtps', auth: true, mailhost: 'imap.gmail.com', mailer: 'Custom mailer service (JavaMail+Groovy)', user: Login.user.login, password: Login.user.password, to: adr, from: Login.user.login, subject: sub, text: msg, attachments: attlist println "Message sent to: $adr" } if (Login.dialog('pjwstk.edu.pl')) Sender.send 'kb@pjwstk.edu.pl', 'Witam', '''Czesc, xxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxx'''

14 14 Najprościej a szybko w Internecie def sitesMap = [:] def cpMap = [:] def loadedList = [] getClass().classLoader.getResourceAsStream('res/urlList').splitEachLine('\t') { tok -> sitesMap[tok[0]] = tok[1] } new SwingBuilder().edt { lookAndFeel 'nimbus' frame(title: "Quick", pack:true, locationRelativeTo: null, visible: true, defaultCloseOperation: JFrame.EXIT_ON_CLOSE, windowClosing: { loadedList.each { it.delete() } } ) { panel(layout: gridLayout(cols: 1, rows: 0)) { sitesMap.each { name, addr -> button(name, actionPerformed: { show(addr, loadedList) } ) } } } } def show(String addr, loadedList) { def tempDir = System.getenv('TEMP') def ls = addr.lastIndexOf('/') // last slash def outFileName = addr[ls+1..-1] def url = new URL( addr[0..ls]+ URLEncoder.encode(outFileName, 'UTF-8').replace('+', '%20') ) outFile = new File(tempDir, outFileName) outFile.bytes = url.bytes Desktop.desktop.open(outFile) loadedList << outFile }

15 15 XML Przykładowy XML John 30 Bill 20 Elementy Atrybuty Nazwy Wartości

16 16 Czytanie XML w Groovy jest proste def doc = new XmlParser().parse(new File('test.xml')) println doc.customer println doc.customer.name println doc.customer.@special println doc.customer.name[0].text() println doc.customer.age[0].text() println doc.customer.name*.text() doc.customer.findAll { it.@special == 'yes'}.each { println 'Special customer: ' + it.name.text() } Output: [customer[attributes={special=yes}; value=[name[attributes={}; value=[John]], age[attributes={}; value=[30]]]], customer[attributes={special=no}; value=[name[attributes={}; value=[Bill]], age[attributes={}; value=[20]]]]] [name[attributes={}; value=[John]], name[attributes={}; value=[Bill]]] [yes, no] John 30 [John, Bill] Special customer: John Listy elementów o danej nazwie Dostęp do wartości atrybutów Dostęp do wartości elementów

17 17 Przykład: kursy euro import groovy.swing.SwingBuilder def url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' def rates = new XmlParser().parse(url) def map = [:] rates.Cube.Cube.Cube.each { map[it.@currency] = it.@rate } new SwingBuilder().edt { frame(title: 'Euro rates', pack: true, visible: true) { panel() { comboBox(id: 'cb', border: titledBorder('Select currency'), prototypeDisplayValue: 'xxxxxxxxxxxxx', items: map.keySet().toList(), actionPerformed: { def cur = it.source.selectedItem lab.text = map[cur] }) label(id: 'lab', preferredSize: cb.preferredSize, border: titledBorder('Rate')) }

18 18 Parsowanie HTML NekoHtml robi z HTML dobry XML Zobaczmy wiadomości ze świata. def url = 'http://www.sawadee.com/hotel/krabi' def html = new XmlParser(new SAXParser()).parse(url) def info = [ ] def allDivs = html.'**'.DIV def hotelNames = allDivs.findAll { it.@class == 'hotelname' } def hotelLocate = allDivs.findAll { it.@class == 'hotellocate' } def roomRate = allDivs.findAll { it.@class == 'roomrate' } println hotelNames.size() + ' ' + hotelLocate.size() + ' ' + roomRate.size() def names = hotelNames*.A*.text() def locs = hotelLocate*.text() def links = hotelNames*.A*.@href def rates = roomRate*.SPAN*.text() names.eachWithIndex { name, i -> println ( [name, locs[i], rates[i], links[i][0] ].join ('\t') ) } Start at root

19 19 HTTPBuilder lub symulacja przeglądarki import org.openqa.selenium.*; import org.openqa.selenium.firefox.*; System.setProperty("webdriver.firefox.bin", "h:/Internet/Firefox2/firefox.exe"); WebDriver driver = new FirefoxDriver(); driver.get("https://www.hoteltravel.com/member/login.aspx?lng=en"); WebElement element = driver.findElement(By.id('ctl00_tbUsername')); element.sendKeys("bartec@astercity.net"); element = driver.findElement(By.id('ctl00_tbPassword')) element.sendKeys(pass.Pass.pass) element = driver.findElement(By.id('ctl00_linkImgBtn')) element.click(); Demo wykorzystania: -Szybkie logowanie i nawigacja -EduDSL Pokaz EduDSL (EduDSL - prezentacja można odłożyć do wykładu o DSL)EduDSL - prezentacja

20 20 Excel by Scriptom def d = new File('.').canonicalPath[0] def dir = new File(/$d:\IKIC\Prognozy09\WBdata/) def tplFile = new File(/$d:\IKIC\Prognozy09\SelectedWorldData.xls/) def outFile = new File("$d:/IKIC/Prognozy09/SelWd.xls") def rowsToSelect = [3: 'PKB',6: 'Inwestycje',7: 'Eksport',8: 'Import'] def out = new StringBuffer() def helper = new ExcelHelper() dir.eachFile { def name = it.name println "Processing $name" out << name[0..<name.indexOf('.')] << '\n' helper.process(it) { workbook -> def worksheet = workbook.Sheets.Item['Sheet1'] def list = worksheet.UsedRange.Value.toList() out << '\t' << list[0][1..-1].join('\t') << '\n' rowsToSelect.each { row, descr -> out << descr << '\t' << list[row-1][1..-1].join('\t') << '\n' } helper.create(tplFile, outFile ) { workbook -> def worksheet = workbook.Sheets.Item['Sel'] worksheet.Activate worksheet.Range('A1').Select worksheet.Paste worksheet.Range('A1').Select } Desktop.getDesktop().open(outFile)

21 21 Bazy danych import groovy.sql.* Sql sql = Sql.newInstance("jdbc:odbc:ksidb") def query = ''' select autor.autor, pozycje.tytul, pozycje.cena from pozycje, autor where autor.id = pozycje.autid ''' sql.eachRow(query) { row -> println "$row.autor, $row.tytul, $row.cena" } Bazy NoSQL: zob. np. http://www.slideshare.net/tednaleid/redis-and-groovy-and- grails-gr8conf-2011 Bazy obiektowe: code.google.com/p/db4o-groovy/

22 22 Integracja z narzędziami (1) Demo projektu: strukturalna dekompozycja zatrudnienia Zobacz: IntegracjaApp.pdf

23 23 Integracja z narzędziami (2) Przykład „constraint programming” – zobacz link z odpowiedzią Zagadka Einsteina (wersja krótka) Przy ulicy stoją obok siebie trzy domy. Każdy jest innego koloru, w każdym mieszka rodzina innej narodowości, każda rodzina ma inne zwierzaki. Mając następujące informacje: Hiszpanie mają psy. Drugi dom jest żółty. W pierwszym domu nie ma psów. Anglicy mieszkają w domu tuż obok niebieskiego domu. Koty są w zielonym domu. proszę odpowiedzieć na pytania: W którym domu są rybki? Jaki kolor ma dom, w którym mieszkają Włosi? Odp


Pobierz ppt "1 Praktyczne narzędzia i skrypty © Krzysztof Barteczko, PJWSTK 2010 - 2012."

Podobne prezentacje


Reklamy Google