public Database.ExecuteSQLResponse executeSQL(String databaseName, String query, ExecuteResultHandler<Database.ExecuteSQLResponse> handler) throws SQLiteException { Util.throwIfNull(query); Util.throwIfNull(handler); SQLiteDatabase database = openDatabase(databaseName); try { String firstWordUpperCase = getFirstWord(query).toUpperCase(); switch (firstWordUpperCase) { case "UPDATE": case "DELETE": return executeUpdateDelete(database, query, handler); case "INSERT": return executeInsert(database, query, handler); case "SELECT": case "PRAGMA": case "EXPLAIN": return executeSelect(database, query, handler); default: return executeRawQuery(database, query, handler); } } finally { database.close(); } }
private void doKill(DumperContext dumpContext, Iterator<String> argsIter) throws DumpException { String signal = ArgsHelper.nextOptionalArg(argsIter, OPTION_KILL_DEFAULT); try { Process kill = new ProcessBuilder() .command("/system/bin/kill", "-" + signal, String.valueOf(android.os.Process.myPid())) .redirectErrorStream(true) .start(); // Handle kill command output gracefully in the event that the signal delivered didn't // actually take out our process... try { InputStream in = kill.getInputStream(); Util.copy(in, dumpContext.getStdout(), new byte[1024]); } finally { kill.destroy(); } } catch (IOException e) { throw new DumpException("Failed to invoke kill: " + e); } }
private void handlePipeOutput(OutputStream output) throws DumpException { File hprofFile = mContext.getFileStreamPath("hprof-dump.hprof"); try { writeHprof(hprofFile); try { InputStream input = new FileInputStream(hprofFile); try { Util.copy(input, output, new byte[2048]); } finally { input.close(); } } catch (IOException e) { throw new DumpException("Failure copying " + hprofFile + " to dumper output"); } } finally { if (hprofFile.exists()) { hprofFile.delete(); } } }
@Nonnull private static LocalServerSocket bindToSocket(String address) throws IOException { int retries = MAX_BIND_RETRIES; IOException firstException = null; do { try { if (LogUtil.isLoggable(Log.DEBUG)) { LogUtil.d("Trying to bind to @" + address); } return new LocalServerSocket(address); } catch (BindException be) { LogUtil.w(be, "Binding error, sleep " + TIME_BETWEEN_BIND_RETRIES_MS + " ms..."); if (firstException == null) { firstException = be; } Util.sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS); } } while (retries-- > 0); throw firstException; }
public ResponseBodyData readFile(String requestId) throws IOException { InputStream in = mContext.openFileInput(getFilename(requestId)); try { int firstByte = in.read(); if (firstByte == -1) { throw new EOFException("Failed to read base64Encode byte"); } ResponseBodyData bodyData = new ResponseBodyData(); bodyData.base64Encoded = firstByte != 0; AsyncPrettyPrinter asyncPrettyPrinter = mRequestIdMap.get(requestId); if (asyncPrettyPrinter != null) { // TODO: this line blocks for up to 10 seconds and create problems as described // in issue #243 allow asynchronous dispatch for MethodDispatcher bodyData.data = prettyPrintContentWithTimeOut(asyncPrettyPrinter, in); } else { bodyData.data = Util.readAsUTF8(in); } return bodyData; } finally { in.close(); } }
@Override public DescriptorMap registerDescriptor(Class<?> elementClass, Descriptor descriptor) { Util.throwIfNull(elementClass); Util.throwIfNull(descriptor); Util.throwIf(descriptor.isInitialized()); Util.throwIfNot(mIsInitializing); // Cannot register two descriptors for one class if (mMap.containsKey(elementClass)) { throw new UnsupportedOperationException(); } // Cannot reuse one descriptor for two classes if (mMap.containsValue(descriptor)) { throw new UnsupportedOperationException(); } mMap.put(elementClass, descriptor); return this; }
public DescriptorMap endInit() { Util.throwIfNot(mIsInitializing); Util.throwIfNull(mHost); mIsInitializing = false; for (final Class<?> elementClass : mMap.keySet()) { final Descriptor descriptor = mMap.get(elementClass); if (descriptor instanceof ChainedDescriptor) { final ChainedDescriptor chainedDescriptor = (ChainedDescriptor) descriptor; Class<?> superClass = elementClass.getSuperclass(); Descriptor superDescriptor = getImpl(superClass); chainedDescriptor.setSuper(superDescriptor); } descriptor.initialize(mHost); } return this; }
public void invokeMethod(String method, Object paramsObject, @Nullable PendingRequestCallback callback) throws NotYetConnectedException { Util.throwIfNull(method); Long requestId = (callback != null) ? preparePendingRequest(callback) : null; // magic, can basically convert anything for some amount of runtime overhead... JSONObject params = mObjectMapper.convertValue(paramsObject, JSONObject.class); JsonRpcRequest message = new JsonRpcRequest(requestId, method, params); String requestString; JSONObject jsonObject = mObjectMapper.convertValue(message, JSONObject.class); requestString = jsonObject.toString(); mPeer.sendText(requestString); }
private static Map<String, MethodDispatchHelper> buildDispatchTable( ObjectMapper objectMapper, Iterable<ChromeDevtoolsDomain> domainHandlers) { Util.throwIfNull(objectMapper); HashMap<String, MethodDispatchHelper> methods = new HashMap<String, MethodDispatchHelper>(); for (ChromeDevtoolsDomain domainHandler : Util.throwIfNull(domainHandlers)) { Class<?> handlerClass = domainHandler.getClass(); String domainName = handlerClass.getSimpleName(); for (Method method : handlerClass.getDeclaredMethods()) { if (isDevtoolsMethod(method)) { MethodDispatchHelper dispatchHelper = new MethodDispatchHelper( objectMapper, domainHandler, method); methods.put(domainName + "." + method.getName(), dispatchHelper); } } } return Collections.unmodifiableMap(methods); }
public List<ApodItem> decorateRssItemsWithLinkImages(List<RssItem> rssItems) { ArrayList<ApodItem> apodItems = new ArrayList<>(rssItems.size()); final CountDownLatch fetchLinkLatch = new CountDownLatch(rssItems.size()); for (RssItem rssItem : rssItems) { final ApodItem apodItem = new ApodItem(); apodItem.rssItem = rssItem; fetchLinkPage(rssItem.link, new PageScrapedCallback() { @Override public void onPageScraped(@Nullable List<String> imageUrls) { apodItem.largeImageUrl = imageUrls != null && !imageUrls.isEmpty() ? imageUrls.get(0) : null; fetchLinkLatch.countDown(); } }); apodItems.add(apodItem); } // Wait for all link fetches to complete, despite running them in parallel... Util.awaitUninterruptibly(fetchLinkLatch); return apodItems; }
public RIAndroidDocumentProviderFactory( Application application, List<DescriptorProvider> descriptorProviders) { mApplication = Util.throwIfNull(application); mDescriptorProviders = Util.throwIfNull(descriptorProviders); mHandler = new Handler(Looper.getMainLooper()); }
public RIAndroidDocumentProvider( Application application, List<DescriptorProvider> descriptorProviders, ThreadBound enforcer) { super(enforcer); mApplication = Util.throwIfNull(application); mDocumentRoot = new RIAndroidDocumentRoot(); mDescriptorMap = new DescriptorMap() .beginInit() .registerDescriptor(RIAndroidDocumentRoot.class, mDocumentRoot) .registerDescriptor(Activity.class, new ActivityDescriptor()) .registerDescriptor(Window.class, new WindowDescriptor()) .registerDescriptor(Dialog.class, new DialogDescriptor()) .registerDescriptor(View.class, new RIViewDescriptor()) .registerDescriptor(ViewGroup.class, new ViewGroupDescriptor()) .registerDescriptor(RINoActivatedActivityDescriptor.class, new RINoActivatedActivityDescriptor()) .registerDescriptor(Object.class, new ObjectDescriptor()); DialogFragmentDescriptor.register(mDescriptorMap); RIFragmentDescriptor.register(mDescriptorMap); for (int i = 0, size = descriptorProviders.size(); i < size; ++i) { final DescriptorProvider descriptorProvider = descriptorProviders.get(i); descriptorProvider.registerDescriptor(mDescriptorMap); } mDescriptorMap.setHost(this).endInit(); mHighlighter = ViewHighlighter.newInstance(); mInspectModeHandler = new InspectModeHandler(); }
public DumperContext( InputStream stdin, PrintStream stdout, PrintStream stderr, CommandLineParser parser, List<String> args) { mStdin = Util.throwIfNull(stdin); mStdout = Util.throwIfNull(stdout); mStderr = Util.throwIfNull(stderr); mParser = Util.throwIfNull(parser); mArgs = Util.throwIfNull(args); }
/** * @param friendlyName identifier to help debug this server, used for naming threads and such. * @param address the local socket address to listen on. * @param socketHandler functional handler once a socket is accepted. */ public LocalSocketServer( String friendlyName, String address, SocketHandler socketHandler) { mFriendlyName = Util.throwIfNull(friendlyName); mAddress = Util.throwIfNull(address); mSocketHandler = socketHandler; }
public DOM(Document document) { mObjectMapper = new ObjectMapper(); mDocument = Util.throwIfNull(document); mSearchResults = Collections.synchronizedMap( new HashMap<String, List<Integer>>()); mResultCounter = new AtomicInteger(0); mPeerManager = new ChromePeerManager(); mPeerManager.setListener(new PeerManagerListener()); mListener = new DocumentUpdateListener(); }
/** * Flatten all columns and all rows of a cursor to a single array. The array cannot be * interpreted meaningfully without the number of columns. * * @param cursor * @param limit Maximum number of rows to process. * @return List of Java primitives matching the value type of each column, converted to * strings. */ private static ArrayList<String> flattenRows(Cursor cursor, int limit) { Util.throwIfNot(limit >= 0); ArrayList<String> flatList = new ArrayList<>(); final int numColumns = cursor.getColumnCount(); for (int row = 0; row < limit && cursor.moveToNext(); row++) { for (int column = 0; column < numColumns; column++) { switch (cursor.getType(column)) { case Cursor.FIELD_TYPE_NULL: flatList.add(null); break; case Cursor.FIELD_TYPE_INTEGER: flatList.add(String.valueOf(cursor.getLong(column))); break; case Cursor.FIELD_TYPE_FLOAT: flatList.add(String.valueOf(cursor.getDouble(column))); break; case Cursor.FIELD_TYPE_BLOB: flatList.add(blobToString(cursor.getBlob(column))); break; case Cursor.FIELD_TYPE_STRING: default: flatList.add(cursor.getString(column)); break; } } } if (!cursor.isAfterLast()) { for (int column = 0; column < numColumns; column++) { flatList.add("{truncated}"); } } return flatList; }
@Override public Void call() throws IOException { GZIPInputStream in = new GZIPInputStream(mIn); try { Util.copy(in, mOut, new byte[1024]); } finally { in.close(); mOut.close(); } return null; }
@Override public String call() throws IOException { HttpURLConnection connection = (HttpURLConnection)url.openConnection(); int statusCode = connection.getResponseCode(); if (statusCode != 200) { throw new IOException("Got status code: " + statusCode + " while downloading " + "schema with url: " + url.toString()); } InputStream urlStream = connection.getInputStream(); try { return Util.readAsUTF8(urlStream); } finally { urlStream.close(); } }
public AndroidDocumentProvider( Application application, List<DescriptorProvider> descriptorProviders, ThreadBound enforcer) { super(enforcer); mApplication = Util.throwIfNull(application); mDocumentRoot = new AndroidDocumentRoot(application); mDescriptorMap = new DescriptorMap() .beginInit() .registerDescriptor(Activity.class, new ActivityDescriptor()) .registerDescriptor(AndroidDocumentRoot.class, mDocumentRoot) .registerDescriptor(Application.class, new ApplicationDescriptor()) .registerDescriptor(Dialog.class, new DialogDescriptor()) .registerDescriptor(Object.class, new ObjectDescriptor()) .registerDescriptor(TextView.class, new TextViewDescriptor()) .registerDescriptor(View.class, new ViewDescriptor()) .registerDescriptor(ViewGroup.class, new ViewGroupDescriptor()) .registerDescriptor(Window.class, new WindowDescriptor()); DialogFragmentDescriptor.register(mDescriptorMap); FragmentDescriptor.register(mDescriptorMap); for (int i = 0, size = descriptorProviders.size(); i < size; ++i) { final DescriptorProvider descriptorProvider = descriptorProviders.get(i); descriptorProvider.registerDescriptor(mDescriptorMap); } mDescriptorMap.setHost(this).endInit(); mHighlighter = ViewHighlighter.newInstance(); mInspectModeHandler = new InspectModeHandler(); }
@Override public void setSuper(Descriptor<? super Object> superDescriptor) { Util.throwIfNull(superDescriptor); if (superDescriptor != mSuper) { if (mSuper != null) { throw new IllegalStateException(); } mSuper = superDescriptor; } }
public AndroidDocumentProviderFactory( Application application, List<DescriptorProvider> descriptorProviders) { mApplication = Util.throwIfNull(application); mDescriptorProviders = Util.throwIfNull(descriptorProviders); mHandler = new Handler(Looper.getMainLooper()); }
/** * Tries to invoke a method on receiver with a single argument by trying out different types * for arg until it finds one that matches (or not). No exceptions are thrown on failure. * * @param methodName The method name to be invoked * @param argument The single argument to be provided to the method */ public void invoke(Object receiver, String methodName, String argument) { Util.throwIfNull(receiver, methodName, argument); int size = invokers.size(); for (int i = 0; i < size; ++i) { final TypedMethodInvoker<?> invoker = invokers.get(i); if (invoker.invoke(receiver, methodName, argument)) { return; } } LogUtil.w("Method with name " + methodName + " not found for any of the MethodInvoker supported argument types."); }
public void add(Activity activity) { Util.throwIfNull(activity); Util.throwIfNot(Looper.myLooper() == Looper.getMainLooper()); mActivities.add(new WeakReference<>(activity)); for (Listener listener : mListeners) { listener.onActivityAdded(activity); } }
public void remove(Activity activity) { Util.throwIfNull(activity); Util.throwIfNot(Looper.myLooper() == Looper.getMainLooper()); if (removeFromWeakList(mActivities, activity)) { for (Listener listener : mListeners) { listener.onActivityRemoved(activity); } } }
@Override public void setSuper(Descriptor<? super E> superDescriptor) { Util.throwIfNull(superDescriptor); if (superDescriptor != mSuper) { if (mSuper != null) { throw new IllegalStateException(); } mSuper = superDescriptor; } }
public DescriptorMap setHost(Descriptor.Host host) { Util.throwIfNull(host); Util.throwIfNot(mIsInitializing); Util.throwIfNotNull(mHost); mHost = host; return this; }
ElementInfo( Object element, @Nullable Object parentElement, List<Object> children) { this.element = Util.throwIfNull(element); this.parentElement = parentElement; this.children = ListUtil.copyToImmutableList(children); }
public Database.ExecuteSQLResponse executeSQL( SqliteDatabaseDescriptor databaseDesc, String query, ExecuteResultHandler<Database.ExecuteSQLResponse> handler) throws SQLiteException { Util.throwIfNull(query); Util.throwIfNull(handler); SQLiteDatabase database = openDatabase(databaseDesc); try { String firstWordUpperCase = getFirstWord(query).toUpperCase(); switch (firstWordUpperCase) { case "UPDATE": case "DELETE": return executeUpdateDelete(database, query, handler); case "INSERT": return executeInsert(database, query, handler); case "SELECT": case "PRAGMA": case "EXPLAIN": return executeSelect(database, query, handler); default: return executeRawQuery(database, query, handler); } } finally { database.close(); } }
/** * Determines if the method is a {@link ChromeDevtoolsMethod}, and validates accordingly * if it is. * * @throws IllegalArgumentException Thrown if it is a {@link ChromeDevtoolsMethod} but * it otherwise fails to satisfy requirements. */ private static boolean isDevtoolsMethod(Method method) throws IllegalArgumentException { if (!method.isAnnotationPresent(ChromeDevtoolsMethod.class)) { return false; } else { Class<?> args[] = method.getParameterTypes(); String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName(); Util.throwIfNot(args.length == 2, "%s: expected 2 args, got %s", methodName, args.length); Util.throwIfNot(args[0].equals(JsonRpcPeer.class), "%s: expected 1st arg of JsonRpcPeer, got %s", methodName, args[0].getName()); Util.throwIfNot(args[1].equals(JSONObject.class), "%s: expected 2nd arg of JSONObject, got %s", methodName, args[1].getName()); Class<?> returnType = method.getReturnType(); if (!returnType.equals(void.class)) { Util.throwIfNot(JsonRpcResult.class.isAssignableFrom(returnType), "%s: expected JsonRpcResult return type, got %s", methodName, returnType.getName()); } return true; } }
@Override protected void doPrint(PrintWriter output, InputStream payload, String schema) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Util.copy(payload, out, new byte[1024]); String prettifiedContent = PRETTY_PRINT_PREFIX + Arrays.toString(out.toByteArray()); output.write(prettifiedContent); output.close(); }
private SQLiteDatabase openDatabase(String databaseName) throws SQLiteException { Util.throwIfNull(databaseName); return mDatabaseConnectionProvider.openDatabase(findDatabaseFile(databaseName)); }
public CSS(Document document) { mDocument = Util.throwIfNull(document); mObjectMapper = new ObjectMapper(); mPeerManager = new ChromePeerManager(); mPeerManager.setListener(new PeerManagerListener()); }
public void setPrettyPrinterInitializer(AsyncPrettyPrinterInitializer initializer) { Util.throwIfNotNull(mPrettyPrinterInitializer); mPrettyPrinterInitializer = Util.throwIfNull(initializer); }
private static void doErrorPrint(PrintWriter output, InputStream payload, String errorMessage) throws IOException { output.print(errorMessage + "\n" + Util.readAsUTF8(payload)); }
public void invokeMethodOnPeers(String method, Object params, PendingRequestCallback callback) { Util.throwIfNull(callback); sendMessageToPeers(method, params, callback); }
public ThreadBoundProxy(ThreadBound enforcer) { mEnforcer = Util.throwIfNull(enforcer); }
public ShadowDocument(Object rootElement) { mRootElement = Util.throwIfNull(rootElement); }