List of usage examples for java.lang NullPointerException printStackTrace
public void printStackTrace()
From source file:com.prgpascal.qrdatatransfer.TransferActivity.java
/** Stop the ServerReceiver AsyncTask. */ private void stopServerReceiver() { try {// w ww. j av a 2 s . c o m mServerReceiver.stopSocket(); mServerReceiver.cancel(true); } catch (NullPointerException e) { e.printStackTrace(); } }
From source file:de.tap.easy_xkcd.fragments.comics.FavoritesFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) { View v = inflateLayout(R.layout.pager_layout, inflater, container, savedInstanceState); if (((MainActivity) getActivity()).getProgressDialog() != null) { ((MainActivity) getActivity()).getProgressDialog().dismiss(); }/*from www . ja v a 2 s.c o m*/ pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { favoriteIndex = position; try { //Update the ActionBar Subtitle if (prefHelper.subtitleEnabled() && ((MainActivity) getActivity()).getCurrentFragment() == R.id.nav_favorites) ((MainActivity) getActivity()).getToolbar() .setSubtitle(String.valueOf(favorites[position])); getActivity().invalidateOptionsMenu(); } catch (NullPointerException e) { e.printStackTrace(); } } @Override public void onPageScrollStateChanged(int state) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } }); if (savedInstanceState != null) { favoriteIndex = savedInstanceState.getInt(LAST_FAV); getActivity().invalidateOptionsMenu(); } new updateFavorites().execute(); return v; }
From source file:io.amira.zen.core.ZenFragmentManager.java
public void load(String title, boolean loadView) { //FragmentActivity activity = ZenAppManager.getActivity(); FragmentActivity activity = ZenApplication.getAppActivity(); ZenApplication.log("SETZENFRAGMENT " + title + " - " + activity.getClass().getCanonicalName()); ZenApplication.log("your api version is ok : GRAZIE A STO CAZZO."); /*// ww w .ja v a 2s. c o m * API LEVEL GREATER OR EQUAL TO HONEYCOMB. */ ZenApplication.log("AVAILABLEFRAGMENTS ARE: " + availableFragments); if (availableFragments.containsKey(title)) { /* * IF WE HAVE ALREADY CREATED AN ATLFRAGMENT, * THEN IT'S INSIDE AVAILABLEFRAGMENTS. */ try { long p = System.nanoTime(); ZenApplication.log("Fragment " + title + " instance available, using it."); int content_frame_id = ZenResManager.getResourceId("content_frame"); FragmentManager fragmentManager = activity.getSupportFragmentManager(); //ZenNavigationManager.push(availableFragments.get(title)); ZenApplication.navigation().push(title, availableFragments.get(title).getClass().getSuperclass().getCanonicalName()); lastFragment = title; //TEST FragmentTransaction transaction = fragmentManager.beginTransaction(); //ANIMATIONS if (ZenApplication.navigation().isBack()) { transaction.setCustomAnimations(ZenResManager.getAnimId("back_enter"), ZenResManager.getAnimId("back_exit")); //transaction.setCustomAnimations(ZenResManager.getAnimId("back_enter"), ZenResManager.getAnimId("back_exit"), ZenResManager.getAnimId("back_pop_enter") , ZenResManager.getAnimId("back_pop_exit")); } else { transaction.setCustomAnimations(ZenResManager.getAnimId("enter"), ZenResManager.getAnimId("exit")); //transaction.setCustomAnimations(ZenResManager.getAnimId("enter"), ZenResManager.getAnimId("exit"), ZenResManager.getAnimId("pop_enter") , ZenResManager.getAnimId("pop_exit")); } transaction.replace(content_frame_id, (Fragment) availableFragments.get(title)) .commitAllowingStateLoss(); long d = System.nanoTime(); //ZenAppManager.moveDrawer(true); ZenApplication.log("TIME to recover old " + (d - p)); } catch (NullPointerException e) { e.printStackTrace(); } } else { /* * CREATE A NEW FRAGMENT * * THERE MUST BE A CLASS NAMED: * * titleController.java * * WHICH EXTENDS ATLFragment * if such class is not available, * ClassNotFoundException is launched. * */ try { ZenApplication.log("create new fragment"); long p = System.nanoTime(); String layoutName; String toCallClass; Integer layoutId; ZenApplication.log("TIT: " + title); //layoutName = ZenAppManager.getLayouts().get(title); layoutName = ZenApplication.config().getDrawer_menu_layouts().get(title); // if layoutName is null fall back to title (because is the layout actually) if (layoutName == null) { ZenApplication.log("ZENFRAGMAN: title is null"); layoutName = title; } ZenApplication.log("LAY NAME: " + layoutName); //boolean isDetail = ZenAppManager.getDetailLayouts().containsKey(layoutName); //ZenApplication.log("ISDETAIL: "+isDetail); String[] tlist; tlist = layoutName.split("_"); ZenApplication.log(tlist.length); String cName = layoutName; if (tlist.length > 1) { StringBuilder sBuilder = new StringBuilder(); sBuilder.append(tlist[0]); for (int i = 1; i < tlist.length; i++) { String t = Character.toUpperCase(tlist[i].charAt(0)) + tlist[i].substring(1); //tlist[i] = t; sBuilder.append(t); } cName = sBuilder.toString(); } //else { // cName = layoutName; //} ZenApplication.log("CNAME: " + cName); //if (!isDetail) { //toCallClass = ZenAppManager.getLayouts().get(title); toCallClass = cName; //layoutId = ZenAppManager.getLayouts().get(title); layoutId = ZenResManager.getLayoutId(layoutName); ZenApplication.log("SET NOT DETAIL LAYOUTID " + layoutId); //} /* else { //toCallClass = ZenAppManager.getDetailLayouts().get(title); //toCallClass = title + "Detail"; toCallClass = cName + "Detail"; ZenApplication.log("LAYOUTCLASS " + toCallClass); layoutId = ZenResManager.getLayoutId(ZenAppManager.getDetailLayouts().get(layoutName)); ZenApplication.log("SET DETAIL LAYOUTID " + layoutId); }*/ //ZenApplication.log("LAYOUTID " + layoutId); //TENTATIVO //int pos = ZenAppManager.getLayouts().get(title); //prima non esisteva. //TENTATIVO toCallClass = Character.toUpperCase(toCallClass.charAt(0)) + toCallClass.substring(1); Class toCall = Class.forName("app.Controllers." + toCallClass + "Controller"); ZenApplication.log("app.Controllers." + toCallClass + "Controller"); try { availableFragments.put(title, toCall.newInstance()); lastFragment = title; Object controller = availableFragments.get(title); String superclass = "io.amira.zen.layout.drawer.ZenFragment"; if (ZenFragment.class.isAssignableFrom(controller.getClass())) { //if (controller.getClass().getSuperclass().getCanonicalName().equals(superclass)) { // // QUESTO VUOL DIRE CHE ABBIAMO CARICATO UNA CLASSE CHE HA COME SUPERCLASSE ATLFRAGMENT // Class[] paramTypes = new Class[2]; //prima era new class[2] paramTypes[0] = String.class; paramTypes[1] = Integer.class; //paramTypes[3] = DrawerLayout.class; //paramTypes[4] = ListView.class; //TENTATIVO //Integer layoutId = ZenAppManager.getLayoutIds()[pos]; // prima era position //= ZenAppManager.getLayouts().get(title); //TENTATIVO ZenApplication.log("TRYING LAYOUTID " + layoutId); toCall.getMethod("setVariables", paramTypes).invoke(controller, createParameters(title, layoutId)); int content_frame_id = ZenResManager.getResourceId("content_frame"); FragmentManager fragmentManager = activity.getSupportFragmentManager(); //TEST //ZenNavigationManager.push(controller); ZenApplication.navigation().push(title, controller.getClass().getSuperclass().getCanonicalName()); //TEST if (loadView) { FragmentTransaction transaction = fragmentManager.beginTransaction(); //ANIMATION if (ZenApplication.navigation().isBack()) { transaction.setCustomAnimations(ZenResManager.getAnimId("back_enter"), ZenResManager.getAnimId("back_exit")); //transaction.setCustomAnimations(ZenResManager.getAnimId("back_enter"), ZenResManager.getAnimId("back_exit"), ZenResManager.getAnimId("back_pop_enter") , ZenResManager.getAnimId("back_pop_exit")); } else { transaction.setCustomAnimations(ZenResManager.getAnimId("enter"), ZenResManager.getAnimId("exit")); //transaction.setCustomAnimations(ZenResManager.getAnimId("enter"), ZenResManager.getAnimId("exit"), ZenResManager.getAnimId("pop_enter") , ZenResManager.getAnimId("pop_exit")); } transaction.replace(content_frame_id, (Fragment) controller).commitAllowingStateLoss(); } ZenApplication.log("SAVING " + title + " - " + controller.getClass().getCanonicalName()); long d = System.nanoTime(); ZenApplication.log("TIME to create new fragment " + (d - p)); } } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //ATLFragment atlf = new ATLFragment(); //atlf.setCurrentActivity(activity); //Bundle args = new Bundle(); //args.putString("title", title); //atlf.setArguments(args); //int content_frame_id = getResourceId("content_frame"); //FragmentManager fragmentManager = activity.getFragmentManager(); //fragmentManager.beginTransaction() // .replace(content_frame_id, atlf) // .commit(); /* * PUSHING NEW FRAGMENT INSIDE LIST */ } /* * FINALLY WE CLOSE THE DRAWER. */ //ATLAppManager.closeDrawer(); }
From source file:org.opendatakit.aggregate.odktables.InstanceFileManager.java
/** * Retrieve the BlobEntitySet for a given tableId and rowId. This should be * treated as read-only by the caller. Updates should be done through the * putFile or postFiles APIs. Manipulations of the blob entity set (which is * being updated) needs to be guarded by a task lock. * /*from www . j a va2 s . co m*/ * It is safe to fetch the Blob from this set because the set is write-only. * * @param tableId * @param rowId * @param cb * -- callback to process each file manifest entry * @param userPermissions * @return map of partial path of file to the FileContentInfo for that file. * @throws IOException * @throws ODKTaskLockException * @throws PermissionDeniedException * @throws ODKDatastoreException */ public void getInstanceAttachments(String tableId, String rowId, FileContentHandler cb, TablesUserPermissions userPermissions) throws IOException, ODKTaskLockException, PermissionDeniedException, ODKDatastoreException { try { if (tableId == null) { throw new IllegalArgumentException("tableId cannot be null!"); } if (rowId == null) { throw new IllegalArgumentException("rowId cannot be null!"); } userPermissions.checkPermission(appId, tableId, TablePermission.READ_ROW); OdkTablesLockTemplate propsLock = new OdkTablesLockTemplate(tableId, rowId, ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES, OdkTablesLockTemplate.DelayStrategy.LONG, cc); try { propsLock.acquire(); DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc); final BlobEntitySet instance = blobStore.getBlobEntitySet(rowId, cc); int count = instance.getAttachmentCount(cc); for (int i = 1; i <= count; ++i) { final int iSafe = i; FileContentInfo info = new FileContentInfo(instance.getUnrootedFilename(i, cc), instance.getContentType(i, cc), instance.getContentLength(i, cc), instance.getContentHash(i, cc), null); cb.processFileContent(info, new FetchBlobHandler() { @Override public byte[] getBlob() throws ODKDatastoreException { return instance.getBlob(iSafe, cc); } }); } } finally { propsLock.release(); } } catch (NullPointerException e) { e.printStackTrace(); throw e; } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); throw e; } catch (ODKTaskLockException e) { e.printStackTrace(); throw e; } catch (PermissionDeniedException e) { e.printStackTrace(); throw e; } catch (ODKDatastoreException e) { e.printStackTrace(); throw e; } }
From source file:com.gu.baselibrary.view.dragtoplayout.DragTopLayout.java
@Override public boolean onInterceptTouchEvent(MotionEvent ev) { try {/*from w w w.j a va 2 s . co m*/ boolean intercept = shouldIntercept && dragHelper.shouldInterceptTouchEvent(ev); return intercept; } catch (NullPointerException e) { e.printStackTrace(); } return false; }
From source file:ffdammit.SkyProcMain.java
@Override public void runChangesToPatch() throws Exception { ObjectMapper mapper = new ObjectMapper(); final Map<String, RaceData> raceData = save.getBool(Settings.PROCESS_RACE_HEIGHTS) ? mapper.readValue(new File(racesDataPath), new TypeReference<HashMap<String, RaceData>>() { })// w w w . ja v a 2 s. c o m : null; final List<String> faceModList = save.getBool(Settings.PROCESS_FACE_VISUALS) ? loadTextArray("faces.txt") : null; final List<String> essentialList = save.getInt(Settings.PRESERVE_PROTECTION_OPTIONS) > 0 ? loadTextArray("essential.txt") : null; final List<String> protectedList = save.getInt(Settings.PRESERVE_PROTECTION_OPTIONS) > 0 ? loadTextArray("protected.txt") : null; final List<String> noProtectionList = save.getInt(Settings.PRESERVE_PROTECTION_OPTIONS) > 0 ? loadTextArray("noprotection.txt") : null; Mod patch = SPGlobal.getGlobalPatch(); Mod merger = new Mod(getName() + "Merger", false); merger.addAsOverrides(SPGlobal.getDB()); merger.getNPCs().forEach(n -> { boolean isNPCRecordChanged = false; if (faceModList != null) { ArrayList<MajorRecord> hist = n.getRecordHistory(); if (hist.size() > 1) { // processing face data int idx = 999999; MajorRecord mrr = null; for (MajorRecord mr : hist) { ModListing ml = mr.getModImportedFrom(); Mod mod = SPDatabase.getMod(ml); String modName = mod.getName(); int i = faceModList.indexOf(modName); if (i != -1 && idx > i) { // the mod matching first listed in faces.txt wins mrr = mr; idx = i; } } if (mrr != null && mrr instanceof NPC_) { NPC_ from = (NPC_) mrr; copyFaceData(from, n); isNPCRecordChanged = true; } } } if (save.getInt(Settings.PRESERVE_PROTECTION_OPTIONS) > 0) { boolean isProtected = false; boolean isEssential = false; boolean isProtectionProcessed = false; if (essentialList != null && essentialList.contains(n.getName())) { n.set(NPC_.NPCFlag.Essential, true); n.set(NPC_.NPCFlag.Protected, false); } else if (protectedList != null && protectedList.contains(n.getName())) { n.set(NPC_.NPCFlag.Essential, false); n.set(NPC_.NPCFlag.Protected, true); } else if (noProtectionList != null && noProtectionList.contains(n.getName())) { n.set(NPC_.NPCFlag.Essential, false); n.set(NPC_.NPCFlag.Protected, false); } else if (save.getInt(Settings.PRESERVE_PROTECTION_OPTIONS) > 1) { // don't process if set to 'files only' // try checking record's history ArrayList<MajorRecord> hist = n.getRecordHistory(); for (MajorRecord mr : hist) { if (mr instanceof NPC_) { NPC_ nh = (NPC_) mr; if (nh.get(NPC_.NPCFlag.Essential)) { isEssential = true; isProtectionProcessed = true; } if (nh.get(NPC_.NPCFlag.Protected)) { isProtected = true; isProtectionProcessed = true; } } } if (isProtectionProcessed) { switch (save.getInt(Settings.PRESERVE_PROTECTION_OPTIONS)) { case 2: // Protected/Essential -> Essential isEssential = isEssential | isProtected; if (isEssential) { isNPCRecordChanged = true; n.set(NPC_.NPCFlag.Protected, false); n.set(NPC_.NPCFlag.Essential, true); } break; case 3: // Protected/Essential -> Protected isProtected = isProtected | isEssential; if (isProtected) { isNPCRecordChanged = true; n.set(NPC_.NPCFlag.Protected, true); n.set(NPC_.NPCFlag.Essential, false); } break; case 4: // Essential -> Protected isProtected = isProtected | isEssential | n.get(NPC_.NPCFlag.Essential) | n.get(NPC_.NPCFlag.Protected); if (isProtected) { isNPCRecordChanged = true; n.set(NPC_.NPCFlag.Protected, true); n.set(NPC_.NPCFlag.Essential, false); } break; case 5: // Protected -> Essential isEssential = isProtected | isEssential | n.get(NPC_.NPCFlag.Essential) | n.get(NPC_.NPCFlag.Protected); if (isEssential) { isNPCRecordChanged = true; n.set(NPC_.NPCFlag.Protected, false); n.set(NPC_.NPCFlag.Essential, true); } break; } } } } if (save.getBool(Settings.PROCESS_OPPOSITE_GENDER_ANIMS)) { if (n.get(NPC_.NPCFlag.Female) && n.get(NPC_.NPCFlag.OppositeGenderAnims)) { n.set(NPC_.NPCFlag.OppositeGenderAnims, false); isNPCRecordChanged = true; } } if (isNPCRecordChanged) { patch.addRecord(n); } }); merger.getRaces().forEach(r -> r.getKeywordSet().getKeywordRefs().forEach(kw -> { boolean isRaceRecordChanged = false; String title = kw.getTitle(); if (save.getBool(Settings.COMBAT_IN_WATER) && r.get(RACE.RACEFlags.NoCombatInWater)) { r.set(RACE.RACEFlags.NoCombatInWater, false); isRaceRecordChanged = true; } if (title != null && title.equals("013794Skyrim.esm")) { // NPC race if (save.getBool(Settings.PROCESS_RACE_MODELS)) { try { Model model = r.getPhysicsModel(Gender.FEMALE); // throws NPE sometimes if (model != null && model.getFileName().equals("Actors\\Character\\DefaultMale.hkx")) { model.setFileName("Actors\\Character\\DefaultFemale.hkx"); isRaceRecordChanged = true; } } catch (NullPointerException e) { e.printStackTrace(); } } if (save.getBool(Settings.PROCESS_RACE_HEIGHTS) && !r.get(RACE.RACEFlags.Child)) { String name = r.getName(); if (raceData != null && raceData.containsKey(name)) { RaceData rd = raceData.get(name); r.setHeight(Gender.MALE, rd.heightMale); r.setHeight(Gender.FEMALE, rd.heightFemale); isRaceRecordChanged = true; } } } if (isRaceRecordChanged) { patch.addRecord(r); } })); }
From source file:org.mandar.analysis.recsys2014.recsysMain.java
public void run() { // We first need to configure the data access. LenskitConfiguration dataConfig = this.configureDAO(DBSettings.TRAINING_COLLECTION); // Now we create the LensKit configuration... LenskitConfiguration config = new LenskitConfiguration(); if (algo.equals("svd")) { config = this.configureSVDRecommender(numFeatures, numIterations, regularizationParam, stoppingCondition, threshold); } else if (algo.equals("ii")) { config = this.configureIIRecommender(numNeighbours, similarityModel); } else if (algo.equals("uu")) { config = this.configureUURecommender(numNeighbours); } else if (algo.equals("so")) { config = this.configureSORecommender(damping); } else if (algo.equals("tfidf")) { config = this.configureTFIDFRecommender(); }/*w w w .j a va 2s.com*/ // There are more parameters, roles, and components that can be set. See the // JavaDoc for each recommender algorithm for more information. // Now that we have a factory, build a recommender from the configuration // and data source. This will compute the similarity matrix and return a recommender // that uses it. LenskitRecommender rec = null; try { LenskitRecommenderEngine engine = LenskitRecommenderEngine.newBuilder().addConfiguration(config) .addConfiguration(dataConfig).build(); rec = engine.createRecommender(dataConfig); } catch (RecommenderBuildException e) { e.printStackTrace(); System.exit(1); } // we want to recommend items if ("training".equals(this.goal)) { ItemRecommender irec = rec.getItemRecommender(); assert irec != null; // not null because we configured one // for users try { MongoClient mongoClient = new MongoClient(DBSettings.DBHOST); DB db = mongoClient.getDB(DBSettings.DATABASE); DBCollection collection = db.getCollection(DBSettings.MOVIES_COLLECTION); for (long user : users) { // get 10 recommendation for the user List<ScoredId> recs = irec.recommend(user, 10); System.out.format("Recommendations for %d:\n", user); for (ScoredId item : recs) { DBObject obj = collection.findOne(new BasicDBObject(DBSettings.FIELDS.movie, item.getId())); String recTitle = obj.get("title").toString(); String recDirector = obj.get("director").toString(); String recRel = obj.get("release_date").toString(); String recStars = obj.get("stars").toString(); System.out.format("\tID:%d, %s, %s Directed By: %s Starring: %s\n", item.getId(), recTitle, recRel, recDirector, recStars); } } mongoClient.close(); } catch (UnknownHostException u) { u.printStackTrace(); } } else if ("eval".equals(this.goal)) { //ItemScorer iscorer = rec.getItemScorer(); RatingPredictor rat = rec.getRatingPredictor(); File outFile = new File("data/participant_solution_" + algo + ".dat"); String line = ""; //String cvsSplitBy = ","; long eng = 0; int count = 0; try { long lines = Utils.countLines("data/test_solution.dat"); //outFile.delete(); BufferedWriter brout = new BufferedWriter((new FileWriter(outFile, false))); //BufferedReader br = new BufferedReader(new FileReader(csvData)); long progress = 0; //br.readLine(); System.out.println( "Reading from Test Set and writing result " + "data/participant_solution_" + algo + ".dat"); MongoClient mongoClient = new MongoClient(DBSettings.DBHOST); DB db = mongoClient.getDB(DBSettings.DATABASE); DBCollection collection = db.getCollection(DBSettings.TEST_COLLECTION_EMPTY); DBCursor cur = collection.find(); ArrayList<DBObject> arr = new ArrayList<DBObject>(cur.size()); System.out.println("Making ObjectArrayList out of test collection result"); while (cur.hasNext()) { DBObject buff = cur.next(); eng = (long) Math.abs(rat.predict(Long.parseLong(buff.get("uID").toString()), Long.parseLong(buff.get("movieID").toString()))); buff.put("engagement", eng); arr.add(buff); count++; } cur.close(); //Now sort this by uID (desc), engagement (desc) and tweetID (desc) System.out.println("Sorting ObjectArrayList"); Collections.sort(arr, new MongoComparator()); for (int i = 0; i < arr.size(); i++) { brout.write(arr.get(i).get("uID") + "," + arr.get(i).get("tweetID") + "," + arr.get(i).get("engagement")); brout.newLine(); progress++; if ((progress * 100 / lines) % 10 >= 0 && (progress * 100 / lines) % 10 <= 1) { System.out.println("File write Progress: " + (progress * 100 / lines) + " %"); } } brout.close(); ProcessBuilder pbr = new ProcessBuilder("java", "-jar", "rscevaluator-0.1-jar-with-dependencies.jar", "data/test_solution.dat", "data/participant_solution_" + algo + ".dat"); Process p = pbr.start(); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); double resultbuff = 0.0d; while ((line = is.readLine()) != null) { if (line.contains("nDCG@10:")) { resultbuff = Double.parseDouble(line.substring(9)); } System.out.println(line); } System.out.println("Writing evaluation results to MongoDB"); this.writeAlgoTestResults(resultbuff, db); mongoClient.close(); p.waitFor(); } catch (FileNotFoundException f) { f.printStackTrace(); } catch (IOException f) { f.printStackTrace(); } catch (InterruptedException i) { i.printStackTrace(); } catch (NullPointerException n) { n.printStackTrace(); } } }
From source file:org.opendatakit.aggregate.odktables.InstanceFileManager.java
/** * Retrieve the content info for a given file. Access to the blob entity set * needs to be guarded by a task lock.//w w w . j a va 2 s .co m * * @param tableId * @param rowId * @param partialPath * @param userPermissions * @return the file content if found; otherwise returns null * @throws ODKDatastoreException * @throws ODKTaskLockException * @throws PermissionDeniedException */ public FileContentInfo getFile(String tableId, String rowId, String partialPath, TablesUserPermissions userPermissions) throws ODKDatastoreException, ODKTaskLockException, PermissionDeniedException { try { if (tableId == null) { throw new IllegalArgumentException("tableId cannot be null!"); } if (rowId == null) { throw new IllegalArgumentException("rowId cannot be null!"); } if (partialPath == null) { throw new IllegalArgumentException("partialPath cannot be null!"); } userPermissions.checkPermission(appId, tableId, TablePermission.READ_ROW); OdkTablesLockTemplate propsLock = new OdkTablesLockTemplate(tableId, rowId, ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES, OdkTablesLockTemplate.DelayStrategy.LONG, cc); try { propsLock.acquire(); DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc); BlobEntitySet instance = blobStore.getBlobEntitySet(rowId, cc); int count = instance.getAttachmentCount(cc); for (int i = 1; i <= count; ++i) { String path = instance.getUnrootedFilename(i, cc); if (path != null && path.equals(partialPath)) { byte[] fileBlob = instance.getBlob(i, cc); String contentType = instance.getContentType(i, cc); String contentHash = instance.getContentHash(i, cc); Long contentLength = instance.getContentLength(i, cc); // And now prepare everything to be returned to the caller. if (fileBlob != null && contentType != null && contentLength != null && contentLength != 0L) { FileContentInfo fo = new FileContentInfo(path, contentType, contentLength, contentHash, fileBlob); return fo; } else { return null; } } } return null; } finally { propsLock.release(); } } catch (NullPointerException e) { e.printStackTrace(); throw e; } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); throw e; } catch (ODKTaskLockException e) { e.printStackTrace(); throw e; } catch (PermissionDeniedException e) { e.printStackTrace(); throw e; } catch (ODKDatastoreException e) { e.printStackTrace(); throw e; } }
From source file:org.geefive.salesforce.soqleditor.RESTfulQuery.java
public void executeObjectSearch() throws Exception { HttpClient restClient = new HttpClient(); restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); String restfulURLTarget = serverDomain + REST_LOGIN; System.out.println("RESTful URL Target: " + restfulURLTarget); GetMethod method = null;/*from ww w .j a v a 2 s. co m*/ try { method = new GetMethod(restfulURLTarget); System.out.println("Setting authorization header with SID [" + SID + "]"); method.setRequestHeader("Authorization", "OAuth " + SID); // NameValuePair[] params = new NameValuePair[1]; // params[0] = new NameValuePair("q","SELECT Name, Id, Phone, CreatedById from Account LIMIT 100"); // method.setQueryString(params); int httpResponseCode = restClient.executeMethod(method); System.out.println("HTTP_RESPONSE_CODE [" + httpResponseCode + "]"); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); System.out .println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXECUTING QUERY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); if (httpResponseCode == HttpStatus.SC_OK) { JSONObject response = new JSONObject( new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()))); System.out.println("_____________________________________"); System.out.println("RESPONSE [" + response + "]"); JSONArray resultArray = response.getJSONArray("sobjects"); // StringBuffer soqlQueryResults = new StringBuffer(); // String token = ""; JSONObject inner = null; inner = resultArray.getJSONObject(0); Iterator keys = inner.keys(); HashMap columnNames = new HashMap(); while (keys.hasNext()) { String column = (String) keys.next(); if (!column.equalsIgnoreCase("attributes")) { System.out.println("KEY>> " + column); columnNames.put(column, ""); } } System.out.println("____________________________________________________________________"); JSONArray results = response.getJSONArray("sobjects"); // for (int i = 0; i < results.length(); i++) { for (int i = 0; i < 35; i++) { try { if (results.getJSONObject(i).getString("searchable").equals("true")) { String objectName = results.getJSONObject(i).getString("name"); if (objectName.equals("Asset")) { parseObjectDetails(objectName); } // System.out.println("[" + results.getJSONObject(i).getString("custom") + "] " + results.getJSONObject(i).getString("name")); } } catch (NullPointerException ex) { //just looking for nulls ex.printStackTrace(); } } //end for System.out.println("____________________________________________________________________"); /* Iterator keyset = null; JSONArray results = response.getJSONArray("records"); Vector<String> newRow = null; for (int i = 0; i < results.length(); i++) { keyset = columnNames.keySet().iterator(); newRow = new Vector<String>(); while(keyset.hasNext()){ String columnName = (String)keyset.next(); String columnValue = results.getJSONObject(i).getString(columnName); System.out.println(">> COLUMN_VALUE >> " + columnValue); newRow.addElement(columnValue); } soqlResults.addDataRow(newRow); }//end for */ } } finally { method.releaseConnection(); } }
From source file:io.github.jeremgamer.editor.panels.Others.java
public Others(final JFrame frame, final OtherPanel op, final PanelSave ps) { this.frame = frame; this.setBorder(BorderFactory.createTitledBorder("")); JButton add = null;//www.ja va 2s.com try { add = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("add.png")))); } catch (IOException e) { e.printStackTrace(); } add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { JOptionPane jop = new JOptionPane(); @SuppressWarnings("static-access") String name = jop.showInputDialog((JFrame) SwingUtilities.windowForComponent(otherList), "Nommez le composant :", "Crer un composant", JOptionPane.QUESTION_MESSAGE); if (name != null) { for (int i = 0; i < data.getSize(); i++) { if (data.get(i).equals(name)) { name += "1"; } } data.addElement(name); new OtherSave(name); ActionPanel.updateLists(); PanelsPanel.updateLists(); } } catch (IOException e) { e.printStackTrace(); } } }); JButton remove = null; try { remove = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png")))); } catch (IOException e) { e.printStackTrace(); } remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { if (otherList.getSelectedValue() != null) { File file = new File("projects/" + Editor.getProjectName() + "/others/" + otherList.getSelectedValue() + ".rbd"); JOptionPane jop = new JOptionPane(); @SuppressWarnings("static-access") int option = jop.showConfirmDialog((JFrame) SwingUtilities.windowForComponent(otherList), "tes-vous sr de vouloir supprimer ce composant?", "Avertissement", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (option == JOptionPane.OK_OPTION) { File dir = new File("projects/" + Editor.getProjectName() + "/panels"); for (File f : FileUtils.listFilesAndDirs(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)) { if (!f.isDirectory()) { try { ps.load(f); } catch (IOException e) { e.printStackTrace(); } OtherSave os = new OtherSave(); try { os.load(file); } catch (IOException e1) { e1.printStackTrace(); } String type = null; switch (os.getInt("type")) { case 0: type = "Zone de saisie"; break; case 1: type = "Zone de saisie de mot de passe"; break; case 2: type = "Zone de saisie (Grande)"; break; case 3: type = "Case cocher"; break; case 4: type = "Menu droulant"; break; case 5: type = "Barre de progression"; break; case 6: type = "Slider"; break; case 7: type = "Spinner"; break; } for (String section : ps.getSectionsContaining( otherList.getSelectedValue() + " (" + type + ")")) { ps.removeSection(section); try { ps.save(f); } catch (IOException e) { e.printStackTrace(); } } } } if (otherList.getSelectedValue().equals(op.getFileName())) { op.setFileName(""); } op.hide(); file.delete(); data.remove(otherList.getSelectedIndex()); ActionPanel.updateLists(); OtherPanel.updateLists(); PanelsPanel.updateLists(); } } } catch (NullPointerException npe) { npe.printStackTrace(); } } }); JPanel buttons = new JPanel(); buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS)); buttons.add(add); buttons.add(remove); updateList(); otherList.addMouseListener(new MouseAdapter() { @SuppressWarnings("unchecked") public void mouseClicked(MouseEvent evt) { JList<String> list = (JList<String>) evt.getSource(); if (evt.getClickCount() == 2) { int index = list.locationToIndex(evt.getPoint()); if (isOpen == false) { op.show(); op.load(new File("projects/" + Editor.getProjectName() + "/others/" + list.getModel().getElementAt(index) + ".rbd")); previousSelection = list.getSelectedValue(); isOpen = true; } else { try { if (previousSelection.equals(list.getModel().getElementAt(index))) { op.hide(); previousSelection = list.getSelectedValue(); list.clearSelection(); isOpen = false; } else { op.hideThenShow(); previousSelection = list.getSelectedValue(); op.load(new File("projects/" + Editor.getProjectName() + "/others/" + list.getModel().getElementAt(index) + ".rbd")); } } catch (NullPointerException npe) { op.hide(); list.clearSelection(); } } } else if (evt.getClickCount() == 3) { int index = list.locationToIndex(evt.getPoint()); if (isOpen == false) { op.show(); op.load(new File("projects/" + Editor.getProjectName() + "/others/" + list.getModel().getElementAt(index) + ".rbd")); previousSelection = list.getSelectedValue(); isOpen = true; } else { try { if (previousSelection.equals(list.getModel().getElementAt(index))) { op.hide(); previousSelection = list.getSelectedValue(); list.clearSelection(); isOpen = false; } else { op.hideThenShow(); previousSelection = list.getSelectedValue(); op.load(new File("projects/" + Editor.getProjectName() + "/others/" + list.getModel().getElementAt(index) + ".rbd")); } } catch (NullPointerException npe) { op.hide(); list.clearSelection(); } } } } }); JScrollPane listPane = new JScrollPane(otherList); listPane.getVerticalScrollBar().setUnitIncrement(Editor.SCROLL_SPEED); this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); this.add(buttons); this.add(listPane); OtherPanel.updateLists(); }