public ExecResult executeCommand(Session session, String command, String workingDir) throws PortalServiceException { ChannelExec channel = null; if (workingDir != null) { command = "cd " + workingDir + "; " + command; } try { channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(null); channel.connect(); try (InputStream out = channel.getInputStream(); InputStream err = channel.getErrStream()) { String outStr = readStream(out, channel); String errStr = readStream(err, channel); return new ExecResult(outStr, errStr, channel.getExitStatus()); } catch (IOException | InterruptedException e) { throw new PortalServiceException(e.getMessage(), e); } } catch (JSchException e) { throw new PortalServiceException(e.getMessage(), e); } finally { if (channel != null) { channel.disconnect(); } } }
@Override public void run() { try { oftp = OftpAutomaton.build(false, CapabilityInit.BOTH, CapabilityMode.BOTH, 999999, 999); this.subscribe(MonitorEvent.class, oftp); oftp.subscribe(MonitorEvent.class, this); Thread oftpThread = new Thread(oftp); oftpThread.start(); System.out.println("Wait for connection"); ServerSocket server = new ServerSocket(LISTEN_PORT); Socket socket = server.accept(); server.close(); MonitorEvent nConInd = new MonitorEvent(new NetworkConnectionIndicationArchetype()); nConInd.putAttribute(AbstractSocketInitialisationArchetype.SOCKET, socket); publish(nConInd); oftpThread.join(); } catch (IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public WorkspaceFactoryHelper(boolean allowOverride, String... args) { Path root = null; Path workspaceFilePath = null; try { Scratch scratch = new Scratch("/"); root = scratch.dir("/workspace"); workspaceFilePath = scratch.file("/workspace/WORKSPACE", args); } catch (IOException e) { fail("Shouldn't happen: " + e.getMessage()); } StoredEventHandler eventHandler = new StoredEventHandler(); builder = Package.newExternalPackageBuilder( Package.Builder.DefaultHelper.INSTANCE, workspaceFilePath, ""); this.factory = new WorkspaceFactory( builder, TestRuleClassProvider.getRuleClassProvider(), ImmutableList.<PackageFactory.EnvironmentExtension>of(), Mutability.create("test"), allowOverride, root, root); Exception exception = null; try { factory.parse(ParserInputSource.create(workspaceFilePath), eventHandler); } catch (BuildFileContainsErrorsException e) { exception = e; } catch (IOException | InterruptedException e) { fail("Shouldn't happen: " + e.getMessage()); } this.events = eventHandler.getEvents(); this.exception = exception; }
private static int executeCmd(String command) throws IOException, InterruptedException { try { // Execute the call log.debug("executing: " + command); Process process = Runtime.getRuntime().exec(command); // TODO Switch to using CommandLineUtils class to execute calls and use the provided exit // codes // on windows don't read result, as nothing returns (blocking process) if (SystemUtils.IS_OS_LINUX) { log.debug("checking Output of command"); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String result = ""; String line; while ((line = in.readLine()) != null) { result += line; } log.debug(result); } } log.debug("waiting for command to finish"); process.waitFor(); return CommandLineUtils.getExecPID(process); } catch (IOException | InterruptedException e) { log.error("Error executing: " + command + " " + e.toString()); throw e; } }
@Override public boolean perform() { Properties config = new Properties(); try (FileInputStream configIS = new FileInputStream("fileserver.properties")) { config.load(configIS); } catch (IOException e) { LOG.severe("Cannot read configuration file, msg =" + e); } String cmd = config.getProperty("stopMule", ""); if (!cmd.isEmpty()) { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); try { ProcessBuilder pb = new ProcessBuilder(); pb.command(cmd); Process proc = pb.start(); proc.waitFor(); writer.append("HTTP/1.0 200 OK\r\n"); writer.append("Content-Type: text/plain\r\n"); writer.append("Date: " + new Date() + "\r\n" + "Server: DgbSoft File server 1.0\r\n\r\n"); writer.append("OK\r\n"); writer.flush(); } catch (IOException | InterruptedException e) { LOG.severe("Cannot start amule, msg = " + e.getMessage()); } } else { LOG.warning("No stop mule command"); } return true; }
/** @param args Arguments from console */ public static void main(String[] args) { Othello othello = new Othello(); try { othello.startOthello(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
@Override public void run() { try { startTimer(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
@Override public void close() { try { stop(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } updater.cancel(); }
protected static void cleanOutputs() { try { String cleanerScript = BASE_TESTING_DIR + "\\0000_clean_outputs.bat"; Process process = Runtime.getRuntime().exec(cleanerScript); process.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
public void importArchive(int day) { try { Calendar processStartedAt = Calendar.getInstance(); Calendar startDate = Calendar.getInstance(); startDate.add(Calendar.DAY_OF_YEAR, -day); Calendar endDate = Calendar.getInstance(); // List<Crawler> crawlers = new ArrayList<>(); ScraperConfiguration config = Crawler.getScraperConfig(context, null, Crawler.CrawlType.DATA_ARCHIVE); Map params = new HashMap(); dateFormat = new SimpleDateFormat(DSE_DATA_ARCHIVE_DATE_FORMAT); params.put("startDate", dateFormat.format(startDate.getTime())); params.put("endDate", dateFormat.format(endDate.getTime())); Item item = new Item(ALL_INSTRUMENT); Crawler crawler = new Crawler(config, item, Crawler.CrawlType.DATA_ARCHIVE, params); crawler.start(); // crawlers.add(crawler); int counter = 0; crawler.join(); List<Item> items = (List<Item>) crawler.getParams().get("items"); List<Item> dsexItems = importDSEXArchive(day); System.out.println("dsex items: " + dsexItems.size()); items.addAll(dsexItems); // filterOutUnneccessaryCodes(items, watchMatrix); if (items.size() > 0) { dao.open(); dao.importItems(items); dao.close(); // System.out.println("[" + (++counter) + "]Import data archive finished for " + // items.get(0).getCode()); } Calendar processEndedAt = Calendar.getInstance(); long elapsedTime = (processEndedAt.getTimeInMillis() - processStartedAt.getTimeInMillis()) / 1000; System.out.println( "Time elapsed to sync " + day + " day archive for " + items.size() + " item: " + (elapsedTime / 60) + " minutes " + (elapsedTime % 60) + " seconds"); } catch (IOException | InterruptedException | SQLException | ClassNotFoundException ex) { Logger.getLogger(ImportService.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { String key = null; if (requestCode == 1) { File f = new File(Environment.getExternalStorageDirectory().toString()); for (File temp : f.listFiles()) { if (temp.getName().equals("temp.jpg")) { f = temp; break; } } try { Bitmap bitmap; BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions); viewImage.setImageBitmap(bitmap); key = ClientHelpers.recognizeLandscape(f.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } } else if (requestCode == 2) { Uri selectedImage = data.getData(); String[] filePath = {MediaStore.Images.Media.DATA}; Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null); c.moveToFirst(); int columnIndex = c.getColumnIndex(filePath[0]); String picturePath = c.getString(columnIndex); c.close(); Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath)); viewImage.setImageBitmap(thumbnail); try { key = ClientHelpers.recognizeLandscape(picturePath); } catch (IOException | InterruptedException | JSONException e) { e.printStackTrace(); } } if (key != null) { int landscapeID = Integer.parseInt(key); Intent intent = new Intent(this, LandscapeDetailActivity.class); intent.putExtra("landscapeID", landscapeID); startActivity(intent); } } }
@Override public int run(String[] args) { // set up basic job information Configuration conf = getConf(); try { runJob(conf); } catch (IOException | InterruptedException | ClassNotFoundException ex) { throw new RuntimeException(ex.getMessage()); } return 0; }
@Override public void process( final OperationList ops, final ImageInfo imageInfo, final OutputStream outputStream) throws ProcessorException { if (!getAvailableOutputFormats().contains(ops.getOutputFormat())) { throw new UnsupportedOutputFormatException(); } // will receive stderr output from kdu_expand final ByteArrayOutputStream errorBucket = new ByteArrayOutputStream(); try { final ReductionFactor reductionFactor = new ReductionFactor(); final ProcessBuilder pb = getProcessBuilder(ops, imageInfo.getSize(), reductionFactor); logger.info("Invoking {}", StringUtils.join(pb.command(), " ")); final Process process = pb.start(); try (final InputStream processInputStream = process.getInputStream(); final InputStream processErrorStream = process.getErrorStream()) { executorService.submit(new StreamCopier(processErrorStream, errorBucket)); final ImageReader reader = new ImageReader(new InputStreamStreamSource(processInputStream), Format.TIF); try { postProcessUsingJava2d(reader, ops, imageInfo, reductionFactor, outputStream); final int code = process.waitFor(); if (code != 0) { logger.warn("kdu_expand returned with code {}", code); final String errorStr = errorBucket.toString(); if (errorStr != null && errorStr.length() > 0) { throw new ProcessorException(errorStr); } } } finally { reader.dispose(); } } finally { process.destroy(); } } catch (EOFException e) { // This will generally not have a message. logger.error("process(): EOFException ({})", e.getMessage(), ops); } catch (IOException | InterruptedException e) { String msg = e.getMessage(); final String errorStr = errorBucket.toString(); if (errorStr != null && errorStr.length() > 0) { msg += " (command output: " + errorStr + ")"; } throw new ProcessorException(msg, e); } }
@Override public boolean dispatchKeyEvent(KeyEvent e) { int keyCode = e.getKeyCode(); if (e.getID() == KEY_PRESSED) { try { handleKeyPressed(keyCode); } catch (IOException | InterruptedException e1) { e1.printStackTrace(); } } else if (e.getID() == KEY_RELEASED) { handleKeyReleased(keyCode); } return true; }
@Override public boolean push(AbstractBuild<?, ?> build, BuildListener listener, String branchName) { try { listener.getLogger().println(EvoSuiteRecorder.LOG_PREFIX + "Pushing new test cases"); if (this.hgClient.run("push").pwd(build.getWorkspace()).join() != 0) { return false; } } catch (IOException | InterruptedException e) { e.printStackTrace(); return false; } return true; }
public void runMetis() throws IOException { String[] args = this.arg_list.toArray(new String[this.arg_list.size()]); ProcessBuilder pb = new ProcessBuilder(args); pb.directory(exec_dir); // Process p = pb.start(); // // // Any error? Or, Any output? // StreamCollector errorStreams = new StreamCollector(p.getErrorStream(), "ERROR"); // StreamCollector outputStreams = new StreamCollector(p.getInputStream(), "OUTPUT"); // // Start stream collectors // outputStreams.start(); // errorStreams.start(); try { final Process p = pb.start(); new Thread( new Runnable() { public void run() { Scanner stdin = new Scanner(p.getInputStream()); while (stdin.hasNextLine()) { System.out.println(stdin.nextLine()); } stdin.close(); } }) .start(); // Any error? Or, Any output? // StreamCollector errorStreams = new StreamCollector(p.getErrorStream(), "ERROR"); // StreamCollector outputStreams = new StreamCollector(p.getInputStream(), "OUTPUT"); // Start stream collectors // outputStreams.start(); // errorStreams.start(); p.waitFor(); // PrintWriter printer = new PrintWriter(outputStreams); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
/** Sends the command TrueCrypt.exe /q background /d to unmount all TrueCrypt volumes */ public static void unmountAll() throws IOException, InterruptedException { String command = createUnmountAllCommand(); log.debug("unmounting: " + command); Process p; try { p = Runtime.getRuntime().exec(command); p.waitFor(); } catch (IOException | InterruptedException e) { log.error("Error executing: " + command + " " + e.toString()); throw e; } for (String drive : getSupportedDriveLetters()) { cleanUpMountingPoint(drive); } }
public void runFNSemanticParsing() { try { Process proc = Runtime.getRuntime() .exec( FrameNetOptions.ABS_PATH_DRIVER_SCRIPT + " " + FrameNetOptions.ABS_PATH_FNDATA + FrameNetOptions.FN_FILE_NAME); BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } proc.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
@Override public void executeSynchronously( RemoteWorkRequest request, StreamObserver<RemoteWorkResponse> responseObserver) { Path tempRoot = workPath.getRelative("build-" + UUID.randomUUID().toString()); try { FileSystemUtils.createDirectoryAndParents(tempRoot); final ConcurrentMapActionCache actionCache = new ConcurrentMapActionCache(tempRoot, cache); final MemcacheWorkExecutor workExecutor = MemcacheWorkExecutor.createLocalWorkExecutor(actionCache, tempRoot); if (LOG_FINER) { LOG.fine( "Work received has " + request.getInputFilesCount() + " input files and " + request.getOutputFilesCount() + " output files."); } RemoteWorkResponse response = workExecutor.executeLocally(request); responseObserver.onNext(response); if (options.debug) { if (!response.getSuccess()) { LOG.warning("Work failed. Request: " + request.toString() + "."); } else if (LOG_FINER) { LOG.fine("Work completed."); } } if (!options.debug || response.getSuccess()) { FileSystemUtils.deleteTree(tempRoot); } else { LOG.warning("Preserving work directory " + tempRoot.toString() + "."); } } catch (IOException | InterruptedException e) { RemoteWorkResponse.Builder response = RemoteWorkResponse.newBuilder(); response.setSuccess(false).setOut("").setErr("").setException(e.toString()); responseObserver.onNext(response.build()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } finally { responseObserver.onCompleted(); } }
@Override public void run() { getAndSendInitialInfo(); System.out.println("CLIENT " + userid + ": registered on team " + team); while (true) { int plen = ClientState.getMaxSize(); byte[] buf = cs.toBytes(); DatagramPacket cp = new DatagramPacket(buf, plen); try { ds.send(cp); Thread.sleep(50); } catch (IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // send client state // receive client data }
public List<Item> importDSEXArchive(int day) { List<Item> items = new ArrayList<>(); try { Calendar processStartedAt = Calendar.getInstance(); Calendar startDate = Calendar.getInstance(); startDate.add(Calendar.DAY_OF_YEAR, -day); Calendar endDate = Calendar.getInstance(); String path = Utils.getConfigFilesPath(); ScraperConfiguration config = Crawler.getScraperConfig(null, path, Crawler.CrawlType.DSEX_DATA_ARCHIVE); Map params = new HashMap(); dateFormat = new SimpleDateFormat(DSE_DATA_ARCHIVE_DATE_FORMAT); params.put("startDate", dateFormat.format(startDate.getTime())); params.put("endDate", dateFormat.format(endDate.getTime())); Item item = new Item(); Crawler crawler = new Crawler(config, item, Crawler.CrawlType.DSEX_DATA_ARCHIVE, params); crawler.start(); crawler.join(); items = (List<Item>) crawler.getParams().get("items"); Calendar processEndedAt = Calendar.getInstance(); long elapsedTime = (processEndedAt.getTimeInMillis() - processStartedAt.getTimeInMillis()) / 1000; System.out.println( "Time elapsed to sync " + day + " day archive for " + items.size() + " item: " + (elapsedTime / 60) + " minutes " + (elapsedTime % 60) + " seconds"); } catch (IOException | InterruptedException ex) { Logger.getLogger(ImportService.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } return items; }
public static void watchService() { try { WatchService watcher = FileSystems.getDefault().newWatchService(); WatchKey watchKey = Paths.get("/Users/caocao024/Desktop") .register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); while (true) { // watchKey = watcher.take(); for (WatchEvent<?> event : watcher.poll(10, TimeUnit.MILLISECONDS).pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { System.out.println("====" + event.context() + " | " + event.count()); } } watchKey.reset(); } } catch (IOException | InterruptedException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
/** start daemon */ private static void start(Context context, Class<?> daemonClazzName, int interval) { String cmd = context.getDir(BIN_DIR_NAME, Context.MODE_PRIVATE).getAbsolutePath() + File.separator + DAEMON_BIN_NAME; /* create the command string */ StringBuilder cmdBuilder = new StringBuilder(); cmdBuilder.append(cmd); cmdBuilder.append(" -p "); cmdBuilder.append(context.getPackageName()); cmdBuilder.append(" -s "); cmdBuilder.append(daemonClazzName.getName()); cmdBuilder.append(" -t "); cmdBuilder.append(interval); try { Runtime.getRuntime().exec(cmdBuilder.toString()).waitFor(); } catch (IOException | InterruptedException e) { Log.e(TAG, "start daemon error: " + e.getMessage()); } }
public static void main(String[] args) { try (ServerSocket server = new ServerSocket(1234)) { // wait 15 seconds for a connection server.setSoTimeout(15000); System.out.println("Listening..."); try (Socket client = server.accept()) { // listen for messages from client Thread listen = new Thread(new SocketListener(client, true)); listen.start(); System.out.println("Client connected from: " + client.getInetAddress()); // wait for listener to terminate listen.join(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } }
/** 监听目录 */ @Test public void testWatchFile() { // 监听目录变化 try { WatchService watcher = FileSystems.getDefault().newWatchService(); Path dir = FileSystems.getDefault().getPath(ParentPath); WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); boolean shutdown = false; while (!shutdown) { System.out.println(1); key = watcher.take(); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { System.out.println("Home dir changed!"); } } key.reset(); } } catch (IOException | InterruptedException e) { System.out.println(e.getMessage()); } }
@Override public void run() { while (!SH.get(tcn).isInterrupted()) { try { String rtn = Tclient(tcn); if (rtn.equals("reload")) { TNH.get(tcn).loggedin = 0; SH.get(tcn).interrupt(); TNH.get(tcn).killme(); } } catch (SocketException e) { dw.append("Server " + tcn + " offline."); TNH.get(tcn).loggedin = 0; SH.get(tcn).interrupt(); } catch (IOException | InterruptedException e) { e.printStackTrace(); dw.append("Server" + tcn + ": Bad Server Address"); SH.get(tcn).interrupt(); } } SH.remove(tcn); }
@Override public Boolean call() { Log.i(TAG, "Trying to extract logcat for minidump"); try { // Step 1: Extract a single logcat file. File logcatFile = getElidedLogcat(); // Step 2: Make copies of logcat file for each minidump then invoke // MinidumpPreparationService on each file pair. int len = mMinidumpFilenames.length; CrashFileManager fileManager = new CrashFileManager(mContext.getCacheDir()); for (int i = 0; i < len; i++) { // Output crash dump file path to logcat so non-browser crashes appear too. Log.i(TAG, "Output crash dump:"); Log.i(TAG, fileManager.getCrashFile(mMinidumpFilenames[i]).getAbsolutePath()); processMinidump(logcatFile, mMinidumpFilenames[i], fileManager, i == len - 1); } return true; } catch (IOException | InterruptedException e) { Log.w(TAG, e.toString()); return false; } }
/** @return */ public boolean sendPing() { ip = conteudo.getServerIp(); port = conteudo.getServerPort(); boolean retv = false; try { System.out.println("Sending a Ping."); InputStream ins = Runtime.getRuntime().exec("ping -n 1 -w 2000 " + ip).getInputStream(); Thread.sleep(3000); byte[] prsbuf = new byte[ins.available()]; ins.read(prsbuf); String parsstr = new StringTokenizer(new String(prsbuf), "%").nextToken().trim(); if (!parsstr.endsWith("100")) { retv = true; } // System.out.println(parsstr); this.changeInfo(parsstr); } catch (IOException | InterruptedException e) { System.out.println("IOException" + e.getMessage()); retv = false; } return retv; }
public void openUrlInNewTab(URL url) { String urlstr = url.toExternalForm(); if (webTabs.get(urlstr) != null) { setSelectedTab(webTabs.get(urlstr)); } else Platform.runLater( () -> { try { if (ScriptingEngine.getLoginID() != null) { ScriptingGistTab newTab = new ScriptingGistTab("Web", url.toExternalForm(), false); newTab.setOnCloseRequest( event -> { webTabs.remove(urlstr); }); webTabs.put(urlstr, newTab); addTab(newTab, true); } } catch (IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); }
@Override public MaterialDialog onCreateDialog(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mType = getArguments().getInt("dialogType"); Resources res = getResources(); MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity()); builder.cancelable(true).title(getTitle()); boolean sqliteInstalled = false; try { sqliteInstalled = Runtime.getRuntime().exec("sqlite3 --version").waitFor() == 0; } catch (IOException | InterruptedException e) { e.printStackTrace(); } switch (mType) { case DIALOG_CURSOR_SIZE_LIMIT_EXCEEDED: case DIALOG_LOAD_FAILED: // Collection failed to load; give user the option of either choosing from repair options, // or closing // the activity return builder .cancelable(false) .content(getMessage()) .iconAttr(R.attr.dialogErrorIcon) .positiveText(res.getString(R.string.error_handling_options)) .negativeText(res.getString(R.string.close)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_ERROR_HANDLING); } @Override public void onNegative(MaterialDialog dialog) { ((DeckPicker) getActivity()).exit(); } }) .show(); case DIALOG_DB_ERROR: // Database Check failed to execute successfully; give user the option of either choosing // from repair // options, submitting an error report, or closing the activity MaterialDialog dialog = builder .cancelable(false) .content(getMessage()) .iconAttr(R.attr.dialogErrorIcon) .positiveText(res.getString(R.string.error_handling_options)) .negativeText(res.getString(R.string.answering_error_report)) .neutralText(res.getString(R.string.close)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_ERROR_HANDLING); } @Override public void onNegative(MaterialDialog dialog) { ((DeckPicker) getActivity()).sendErrorReport(); dismissAllDialogFragments(); } @Override public void onNeutral(MaterialDialog dialog) { ((DeckPicker) getActivity()).exit(); } }) .show(); dialog .getCustomView() .findViewById(R.id.buttonDefaultNegative) .setEnabled(((DeckPicker) getActivity()).hasErrorFiles()); return dialog; case DIALOG_ERROR_HANDLING: // The user has asked to see repair options; allow them to choose one of the repair options // or go back // to the previous dialog ArrayList<String> options = new ArrayList<>(); ArrayList<Integer> values = new ArrayList<>(); if (!((AnkiActivity) getActivity()).colIsOpen()) { // retry options.add(res.getString(R.string.backup_retry_opening)); values.add(0); } else { // fix integrity options.add(res.getString(R.string.check_db)); values.add(1); } // repair db with sqlite if (sqliteInstalled) { options.add(res.getString(R.string.backup_error_menu_repair)); values.add(2); } // // restore from backup options.add(res.getString(R.string.backup_restore)); values.add(3); // delete old collection and build new one options.add(res.getString(R.string.backup_full_sync_from_server)); values.add(4); // delete old collection and build new one options.add(res.getString(R.string.backup_del_collection)); values.add(5); String[] titles = new String[options.size()]; mRepairValues = new int[options.size()]; for (int i = 0; i < options.size(); i++) { titles[i] = options.get(i); mRepairValues[i] = values.get(i); } dialog = builder .iconAttr(R.attr.dialogErrorIcon) .negativeText(res.getString(R.string.dialog_cancel)) .items(titles) .itemsCallback( new MaterialDialog.ListCallback() { @Override public void onSelection( MaterialDialog materialDialog, View view, int which, CharSequence charSequence) { switch (mRepairValues[which]) { case 0: ((DeckPicker) getActivity()).restartActivity(); return; case 1: ((DeckPicker) getActivity()) .showDatabaseErrorDialog(DIALOG_CONFIRM_DATABASE_CHECK); return; case 2: ((DeckPicker) getActivity()) .showDatabaseErrorDialog(DIALOG_REPAIR_COLLECTION); return; case 3: ((DeckPicker) getActivity()) .showDatabaseErrorDialog(DIALOG_RESTORE_BACKUP); return; case 4: ((DeckPicker) getActivity()) .showDatabaseErrorDialog(DIALOG_FULL_SYNC_FROM_SERVER); return; case 5: ((DeckPicker) getActivity()) .showDatabaseErrorDialog(DIALOG_NEW_COLLECTION); } } }) .show(); return dialog; case DIALOG_REPAIR_COLLECTION: // Allow user to run BackupManager.repairCollection() return builder .content(getMessage()) .iconAttr(R.attr.dialogErrorIcon) .positiveText(res.getString(R.string.dialog_positive_repair)) .negativeText(res.getString(R.string.dialog_cancel)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { ((DeckPicker) getActivity()).repairDeck(); dismissAllDialogFragments(); } }) .show(); case DIALOG_RESTORE_BACKUP: // Allow user to restore one of the backups String path = CollectionHelper.getInstance().getCollectionPath(getActivity()); File[] files = BackupManager.getBackups(new File(path)); mBackups = new File[files.length]; for (int i = 0; i < files.length; i++) { mBackups[i] = files[files.length - 1 - i]; } if (mBackups.length == 0) { builder .title(res.getString(R.string.backup_restore)) .content(getMessage()) .positiveText(res.getString(R.string.dialog_ok)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_ERROR_HANDLING); } }); } else { String[] dates = new String[mBackups.length]; for (int i = 0; i < mBackups.length; i++) { dates[i] = mBackups[i] .getName() .replaceAll(".*-(\\d{4}-\\d{2}-\\d{2})-(\\d{2})-(\\d{2}).apkg", "$1 ($2:$3 h)"); } builder .title(res.getString(R.string.backup_restore_select_title)) .negativeText(res.getString(R.string.dialog_cancel)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onNegative(MaterialDialog dialog) { dismissAllDialogFragments(); } }) .items(dates) .itemsCallbackSingleChoice( dates.length, new MaterialDialog.ListCallbackSingleChoice() { @Override public boolean onSelection( MaterialDialog materialDialog, View view, int which, CharSequence charSequence) { if (mBackups[which].length() > 0) { // restore the backup if it's valid ((DeckPicker) getActivity()).restoreFromBackup(mBackups[which].getPath()); dismissAllDialogFragments(); } else { // otherwise show an error dialog new MaterialDialog.Builder(getActivity()) .title(R.string.backup_error) .content(R.string.backup_invalid_file_error) .positiveText(R.string.dialog_ok) .build() .show(); } return true; } }); } return builder.show(); case DIALOG_NEW_COLLECTION: // Allow user to create a new empty collection return builder .content(getMessage()) .positiveText(res.getString(R.string.dialog_positive_create)) .negativeText(res.getString(R.string.dialog_cancel)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { CollectionHelper.getInstance().closeCollection(false); String path = CollectionHelper.getCollectionPath(getActivity()); if (BackupManager.moveDatabaseToBrokenFolder(path, false)) { ((DeckPicker) getActivity()).restartActivity(); } else { ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_LOAD_FAILED); } } }) .show(); case DIALOG_CONFIRM_DATABASE_CHECK: // Confirmation dialog for database check return builder .content(getMessage()) .positiveText(res.getString(R.string.dialog_ok)) .negativeText(res.getString(R.string.dialog_cancel)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { ((DeckPicker) getActivity()).integrityCheck(); dismissAllDialogFragments(); } }) .show(); case DIALOG_CONFIRM_RESTORE_BACKUP: // Confirmation dialog for backup restore return builder .content(getMessage()) .positiveText(res.getString(R.string.dialog_continue)) .negativeText(res.getString(R.string.dialog_cancel)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_RESTORE_BACKUP); } }) .show(); case DIALOG_FULL_SYNC_FROM_SERVER: // Allow user to do a full-sync from the server return builder .content(getMessage()) .positiveText(res.getString(R.string.dialog_positive_overwrite)) .negativeText(res.getString(R.string.dialog_cancel)) .callback( new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { ((DeckPicker) getActivity()).sync("download"); dismissAllDialogFragments(); } }) .show(); default: return null; } }