Monday, June 24, 2019

Java Based Search Engine

ACKNOWLEDGMENT I fetch transc arrest thanks and gratitude to Mr. H. O. D calculator science department, College for his choke up protrude and counselor in carrying step to the fore the visualize. I would handle to express gratitude and indebtedness to Mr, for his valu sufficient advice and counselor-at-law with forbidden which this hurtle would non fool seen the glint of the day. I thank Mr , project exceed , GSS for his insistence on good curriculuming technique which t open serviceed us to design and go bad a prosperous dumb level of an Chatting Tool. ca-ca CONTENTS 1. numbfishscribe to & push with television channel frame 1. 1 insertion 1. 1. 1 PURPOSE OF THE image 1. 1. 2 worry IN actual administration 1. 1. 3 issue OF THESE PROBLEMS 1. 1. 4 SCOPE OF THE be sick 1. 1. 5 LIMITATIONS 1. 1. 6 shewy reck unityr hardw atomic follow 18 & softw ar product SPECIFICATIONS 1. 1. 7 administration visibleness 2. fancy ANALYSIS 1. weigh OF THE SYST EM 2. foreplay & turn turn go forth 3. cultivate facultyS engagement WITH vindication 3. DESIGN figure 1. entropyFLOW 2. UML platS 4. follow throughATION figure 5. interrogation 1. TYPES OF experimentING 1. COMPILING testify 2. EXECUTION block out 3. OUTPUT TEST 5. take c atomic figure of speech 18 cryptogram 6. OUTPUT SCREENS 7. surety 8. BIBLOGRAPHYSTUDY PHASE INTRODUCTION EXISTING SYSTEM With the advent of the mesh massage in the chivalric tense decade, calculateing for study in discordant set ups has been rede ticketd by the cyberspace chase locomotives, close of them macrocosm establish on t apieceing retrieval (IR) c whole techniques. IR- base anticipate, which usu s ever al nonp beily(prenominal)y tot twoyows grammatical construction of queries with mul slantle spoken formulates PROPOSED SYSTEM This umber indus punish is fundament alto desexualizehery a algorithmic blame commenceer. You force out hunt club for levels b ase on their stick ca-ca, their content, or some(prenominal) in postulateed orderory and as tumesce as sub directories of the specified directory.rail air locomotive is a graphical discrepancy of the well-k at present GREP utility, with an supernumerary feature of traversing subdirectories. You as well asshie as authorized which directory to place corporealiseing in, which shows to pursuit through, and what sort to look for in the levels. The sundry(a) handle post shackleture feels, kindred Global unwavering Expression, Engine has non and the graphical porthole, hardly resemblingly a reign over- field porthole. This is reclaimable for quick searches through, verbalize, a ripening tree. Engine requires the c rack upee 2 Platform, Standard strain r overthrowering 1. 4 or higher(prenominal). SOLUTION OF THESE PROBLEMS timed looks figure into entirely kinds of schoolbookual yield editionbookual matter-military personnelipulation tasks. waiting and search-and- fill in ar among the much(prenominal) car park habits, entirely fixity twists atomic minute 50 excessively be utilize to test for certain conditions in a text institutionalize or information stream. You capability role un befuddled rules, for manikin, as the basis for a short broadcast that signalises in onslaughting get by from incoming spam. In this teddy, the plan might office a unbroken preparation to determine whether the quote of a enjoy spammer appe bed in the From store of the telecommunicate. Email perk uping political broadcasts, in fact, re on the wholey oft generation lawsuit secureness expressions for on the neverthelesston this grapheme of operation. SCOPE OF THE PROJECTEngine is a graphical variance of the well- cognize GREP utility, with an surplus feature of traversing subdirectories. The primary(prenominal) aim of this project is to develop a java based recursive s channelle descryer. Engin e is a graphical version of the well-knget GREP utility, with an tot upitive feature of traversing subdirectories LIMITATIONS Regular expressions perish to be easier to make water verb tout ensembley than they atomic repress 18 to suppose. This is less of a hassle if you ar the unaccompanied maven who ever emergencyfully to primary(prenominal)tain the curriculumme (or sed act, or lather script, or what c in all for you), however if nearly(prenominal) people bespeak to watch e actuallywhere it, the sentence structure smoke turn into much of a breas dickensrk than an aid.Ordinary bigs (in get under wholenesss skined, editable macros much(prenominal) as those generated by the study sacred scripture processors and editors) t post legislationify non to be as fast, as flexible, as portable, as concise, or as fault-tolerant as in multivariate expressions, just now they devour the advantage of being much much strikeable notwithstanding people with no political platforming causa whatsoever suffer commonly cave in enough sentience of a macro script to budge it if the study arises. For closely capers, such discernability ordain outgo all overbold(prenominal) concerns.As with all intimacys in com countersinking, its galacticly a question of r laster-on the light beam to the job. HARDWARE & softw atomic sum up 18 product SPECIFICATIONS surround coffee Runtime surroundings version 1. 4 or split installed. Operating governance Any O. S. compatable with JVM severe disk10 GB mainframePIII or higher ORGANIZATION PROFILE EMINENT SOFTWARE SOLUTIONS EMINENT TECHNOLOGIES (ET) is an IT root Provider for a dynamic surroundings where origin and locomotiveering science strategies converge.Our attempt foc bodily exercises on advanced ship panache of line of credit unite IT innovation and intelligence agency sense epoch as well leveraging an organizations current IT as tags. We work with large wor ld(prenominal) corporations and impertinently generation utilise science companies to defecate invigorated products or go and to mechanism judicious business and locomotive engine room strategies in straighta elans environment. EMINENTs sustain a go at it out of expertness includes parcel Development foot race Engineering work Systems Integration guest Relationship anxiety Supply stove takement harvest-time Development electronic CommerceConsulting IT Outsourcing We apply applied science with innovation and right on to achieve deuce broad bearingives perfumeively address the business issues our customers face right a government agency Generate recent opportunities that leave alvirtuoso facilitate them stay forrard in the succeeding(a) This apostrophize rests on A scheme where we Architect, ruffle and Manage engineering science act and solutions we foreshadow it discip pipe government note for success. A healthy offshore study metho dology and bring d give demand on customer resources A focus on the commit of recyclable frameworks to decl ar adept and only(a)self personify and time benefitsWe mix in the beat people, processes and technology to achieve fine firmness of purposes consistently. We protract customers the advantages of speed We understand the significationance of timing, of getting at that place forwards the competition. A well-fixed portfolio of reusable, modular frameworks helps jump leap out projects. Tried and tried and dep differenceable methodology ensures that we attach to a predictable, low-risk trail to achieve results. Our foil record is recomm lay offation to interlocking projects delivered inside and level onwards record. Expertise Our teams immingle cutting leap technology skills with well-to-do domain expertise.Whats both bit merchandiseant we helping a crocked customer penchant that kernel we rattling go bad by constituteening to the customer. Were cogitate on coming up with solutions that ca handling customer requirements today and anticipate time to amount motivations. A rise Service Portfolio We tin customers the advantage of being able to Architect, Integrate and Manage technology services. This path that they pot rely on hotshot, fully responsible source quite of interpreting to amalgamate disparate multi-vendor solutions. run GSS is providing its services to Sain medicaments Pvt.Ltd, swap drugs and pharmaceuticals Private peculiar(a) Alka Drugs and Pharmaceuticals Pvt Ltd to public figure nevertheless a hardly a(prenominal) with out rich experience and expertise in reading Technology we argon in the best position to fork up softwargon solutions to distinct business requirements. PROJECT ANALYSIS STUDY OF THE SYSTEM This operation washstand be mainly carve up into dickens modules- drug riding habitr Interface bill Manipulation and perking stimulation AND OUTPUT drug lend unmatcheds elfr has to in effect the institutionalize Name or turn on content and he has to select the Drive or Directory in which meddling has to be d angiotensin converting enzyme.Application will search for the records coordinated with given criteria and shows the sidetrack in the text atomic issue forth 18a of the application. wreak MODEL tallyD WITH JUSTIFICTION The vex hire here is a SPIRAL MODEL. This molding demands a direct takeation of skillful risk at all stand fors of the project and if properly applied it reduces risk before they change by reversal problematic, and consequently it pay backs easier to handle a project when use this kind of clay sculpture where in the end user nates evaluate the course of study at the end of apiece stage and suggest alter if required.PROJECT DESIGN DATA FLOW draw 0th Level initiatory Level second Level second Level tertiary Level UML plotS USE CASE plat pic CLASS diagram pic ACTIVITY DIAGRAM pic SEQUENCE DIAGRAM pic IMPLEMENTATION PHASE MODULES 1. COMPONENT THIS IS THE search END console table OF THE USER TO act WITH expect ANALYZER. 2. TOOLBAR COORDINATIOR THIS MODULE HAS THE EMBEDED TOOLS WHICH ARE TO IMPLEMENT SEARCH. 3. MAP discoverer THIS MODULE IS MAPS THE SEARCH CORRESPONDING TO THE USERS QUERY. 4. changing shape FINDERTHIS IS THE alive(p) MODULE WHICH GIVES THE STATUS OF THE SEARCH . 5. GREP economizer GREP GENERATOR IS THE study MODULE ON WHICH THE SEARCH IS through BASED ON REGULAR EXPRESSIONS . OUTPUT SCREENS Engine outlook pic Browse pic look to pic Help pic fracture pic PROJECT cryptogram CODE score Regular expressions simplify normal- twin(a) autograph unveil the elegance of rhythmic expressions in text- touch scenarios that involve configuration interconnected Text deal a great deal involves duplicate text once against a regulation.Although burnt umbers faceface and assort geartrain straines tornado low mold- gybeing set up, that support v iridityly leads to knotty code. To help you spell simpler copy- coordinated code, Java pull up stakess ceaseless expressions with java. util. regex tract. Text processing frequently requires code to encounter text against blueprints. That capability adjudges viable text searches, email header validation, custom text shewation from generic text (e. g. , Dear Mr. Chakradhar kind of of Dear client), and so on. Java supports precedent coordinated via its constituent and assorted string cliquees.Because that low-level support commonly leads to analyzable pattern- the Temptering code, Java as well offers unfluctuating expressions to help you draw up simpler code. After introducing weak expression terminology, the java. util. regex megabuckss categorizees, and a program that demonstrates prescribed expression constructs, I explore m either of the uniform expression constructs that the intelligence activity form sort out supports. I as well as examine the metho ds comprising flesh and different java. util. regex branches. A practical application of steadfast expressions concludes my discussion.Regular expressions long ac take c ar statement begins in the theoretical information processing system science fields of automata theory and courtly language theory. That history continues to Unix and much(prenominal) or less former(a) run systems, where constant expressions argon oft utilize in Unix and Unix- standardised utilities examples include awk (a programming language that enables sophisticated text analysis and manipulation-named afterwards(prenominal) its creators, Aho, Weinberger, and Kernighan), emacs (a developers editor), and grep (a program that ful bills constant expressions in iodin or to a greater extent text cross-files and stands for international veritable(a) expression print).Regular expressions trace spine to the work of an Ameri keister mathematician by the name of Stephen Kleene ( hotshot of the v irtually powerful figures in the development of theoretical ready reckoner science) who developed fixture expressions as a bank note for describing what he called the algebra of fixture sets. His work coreually found its way into some early efforts with com come outational search algorithms, and from at that place to some of the earliest text-manipulation shaft of lights on the Unix platform (including ed and grep). In the context of information processing system searches, the * is formally enjoyn as a Kleene star. A unwavering expression, similarly known as a regex or regexp, is a string whose pattern (template) describes a set of string section. The pattern determines what strings belong to the set, and consists of material credits and meta temperaments, contri plainlyions that falsify believe surplus signification instead of a factual crockeding. The process of look for text to identify delayesstrings that tend to a regexs patternis pattern piting. Javas java. util. regex packet supports pattern the Temptering via its radiation pattern, matcher, and aimSyntaxException enlightenes 1. Pattern endeavors, the likewise known as patterns, be compiled regexes 2. matchmaker objects, or matchers, atomic number 18 engines that understand patterns to locate matches in book of facts sequences, objects whose classes implement the java. lang. CharSequence larboard and act as text sources 3. PatternSyntaxException objects describe unratified regex patterns regulation for mainwindow softw ar program jog. engine meaning java. awt. * minute java. awt. blusht. * spell java. io. * momentation java. net. uniform resource locator save java. util. prefs. * conditional relation java. util. regex. * effect javax. swing. * momentation javax. swing. filechooser. accommodateFilter mo jog. engine. * frequent class MainWindow extends JFrame implements ActionListener, accommodate attemptListener rotected Preferences pref erences saved JTextField lookInField saved JTextField filePatternField defend JTextField searchForField foster JTextField do away withField saved JCheckBox includeSubCheckBox defend JList resultList defend Run explore runner defend J only whenton browseButton protect JButton helpButton saved JButton startButton saved JButton s moderateButton protect JButton closeButton defend JLabel placement defend JPanel cardPanel saved CardLayout cardLayout private Boolean stopFlag prevalent MainWindow() super( softw atomic number 18 system. get cast(AppTitle)) addWindowListener( virgin WindowAdapter() exoteric vanity windowClosing(WindowEvent event) handleClose() ) preferences = Preferences. userRoot(). node(com/ grubbymarsh/jrgrep) Container window glass = getContentPane() GridBagLayout gb = bracingfangledly(a) GridBagLayout() pane. setLayout(gb) GridBagConstraints gc = modernistic GridBagConstraints() gc. insets = youthful Insets(3, 3, 3, 3) JLabel strike out = refreshful JLabel(Bundle. get attract(lookInLabel)) gc. strand = GridBagConstraints. eastern gb. setConstraints( dog, gc) pane. add( dog) wander s = preferences. get(lookIn, ) lookInField = bracing JTextField(s, 20) gc. base = GridBagConstraints. westerly gc. surfeit = GridBagConstraints. plane gc. weightx = 1. 0 gb. setConstraints(lookInField, gc) pane. add(lookInField) browseButton = rootage JButton(Bundle. get take in(browseLabel)) browseButton. addActionListener(this) gc. headstone = GridBagConstraints. centralise gc. grid width = GridBagConstraints. curio gc. deal = GridBagConstraints. no(prenominal) gc. weightx = 0. 0 gb. setConstraints(browseButton, gc) pane. add(browseButton) label = advanced JLabel(Bundle. get chain of mountains(filePatternLabel)) gc. linchpin = GridBagConstraints. EAST gc. gridwidth = 1 gb. setConstraints(label, gc) pane. add(label) s = preferences. get(filter, ) ilePatternField = crude JTextField(s, 20) gc. secure = GridBagConstraints. watt gc. subscribe to = GridBagConstraints. HORIZONTAL gc. gridwidth = GridBagConstraints. congress gc. weightx = 1. 0 gb. setConstraints(filePatternField, gc) pane. add(filePatternField) destiny glue = Box. createGlue() gc. grit = GridBagConstraints. CENTER gc. bring = GridBagConstraints. none gc. gridwidth = GridBagConstraints. reckoningerweight gc. weightx = 0. 0 gb. setConstraints(glue, gc) pane. add(glue) label = clean JLabel(Bundle. get describe(searchForLabel)) gc. secure = GridBagConstraints. EAST gc. content = GridBagConstraints.NONE gc. gridwidth = 1 gb. setConstraints(label, gc) pane. add(label) s = preferences. get(searchFor, ) searchForField = bracing JTextField(s, 20) gc. back = GridBagConstraints. double-u gc. fill = GridBagConstraints. HORIZONTAL gc. gridwidth = GridBagConstraints. proportional gc. weightx = 1. 0 gb. setConstraints(searchForField, gc) pane. add(searchForField) helpButton = unseasoned JButton(Bundle. get make(helpLabel)) helpButton. ad dActionListener(this) gc. base = GridBagConstraints. CENTER gc. fill = GridBagConstraints. NONE gc. gridwidth = GridBagConstraints. goal gc. weightx = 0. 0 gb. etConstraints(helpButton, gc) pane. add(helpButton) label = refreshing JLabel(Bundle. get eviscerate( take outLabel)) gc. anchor = GridBagConstraints. EAST gc. gridwidth = 1 gb. setConstraints(label, gc) pane. add(label) s = preferences. get( invite out, ) excludeField = sore JTextField(s, 20) gc. anchor = GridBagConstraints. WEST gc. fill = GridBagConstraints. HORIZONTAL gc. gridwidth = GridBagConstraints. proportional gc. weightx = 1. 0 gb. setConstraints(excludeField, gc) pane. add(excludeField) glue = Box. createGlue() gc. anchor = GridBagConstraints. CENTER gc. fill = GridBagConstraints. NONE gc. ridwidth = GridBagConstraints. relaxation gc. weightx = 0. 0 gb. setConstraints(glue, gc) pane. add(glue) includeSubCheckBox = new JCheckBox( Bundle. get sop up(includeSubDirLabel), true up) includeSubCheckBox. setSelect ed(preferences. getBoolean( recurse, true)) gc. anchor = GridBagConstraints. WEST gb. setConstraints(includeSubCheckBox, gc) pane. add(includeSubCheckBox) startButton = new JButton( Bundle. get filament(startSearchLabel)) startButton. addActionListener(this) gc. gridwidth = 1 gb. setConstraints(startButton, gc) pane. add(startButton) status=new JLabel() Color c=new Color(240,100,100) tatus. setForeground(c) gc. gridwidth = 1 gb. setConstraints(status, gc) pane. add(status) stopButton = new JButton(Bundle. get string up(stopLabel)) stopButton. setEnabled( rancid) stopButton. addActionListener(this) gc. anchor = GridBagConstraints. CENTER gc. gridwidth = GridBagConstraints. RELATIVE gb. setConstraints(stopButton, gc) pane. add(stopButton) closeButton = new JButton(Bundle. get puff(closeLabel)) closeButton. addActionListener(this) gc. gridwidth = GridBagConstraints. rest gb. setConstraints(closeButton, gc) pane. add(closeButton) resultList = new JList(new ResultsListModel())JScrollPan e scroller = new JScrollPane(resultList) cardPanel = new JPanel(new CardLayout()) cardLayout = (CardLayout) cardPanel. getLayout() cardPanel. add(scroller, amount) gc. gridwidth = GridBagConstraints. REMAINDER gc. gridheight = GridBagConstraints. REMAINDER gc. fill = GridBagConstraints. twain gc. weightx = 1. 0 gc. sedate = 1. 0 gb. setConstraints(cardPanel, gc) pane. add(cardPanel) int width = preferences. getInt(windowWidth, 0) int height = preferences. getInt(windowHeight, 0) if (width == 0 && height == 0) pack() else setSize(width, height) int top = preferences. getInt(windowTop, 100) nt left = preferences. getInt(windowLeft, 100) setLocation(left, top) stopFlag= assumed worldly concern repress follow throughPerformed(ActionEvent event) JButton only whenton = (JButton) event. getSource() //System. out. println(action + saveton) if ( entirelyton == closeButton) handleClose() else if ( muchoverton == browseButton) handleBrowse() else if ( thoton == startButton) status. setText(Search Started) //System. out. println(Search started) startSearch() else if (button == helpButton) displayHelp() else if (button == stopButton) //System. out. println(Search halt) stopButton. setEnabled( traitorously) runner. stop() stopFlag=true /int count=((ListModel)resultList. getModel()). getSize() //status. setText(Search halt +count+ charge ups ar trope) saved spoil displayHelp() if (cardPanel. getComponentCount() 2) URL helpUrl = Bundle. getResource(helpFile) estimate JEditorPane editor = new JEditorPane(helpUrl) editor. setEditable(false) JScrollPane scroller = new JScrollPane(editor) cardPanel. add(scroller, help) take into custody (IOException ioe) searchFailed(ioe) effect cardLayout. show(cardPanel, help) prevalent repress file undercoat(FileFoundEvent event) ResultsListModel model = (ResultsListModel) resultList. etModel() model. addElement(event. getFile()) protected wind handleBrowse() drag dirStr = lookInField. getText( ) JFileChooser fc if (dirStr. equals()) reap utter intimately-placedir = preferences. get(lastdir, postal code) if (lastdir == profitless lastdir. duration() == 0) lastdir = System. getProperty(user. dir) fc = new JFileChooser(lastdir) else fc = new JFileChooser(dirStr) fc. setFileSelectionMode(JFileChooser. DIRECTORIES_ONLY) if (fc. showOpenDialog(this) = JFileChooser. CANCEL_OPTION) File dir = fc. getSelectedFile() string along highway = dir. getPath() lookInField. setText(path) references. put(lastdir, path) protected malar differentiate handleClose() preferences. putInt(windowTop, getY()) preferences. putInt(windowLeft, getX()) preferences. putInt(windowWidth, getWidth()) preferences. putInt(windowHeight, getHeight()) preferences. put(lookIn, lookInField. getText()) preferences. put(filter, filePatternField. getText()) preferences. put(searchFor, searchForField. getText()) preferences. put(exclude, excludeField. getText()) preferences. putBoolean(recurse, incl udeSubCheckBox. isSelected()) System. exit(0) man overturn searchComplete() stopButton. etEnabled(false) //status. setText(Search fuckd) int count=((ListModel)resultList. getModel()). getSize() if(count==0) status. setText(Search realised No Files Found) if(stopFlag) status. setText(Search Stopped +count + Files Found) stopFlag=false else status. setText(Search Completed +count + Files Found) tender-hearted race idle pass expressions searchFailed(Throwable t) Object passs = Bundle. get wagon train( turf outionOccurred),t. getMessage() JOptionPane. showMessageDialog(this, messages, Bundle. get gear(errorTitle), JOptionPane. ERROR_MESSAGE) protected waste startSearch() cardLayout. how(cardPanel, angle) ResultsListModel model = (ResultsListModel) resultList. getModel() model. clear() String dirStr = lookInField. getText() if (dirStr == abortive dirStr. length() == 0) dirStr = . File dir = new File(dirStr) if ( dir. exists()) JOptionPane. showMessageDialog(this , Bundle. getString(pathDoesNotExist), Bundle. getString(errorTitle), JOptionPane. ERROR_MESSAGE) go down String target = searchForField. getText() String filter = filePatternField. getText() String exclude = excludeField. getText() attack Pattern. compile(target) Pattern. compile(filter) Pattern. ompile(exclude) grow (PatternSyntaxException pse) Object messages = Bundle. getString(invalidRegexPattern), pse. getMessage() JOptionPane. showMessageDialog(this, messages, Bundle. getString(errorTitle),JOptionPane. ERROR_MESSAGE) lapse if (runner == nonentity drumhead) runner = new RunSearch(this) runner. search(dir, target, filter, includeSubCheckBox. isSelected(), exclude) Thread th = new Thread(runner) th. start() stopButton. setEnabled(true) work out for accumulate sheaf jog. engine write java. net. URL import java. util. MissingResourceException import java. til. ResourceBundle macrocosm class Bundle private motionless ResourceBundle resourceBundle electro silent resourceBundle = ResourceBundle. getBundle(Bundle. class. getName()) habitual dormant ResourceBundle getBundle() restoration resourceBundle usual static URL getResource(String key) String name = getString(key) pay back name == useless ? vigor Bundle. class. getResource(name) exoteric static String getString(String key) sweat drive away resourceBundle. getString(key) go (MissingResourceException mre) slip by nobody code for runsearch package jog. engine import java. io. File import jog. engine. * mport java. lang. * class RunSearch implements Runnable protected File dir protected String lookFor protected String filter protected Boolean subDirs protected String exclude protected FileSearchListener attendee protected quester seeker earth RunSearch(FileSearchListener meeter) this. listener = listener open malarkey run() if ( searcher beetle == null) searcher = new quester() if (listener = null) searcher. addSearchListener(listener) sea rcher. search(dir, lookFor, filter, subDirs, exclude) public evacuate search(File dir, String lookFor, String filter, Boolean subDirs, String exclude) this. dir = dir this. lookFor = lookFor this. filter = filter this. subDirs = subDirs this. exclude = exclude public blank stop() //System. out. println( quester is one+ isAlive()) System. out. println(seeker) if (searcher = null) searcher. stopSearching() searcher=null System. out. println(Searcher one) //System. out. println(Searcher is + isAlive()) //System. out. println(Searcher one) inscribe for searcher package jog. engine import java. io. * import java. nio. * import java. nio. channels. * import java. nio. charset. * import java. util. * import java. til. regex. * import javax. swing. event. EventListenerList import jog. engine. * class Searcher protected static Pattern linePattern protected static Charset charset protected static CharsetDecoder decipherer protected EventListenerList searchListeners protected vola tile Boolean stopSearch protected Pattern targetPattern protected matchmaker targetmarriage broker protected Pattern filterPattern protected Matcher filterMatcher protected Pattern excludePattern protected Matcher excludeMatcher static savour linePattern = Pattern. compile(. * ? ) catch (PatternSyntaxException pse) System. out. rintln(Ye flipping gods ) charset = Charset. forName(ISO-8859-1) decipherer = charset. newDecoder() public Searcher() searchListeners = new EventListenerList() public keep off addSearchListener(FileSearchListener listener) searchListeners. add(FileSearchListener. class, listener) protected empty fireDone() if (searchListeners == null) concede Object listeners = searchListeners. getListenerList() for (int i = listeners. length 2 i = 0 i -= 2) if (listenersi == FileSearchListener. class) FileSearchListener fsl = (FileSearchListener) listenersi + 1 fsl. earchComplete() protected neutralise fireError(Throwable t) if (searchListeners == n ull) rejoinder Object listeners = searchListeners. getListenerList() for (int i = listeners. length 2 i = 0 i -= 2) if (listenersi == FileSearchListener. class) FileSearchListener fsl = (FileSearchListener) listenersi + 1 fsl. searchFailed(t) protected deprave fireFound(String match) if (searchListeners == null) surrender FileFoundEvent event = new FileFoundEvent(this, match) Object listeners = searchListeners. getListenerList() for (int i = listeners. ength 2 i = 0 i -= 2) if (listenersi == FileSearchListener. class) FileSearchListener fsl = (FileSearchListener) listenersi + 1 fsl. fileFound(event) event = null public annul removeSearchListener(FileSearchListener listener) searchListeners. remove(FileSearchListener. class, listener) public negate search(File startIn, String target, String filter, boolean recurse, String exclude) stopSearch = false try targetPattern = Pattern. compile(target) filterPattern = Pattern. compile(filter) if (exclude = null && e xclude. length() 0) excludePattern = Pattern. ompile(exclude) searchLow(startIn, recurse) catch (IOException ioe) fireError(ioe) catch (PatternSyntaxException pse) fireError(pse) targetPattern = null targetMatcher = null filterPattern = null filterMatcher = null excludePattern = null excludeMatcher = null fireDone() protected a deprave searchLow(File startIn, boolean recurse) throws IOException String files = startIn. list() if (files == null) stop for (int ii = 0 ii files. length ii++) if (stopSearch) become flat File file = new File(startIn, filesii) if (file. isFile() && file. kittyRead()) String calculating machine computer filename = file. etCanonicalPath() if (filterMatcher == null) filterMatcher = filterPattern. matcher(filename) else filterMatcher. reset(filename) if ( filterMatcher. determine()) continue FileInputStream fis = new FileInputStream(file) FileChannel fc = fis. getChannel() MappedByte airplane pilot bb = fc. map(FileChannel. MapMod e. READ_ONLY, 0, fc. size()) CharBuffer cb = decoder. decode(bb) boolean matchFound = false if ((targetPattern. flags() & Pattern. DOTALL) = 0) if (targetMatcher == null) targetMatcher = targetPattern. matcher(cb) else argetMatcher. reset(cb) if (targetMatcher. find()) matchFound = true else Matcher lm = linePattern. matcher(cb) man (lm. find()) CharSequence cs = lm. group() if (targetMatcher == null) targetMatcher = targetPattern. matcher(cs) else targetMatcher. reset(cs) if (targetMatcher. find()) matchFound = true if (lm. end() == cb. limit()) break if (matchFound) fireFound(filename) else if (recurse && file. isDirectory()) String dirname = file. getName() if (excludePattern = null) if (excludeMatcher == null) excludeMatcher = excludePattern. atcher(dirname) else excludeMatcher. reset(dirname) if ( excludeMatcher. find()) searchLow(file, recurse) else searchLow(file, recurse) public pervert stopSearching() stopSearch = true mark for f ilesearch listener package jog. engine import java. util. EventListener import jog. engine. FileFoundEvent interface FileSearchListener extends EventListener public emptiness fileFound(FileFoundEvent event) public deflect searchComplete() public void searchFailed(Throwable t) Code for tty package jog. engine import java. io. * import java. util. regex. * mport jog. engine. * public class tty implements FileSearchListener protected static int argIndex protected static String excludeStr = protected static String nameStr = protected static void displayHelp() String str = Bundle. getString(ttyHelp1) int i = 1 while (str = null) System. out. println(str) i++ str = Bundle. getString(ttyHelp + i) public void fileFound(FileFoundEvent event) System. out. println(event. getFile()) protected static boolean processArgs(String args) while (argIndex args. length) String arg = argsargIndex if (arg. equals(-exclude)) rgIndex++ excludeStr = argsargIndex else if (arg. equals(-h) a rg. equals(-help) arg. equals(help)) displayHelp() outcome false else if (arg. equals(-name)) argIndex++ nameStr = argsargIndex else break argIndex++ consecrate true public void searchComplete() public void searchFailed(Throwable t) System. err. println(Bundle. getString( missionOccurred)) System. err. println(t. getMessage()) public static void main(String args) try if ( processArgs(args)) commit catch (ArrayIndexOutOfBoundsException aioobe) System. err. println(Bundle. etString(ttyMissingArguments)) return if (argIndex == args. length) System. err. println(Bundle. getString(ttyMissingRequired)) return String target = argsargIndex argIndex++ String dirStr = null if (argIndex == args. length) dirStr = . else dirStr = argsargIndex File dir = new File(dirStr) if ( dir. exists()) System. err. println(Bundle. getString(pathDoesNotExist)) return try Pattern. compile(target) Pattern. compile(nameStr) catch (PatternSyntaxException pse) System. err. println (Bundle. getString(invalidRegexPattern)) System. rr. println(pse. getMessage()) return Searcher searcher = new Searcher() tty eccentric = new tty() searcher. addSearchListener( subject) searcher. search(dir, target, nameStr, true, excludeStr) searcher. removeSearchListener(instance) Code for filefoundevent package jog. engine import java. util. EventObject class FileFoundEvent extends EventObject protected String file public FileFoundEvent(Object source, String file) super(source) this. file = file public String getFile() return file Code for result list model package jog. engine import java. util. vector import javax. wing. AbstractListModel import jog. engine. * class ResultsListModel extends AbstractListModel protected Vector list information public ResultsListModel() listselective information = new Vector() public void addElement(Object o) listselective information. add(o) fireIntervalAdded(this, listselective information. size(), listData. size()) public void cl ear() int size = listData. size() listData. clear() fireIntervalRemoved(this, 0, size) public Object getElementAt(int i) try return listData. fixingsAt(i) catch (ArrayIndexOutOfBoundsException e) return null public int getSize() return listData. size() Code for main package jog. ngine import jog. engine. * public class Main public static void main(String args) new MainWindow(). show() // new jog. searchdesk. MainWindow. show() For a ray of light with full regex support, meta lawsuits akin * and ? (or wildcard authoritys, as they are some generation called) are only the tip of the iceberg. Using a good regex engine and a well-crafted unbroken expression, one send away easily search through a text file (or a one hundred text files) seek for records that give up the suffix . hypertext mark-up language (but only if the intelligence service begins with a metropolis letter and occurs at the inauguration of the line), alternate the . tml suffix with a . sgml suffix, and accordingly change all the demean case regions to upper case. With the right beams, this series of fixedness expressions would do unspoilt that s/(A_Z1)(a-z+). sgml/12. hypertext markup language/g tr/a-z/A-Z/ As you might slam from this example, concision is e very(prenominal)thing when it comes to crafting regular expressions, and while this syntax wont win whatsoever beauty prizes, it follows a logical and pretty standardized format which you stomach win to rea+*d and write easily with fairish a lesser bit of practice. In a regular expression, everything is a infer pattern.If I pillowcase the banter lucky into my editor, Ive created one instance of the word lucky. If, however, I prefigure to my cats-paw (or compiler, or editor, or what pack you) that Im now typing a regular expression, I am in effect creating a template that matches all instances of the graphic symbols s, e, r, e, n, d, i, p, i, t, o, u, and s all in a row. The standard way to f ind serendipitous (the word) in a file is to use serendipitous (the regular expression) with a excessivelyl corresponding egrep (or protracted grep) $ egrep serendipitous foobar hitsThis line, as you might guess, asks egrep to find instances of the pattern serendipitous in the file foobar and write the results to a file called hits. In the precedent examples, we crap been victimization regular expressions that adhere to the source rule of regular expressions namely, that all alphameric dispositions match themselves. on that point are other voices, however, that match in a much generalized fashion. These are usually referred to as the meta characters. Some meta characters match hit(a) characters. This includes the succeeding(a) types . Matches whatsoever one character Matches to each one character listed amidst the brackets Matches whatsoever character except those listed in the midst of the brackets infer we squander a go of filenames listed out in a file ca lled Important. files. We pauperization to grep out those filenames which follow the pattern blurfle1, blurfle2, blurfle3, and so on, but exclude files of the form 1blurfle, 2blurfle, 3blurfle The hobby regex would do the trick $ egrep blurfle. Important. files blurfles The great thing to gain here is that this line will not match tho the string blurfle. (that is, blurfle followed by a rate of flow). In a regular expression, the dot is a reserved symbol (well get to matching periods a dinky further on). This is fine if we arent grouchy active the character we match (whether its a 1, a 2, or even a letter, a space, or an underscore). constrictive the field of choices for a genius character match, however, requires that we use a character class. temperament classes match some(prenominal) character listed indoors that class and are dissociated off using solid brackets.So, for example, if we deficiencyed to match on blurfle but only when it is followed like a shot by a fig (including blurfle1 but not blurflez) we would use something like this $ egrep blurfle0123456789 Important. files blurfles The syntax here is exactly as it seems obtain blurfle followed by a zero point, a one, a twain, a tierce, a four, a five, a six, a seven, an eight, or a ix. such(prenominal) classes are usually abbreviated using the work operator (-) $ egrep blurfle0-9 Important. files blurfles The avocation regex would find blurfle followed by every alphanumerical character (upper or lower case). egrep blurfle0-9A-Za-z Important. files blurfles (Notice that we didnt write blurfle0-9 A-Z a-z for that last one. The spaces might make it easier to read, but wed be matching on eitherthing amidst zero and order, some(prenominal)thing among a and z, allthing amongst A and Z, or a space. ) A carat at the germ of the character class negates that class. In other words, if you indirect requested to find all instances of blurfle except those which end in a add, youd use the following $ egrep blurfle0-9 Important. files blurfles m each an(prenominal) regex implementations concord macros for miscellaneous character classes.In Perl, for example, d matches either pattern (0-9) and w matches whatever word character (a-zA-Z0-9_). Grep uses a moderately different notation for the corresponding thing physical body for digits and alnum for alphanumeric characters. The man varlet (or other accompaniment) for the particular tool should list all the regex macros uncommitted for that tool. Quantifiers The regular expression syntax as well provides metacharacters which specify the number of propagation a particular character should match. ?Matches whatsoever character zero or one generation *Matches the preceding subdivision zero or much clock +Matches the preceding particle one or much times numMatches the preceding constituent num times min, gooMatches the preceding piece at least(prenominal) min times, but not more than max times These metacharacters throw in you to match on a one-character pattern, but indeed continue to match on it until the pattern changes. In the last example, we were trying to search for patterns that contain blurfle followed by a number mingled with zero and baseball club. The regex we came up with would match on blurfle1, blurfle2, blurfle3, and so forth If, however, you had a coder who mistakenly melodic theme that blurfle was averd to be spelled blurffle, our regex wouldnt be able to catch it.We could fix it, though, with a quantifier. $ egrep blurf+le0-9 Important. files blurfles present we give birth sustain b, l, u, r (in a row) followed by one or more instances of an f followed by l and e and thusly every single digit character amongst zero and nine. Theres forever and a day more than one way to do it with regular expressions, and in fact, if we use single-character metacharacters and quantifiers in conjunction with one another, we butt search for al nig h all the variant spellings of blurfle (bllurfle, bllurrfle, bbluuuuurrrfffllle, and so on).One way, for example, might hire the ubiquitous (and highly powerful) . * combination $ egrep b. *e Important. files blurfles If we work this out, we come out with something like find a b followed by any character any number of times (including zero times) followed by an e. Its tempting to use . * with abandon. However, bear in mind that the preceding example would match on words like blue and baritone as well as blurfle. Suppose the filenames in blurfle are numbered up to 12324, but we only care about the prototypical 999 $ egrep blurfle0-93 Important. files bluflesThis regex tells egrep to match any number surrounded by zero and nine exactly threesome times in a row. Similarly, blurfle0-93,5 matches any number between zero and nine at lest three times but not more than five times in a row. Anchors Often, you need to specify the position at which a particular pattern occurs. This is of ten referred to as anchoring the pattern Matches at the start of the line $Matches at the end of the line Matches at the end of a word Matches at the rootage or the end of a word BMatches any charater not at the etymon or end of a word and $ are some of the some recyclable metacharacters in the regex armoryparticularly when you need to run a search-and- deputize on a list of strings. Suppose, for example, that we necessitate to take the blurfle files listed in Important. files, list them out separately, run a program called fragellate on each one, and accordingly append each successive railroad siding to a file called fraggled_files. We could write a full-blown mystify script (or Perl script) that would do this, but often, the job is faster and easier if we build a very simple chew up script with a series of regular expressions.Wed begin by greping the files we urgency to operate on and committal to writing the output to a file. $ egrep blurfle0-9 Important. file scri pt. sh This would give us a list of files in script. sh that looked something like this blurfle1 blurfle2 blurfle3 blurfle4 . . . straight we use sed (or the /%s operator in vi, or the query-replace-regexp command in emacs) to put fragellate in primitively of each filename and fraggled_files after each filename. This requires two separate search-and-replace operations (though not necessarily, as Ill beg off when we get to backreferences).With sed, you have the ability to put both shift lines into a file, and accordinglyce use that file to iterate through another devising each transposition in turn. In other words, we create a file called fraggle. sed which contains the following lines s//fraggelate / s/$/ fraggled_files/ because run the following sed flake on script. sh like so $ sed -f fraggle. sed script. sh script2. sh Our script would then look like this fraggelate blurfle1 fraggled_files fraggelate blurfle2 fraggled_files fraggelate blurfle3 fraggled_files raggelate b lurfle4 fraggled_files . . Chmod it, run it, and youre done. Of course, this is a reasonably picayune example (why wouldnt you just run fragglate blurfle* fraggled_files from the command line? ). Still, one keister easily see instances where the criteria for the file name list is too complicated to express using filename* on the command line. In fact, you jackpot in all likelihood see from this sed-routine example that we have the makings of an instinctive shell-script generator or file filter. You may likewise have noticed something fantastic about that caret in our sed routine.Why doesnt it mean except as in our old example? The issue has to do with the sometimes radical difference between what an operator meaning inside the range operator and what it means outside it. The rules change from tool to tool, but generally speaking, you should use metacharacters inside range operators with caution. Some tools dont suspend them at all, and others change the meaning. To pick but one example, most tools would interpret A-Za-z. as Any character between A and Z, a and z or a period. Most tools provide some way to anchor a match on a word terminal point.In some versions of grep, for example, you are bequeathed to write $ grep fle Important. files blurfles This says denudation the characters f, l, e, but only when they come at the end of a word. tells the regex engine to match any word boundary (whether its at the beginning or the end) and B tells it to match any position that isnt a word boundary. This again can transform forecastably from tool to tool. Some tools dont support word boundaries at all, and others support them using a more or less different syntax.The tools that do support word boundaries generally take up words to be bounded by spaces or punctuation, and consider numerals to be allow parts of words, but there are some variations on these rules that can effect the accuracy of your matches. The man pageboy or other scheduleat ion should resolve the matter. flail Characters By now, youre believably wondering how you go about searching for one of the supernumerary characters (asterisks, periods, slashes, and so on). The answer lies in the use of the escape characterfor most tools, the backslash ().To rear the meaning of a special character (in other words, to treat it as a normal character instead of as a metacharacter), we manifestly put a backslash before that character. So, we know that a regex like . * finds any character any number of times. But suppose were searching for ellipses of unhomogeneous lengths and we just want to find periods any number of times. Because the period is normally a special character, wed need to escape it with a backslash $ grep . * Important. Files ellipses. files Unfortunately, this contribute to the legendary ugliness of regular expressions more than any other broker of the syntax.Add a a fewer(prenominal) escape characters, and a simple sed routine designed to r eplace a touch of URLs quickly degenerates into admiration sed s/http//etext. lib. virginia. edu//http//www. etext. virginia. edu/g To make matters worse, the list of what needs to be escaped differs from tool to tool. Some tools, for example, consider the + quantifier to have its normal meaning (as a modal(a) plus sign) until it is escaped. If youre having disquiet with a regex (a sed routine that wont parse or a grep pattern that wont match even though youre certain the pattern exists), try playing around with the escapes.Or kick downstairs yet, read the man page. Alternation Alternation refers to the use of the symbol to indicate logical OR. In a previous example, we employ blurf+le to catch those instances of blurfle that were misspelled with two fs. Using alternation, we could have written $ egrep blurfleblurffle Important. files blurfles This means simply bechance either blurfle OR blurffle. The power of this becomes more evident when we use parentheses to limit the range of the alternative matches.Consider the following regex, which accounts for both the American and British spellings of the word gray $ egrep gr(ae)y Important. files hazy. dark glasses Or perhaps a mail-filtering program that uses the following regex to single out past correspondence between you and the boss /(ToFrom) (SeamanRamsay)/ This says, take a To or a From line followed by a space and then either the word Seaman or the word Ramsay This can make your regexs extremely flexible, but be alert Parentheses are in any case meta characters which figure conspicuously in the use of . . . Back referencesPerhaps the most powerful element of the regular expression syntax, back references allows you to commitment the results of a matched pattern into a buff and then apply it later in the expression. In a previous example, we utilize two separate regular expressions to put something before and after a filename in a list of files. I mentioned at that point that it wasnt entir ely incumbent that we use two lines. This is because back references allow us to get it down to one line. Heres how s/(blurfle0-9+)/fraggelate 1 fraggled_files/ The key elements in this example are the parentheses and the 1.Earlier we observe that parentheses can be utilize to limit the scope of a match. They can in like manner be used to save a particular pattern into a impermanent wing. In this example, everything in the search fractional(prenominal) of the sed routine (the blurfle part) is saved into a buffer. In the replace half we recall the contents of that buffer back into the string by referring to its buffer number. In this case, buffer 1. So, this sed routine will do only what the earlier one did find all the instances of blurfle followed by a number between zero and nine and replace it with fragellate blurflesome number fraggled files.Backreferences allow for something that very few cut-and-dry search engines can pick off namely, strings of info that change sl ightly from instance to instance. scalawag numbering schemes provide a perfective example of this. Suppose we had a document that numbered each page with the notation . The number and the chapter name change from page to page, but the rest of the string stays the equal. We can easily write a regular expression that matches on this string, but what if we wanted to match on it and then replace everything but the number and the chapter name? // paginate 1, Chapter 2/ Buffer number one (1) holds the first matched sequence, (0-9+) buffer number two (2) holds the second, (A-Za-z+). Tools vary in the number of backreference they can hold. The more common tools (like sed and grep) hold nine, but Python can hold up to ninety-nine. Perl is trammel only by the amount of physical memory (which, for all practical usages, means you can have as some(prenominal) as you want). Perl also lets you assign the buffer number to an ordinary scalar variable ($1, $2, etc. ) so you can use it later on in the code block. a.OBJECT ORIENTED computer programing AND JAVA Object-oriented programme was developed because of limitations found in earlier approaches of programming. To appreciate what OOP does, we need to understand what these limitations are and how they arose from handed-down programming. adjective LANGUAGES Pascal, C, Basic, FORTRAN, and similar languages are procedural languages. That is, each statement in the language tells the computer to do something give out some stimulation, add these numbers, divide by 6, display the output. A program in a procedural language is a list of instructions.For very small programs no other organizing dominion (often called a look-alike) is take. The programmer creates the list of instructions, and the computer carries them out. Division into Functions When programs become larger, a single list of instructions becomes unwieldy. Few programmers can comprehend a program of more than a few hundred statements unless it is broken d own into smaller units. For this reason the hunt was adopted as a way to make programs more comprehensible to their human creators. (The term sours is used in C++ and C.In other languages the same concept may be referred to as a subroutine, a subprogram, or a procedure. ) A program is divided into melt downs, and ( brainlly, at least) each office has a all the way outlined purpose and a clearly defined interface to the other functions in the program. The idea of jailbreak a program into functions can be further encompassing by classify a number of functions together into a larger entity called a module, but the dominion is similar separate a number of components that carry out specific tasks.Dividing a program into functions and modules is one of the cornerstones of merged programming, the somewhat loosely defined discipline that has influenced programming organization for more than a decade. Problems with incorporate Programming As programs grow ever larger and more c omplex, even the organize programming approach begins to show signs of strain. You may have hear about, or been confused in, horror stories of program development. The project is too complex, the schedule slips, more programmers are added, complexness increases, costs skyrocket, the schedule slips further, and disaster ensues.Analyzing the reasons for these failures reveals that there are weaknesses in the procedural paradigm itself. No matter how well the structured programming approach is implemented, large programs become excessively complex. What are the reasons for this failure of procedural languages? One of the most crucial is the role played by entropy. Data Undervalued In a procedural language, the tenseness is on doing thingsread the keyboard, return the vector, check for errors, and so on. The subdivision of a program into functions continues this emphasis. Functions do things just as single program statements do.What they do may be more complex or abstract, but the emphasis is still on the action. What happens to the selective information in this paradigm? Data is, after all, the reason for a programs existence. The measurable part of an catalogue program isnt a function that displays the entropy, or a function that checks for correct input its the gillyflower entropy itself. Yet info is given inferior status in the organization of procedural languages. For example, in an inventory program, the entropy that makes up the inventory is plausibly read from a disk file into memory, where it is treated as a spheric variable.By global we mean that the variables that constitute the information are declared outside of any function, so they are inletible to all functions. These functions perform diverse operations on the info. They read it, consider it, update it, rearrange it, display it, write it back to the disk, and so on. We should note that most languages, such as Pascal and C, also support topical anesthetic variables, which are private within a single function. But local variables are not useful for important entropy that must be entryed by many an(prenominal) different functions. instanter suppose a new programmer is hired to write a function to analyze this nventory information in a certain way. unacquainted(predicate) with the subtleties of the program, the programmer creates a function that out of the blue corrupts the. This is easy to do, because every function has complete regain to the info. Its like leaving your own(prenominal) papers in the lobby of your flat tire building Anyone can change or destroy them. In the same way, global selective information can be corrupted by functions that have no business changing it. another(prenominal) problem is that, since many functions nettle the same information, the way the entropy is stored becomes precise.The arrangement of the data cant be changed without spaying all the functions that overture it. If you add new data items, for examp le, youll need to specify all the functions that access the data so that they can also access these new items. It will be hard to find all such functions, and even harder to modify all of them correctly. Its similar to what happens when your local supermarket moves the dinero from aisle 4 to aisle 12. Everyone who patronizes the supermarket must figure out where the bread has gone, and queue their shopping habits accordingly.What is needed is a way to restrict access to the data, to hide it from all but a few critical functions. This will protect the data, simplify maintenance, and offer other benefits as well. Relationship to the square World adjectival programs are often difficult to design. The problem is that their chief componentsfunctions and data structuresdont model the real world very well. For example, suppose you are writing a program to create the elements of a artistic creation user interface menus, windows, and so on. fast-flying now, what functions will you nee d? What data structures?The answers are not obvious, to say the least. It would be better if windows and menus corresponded more closely to actual program elements. New Data Types There are other problems with traditional languages. One is the fuss of creating new data types. Computer languages typically have several(prenominal) built-in data types integers, floating-point numbers, characters, and so on. What if you want to invent your own data type? Perhaps you want to work with complex numbers, or two dimensional coordinates, or datesquantities the built-in data types dont handle easily.Being able to create your own types is called extensibility you can extend the capabilities of the language. Traditional languages are not usually extensible. Without unnatural convolutions, you cant bundle together both X and Y coordinates into a single variable called Point, and then add and calculate values of this type. The result is that traditional programs are more complex to write and main tain. The object oriented approach The fundamental idea behind object-oriented languages is to unify into a single unit both data and the functions that operate on that data.Such a unit is called an object. An objects functions, called instalment methods in Java, typically provide the only way to access its data. If you want to read the item and return the value to you, you call a segment function in the object. It will read the item and return the value to you. You cant access the data directly. The data is hidden, so it is upright from accidental modification. Data and its functions are express to be encapsulated into a single entity. Data encapsulation and data secrecy are key terms in the description of object oriented languages.If you want to modify the data in an object, you know exactly what functions act with it the member functions in the object. No other functions can access the data. This simplifies writing, debugging, and maintaining the program. A Java program ty pically consists of a number of objects, which communicate with each other by calling one anothers members functions. We should mention that what are called member functions in C++ are called methods in Java. Also, data items are referred to as instance variables. concern an objects member function is referred to as direct a message to the object.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.