code
stringlengths
73
34.1k
label
stringclasses
1 value
public List<Article> get(String url) { if(url.equals(KEY_FAVORITES)) return getFavorites(); return articleMap.get(url); }
java
public void deleteAllFavorites() { long time = System.currentTimeMillis(); log("Deleting all favorites..."); favoriteDatabase.deleteAll(); log("Deleting all favorites took " + (System.currentTimeMillis() - time) + "ms"); }
java
private void insert(String url, List<Article> newArticles) { if(!articleMap.containsKey(url)) articleMap.put(url, new ArrayList<Article>()); List<Article> articleList = articleMap.get(url); articleList.addAll(newArticles); log("New size for " + url + " is " + articleList.size()); }
java
private void getRead() { // Execute on background thread as we don't know how large this is new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { int size = mPrefs.getInt("READ_ARRAY_SIZE", 0); boolean value; if(size < 1) return null; for(int i = 0...
java
private void writeRead() { // Execute on background thread as we don't know how large this is new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // Get editor & basic variables SharedPreferences.Editor editor = mPrefs.edit(); int size = readList.size(); ...
java
private String pullImageLink(String encoded) { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(new StringReader(encoded)); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (ev...
java
public boolean validate(URL url) throws SAXException { String xmlText = null; try { xmlText = IOUtils.toString(url.openStream()); } catch (IOException e) { throw new RuntimeException(e); } return validate(xmlText); }
java
public boolean validate(String xmlText) throws SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // This section removes the schema hint as we have the schema docs // otherwise exceptions may be thrown try { DocumentBuilder b = factory...
java
public static String getNamespaceURI(Object obj) { Package pkg = obj.getClass().getPackage(); XmlSchema xmlSchemaAnnotation = pkg.getAnnotation(XmlSchema.class); return xmlSchemaAnnotation.namespace(); }
java
public static String getName(Object obj) { try { return obj.getClass().getAnnotation(XmlRootElement.class).name(); } catch (NullPointerException e) { return obj.getClass().getAnnotation(XmlType.class).name(); } }
java
public static QName getQualifiedName(Object obj) { return new QName(STIXSchema.getNamespaceURI(obj), STIXSchema.getName(obj)); }
java
public RequestCreator nextPage() { Request request = data.build(); String url = request.url; int page = request.page; if(request.search != null) url += "?s=" + request.search; Map<String, Integer> pageTracker = singleton.getPageTracker(); if(pageTracker.containsKey(url)) page = pageTracker.get(url);...
java
public static Document toDocument(JAXBElement<?> jaxbElement, boolean prettyPrint) { Document document = null; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setIgnoringElementCont...
java
public static String toXMLString(JAXBElement<?> jaxbElement, boolean prettyPrint) { Document document = toDocument(jaxbElement); return toXMLString(document, prettyPrint); }
java
private final static void traverse(Element element, ElementVisitor visitor) { visitor.visit(element); NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; traverse((Eleme...
java
public static Document toDocument(String xml) { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setIgnoringElementContentWhitespace(true); documentBuilderFactory.isIgnoringComments(); ...
java
public static String stripFormattingfromXMLString(String xml) { try { Document document = DocumentUtilities.toDocument(xml); DOMImplementationRegistry registry = DOMImplementationRegistry .newInstance(); DOMImplementationLS domImplementationLS = (DOMImplementationLS) registry .getDOMImplementation...
java
public static PagerDuty create(String apiKey) { Retrofit retrofit = new Retrofit.Builder() // .baseUrl(HOST) // .addConverterFactory(GsonConverterFactory.create()) .build(); return create(apiKey, retrofit); }
java
public void add(Article article) { // Get Write Access SQLiteDatabase db = this.getWritableDatabase(); // Build Content Values ContentValues values = new ContentValues(); values.put(KEY_TAGS, TextUtils.join("_PCX_", article.getTags())); values.put(KEY_MEDIA_CONTENT, Article.MediaContent.toByteArray(article...
java
public void delete(Article article) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_ARTICLES, KEY_ID + " = ?", new String[] {String.valueOf(article.getId())}); db.close(); }
java
public void deleteAll() { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_ARTICLES, null, null); db.close(); }
java
public Article putExtra(String key, String value) { this.extras.putString(key, value); return this; }
java
public Article addMediaContent(MediaContent mediaContent) { if(mediaContent == null) return this; if(this.mediaContentVec == null) this.mediaContentVec = new Vector<>(); this.mediaContentVec.add(mediaContent); return this; }
java
public Article removeMediaContent(MediaContent mediaContent) { if(mediaContent == null || this.mediaContentVec == null) return this; this.mediaContentVec.remove(mediaContent); return this; }
java
public boolean markRead(boolean read) { if (PkRSS.getInstance() == null) return false; PkRSS.getInstance().markRead(id, read); return true; }
java
public boolean saveFavorite(boolean favorite) { if (PkRSS.getInstance() == null) return false; return PkRSS.getInstance().saveFavorite(this, favorite); }
java
private boolean handleNode(String tag, Article article) { try { if(xmlParser.next() != XmlPullParser.TEXT) return false; if (tag.equalsIgnoreCase("link")) article.setSource(Uri.parse(xmlParser.getText())); else if (tag.equalsIgnoreCase("title")) article.setTitle(xmlParser.getText()); else if ...
java
private void handleMediaContent(String tag, Article article) { String url = xmlParser.getAttributeValue(null, "url"); if(url == null) { throw new IllegalArgumentException("Url argument must not be null"); } Article.MediaContent mc = new Article.MediaContent(); article.addMediaContent(mc); mc.setUrl(url)...
java
public static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { if (!deleteDir(new File(dir, children[i]))) return false; } } return dir.delete(); }
java
public static Downloader createDefaultDownloader(Context context) { Downloader downloaderInstance = null; try { Class.forName("com.squareup.okhttp.OkHttpClient"); downloaderInstance = new OkHttpDownloader(context); } catch (ClassNotFoundException ignored) {} try { Class.forName("okhttp3.OkHttpClient...
java
public void start( Class<? extends Easing> clazz, EaseType type, double fromValue, double endValue, int durationMillis, long delayMillis ) { if ( !mRunning ) { mEasing = createInstance( clazz ); if( null == mEasing ){ return; } mMethod = getEasingMethod( mEasing, type ); if( mMethod == null...
java
public static List<Map<String, Object>> mergeLists(String[] names, List<Object>... lists) { List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>(); if (lists.length != 0) { // first check if all looks good int expectedSize = lists[0].size(); for (int i = 1; i < lists.length;...
java
private void append(StringBuilder buffer, char c) { // version manually simplified // final boolean shouldAppend = rawOutput || escaped // || (c != quoteChar && c != escapeChar); // final boolean newEscaped = c == escapeChar && !escaped; // final boolean newQuoted = (c == quoteChar && !escaped) ? !quot...
java
public boolean variablesAvailable(Map<String, Object> model, String... vars) { final TemplateContext context = new TemplateContext(null, null, null, new ScopedMap(model), modelAdaptor, this, new SilentErrorHandler(), null); for (String var : vars) { final IfToken token = new IfToken(var, false); if (...
java
@Deprecated() public synchronized Set<String> getUsedVariables(String template) { Template templateImpl = getTemplate(template, null); return templateImpl.getUsedVariables(); }
java
public synchronized List<VariableDescription> getUsedVariableDescriptions(String template) { Template templateImpl = getTemplate(template, null); return templateImpl.getUsedVariableDescriptions(); }
java
public Token pop() { if (scopes.isEmpty()) { return null; } else { Token token = scopes.remove(scopes.size() - 1); return token; } }
java
public Token peek() { if (scopes.isEmpty()) { return null; } else { Token token = scopes.get(scopes.size() - 1); return token; } }
java
public void notifyProcessListener(Token token, Action action) { if (processListener != null) { processListener.log(this, token, action); } }
java
public static String streamToString(InputStream is, String charsetName) { try { Reader r = null; try { r = new BufferedReader(new InputStreamReader(is, charsetName)); return readerToString(r); } finally { if (r != null) { try { r.close(); } catch (IOException e) { ...
java
public static String resourceToString(String resourceName, String charsetName) { InputStream templateStream = Thread.currentThread() .getContextClassLoader().getResourceAsStream(resourceName); String template = Util.streamToString(templateStream, "UTF-8"); return template; }
java
public static String readerToString(Reader reader) { try { StringBuilder sb = new StringBuilder(); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { sb.append(buf, 0, numRead); } return sb.toString(); } catch (Exception e) { throw new Runti...
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static List<Object> arrayAsList(Object value) { if (value instanceof List) { return (List<Object>) value; } List list = null; if (value instanceof int[]) { list = new ArrayList(); int[] array = (int[]) value; for (int i : array) { ...
java
public static String trimFront(String input) { int i = 0; while (i < input.length() && Character.isWhitespace(input.charAt(i))) i++; return input.substring(i); }
java
public MisplacedClassProcessor getProcessorForName(String name) { if (name == null) { return getDefaultProcessor(); } switch (Strategy.valueOf(name.toUpperCase())) { case FATAL: return new FatalMisplacedClassProcessor(); case MOVE: return new MoveMisplacedClassProcessor(); case OMIT...
java
public static int safeRead(final InputStream inputStream, final byte[] buffer) throws IOException { int readBytes = inputStream.read(buffer); if(readBytes == -1) { return -1; } if(readBytes < buffer.length) { int offset = readBytes; int left = buffer.l...
java
public static boolean eofIsNext(final RawPacket rawPacket) { final ByteBuffer buf = rawPacket.getByteBuffer(); return (buf.get(0) == (byte)0xfe && buf.capacity() < 9); }
java
static RawPacket nextPacket(final InputStream is) throws IOException { byte[] lengthBuffer = readLengthSeq(is); int length = (lengthBuffer[0] & 0xff) + ((lengthBuffer[1] & 0xff) << 8) + ((lengthBuffer[2] & 0xff) << 16); if (length == -1) { return null; } if (length <...
java
public boolean execute(final String query) throws SQLException { startTimer(); try { if (queryResult != null) { queryResult.close(); } queryResult = protocol.executeQuery(queryFactory.createQuery(query)); if (queryResult.getResultSetType() ...
java
public final int writeTo(final OutputStream os,int offset, int maxWriteSize) throws IOException { int bytesToWrite = Math.min(blobReference.getBytes().length - offset, maxWriteSize); os.write(blobReference.getBytes(), offset, blobReference.getBytes().length); return bytesToWrite; }
java
public String readString(final String charset) throws IOException { byte ch; int cnt = 0; final byte [] byteArrBuff = new byte[byteBuffer.remaining()]; while (byteBuffer.remaining() > 0 && ((ch = byteBuffer.get()) != 0)) { byteArrBuff[cnt++] = ch; } return new...
java
public ValueObject getValueObject(final int i) throws NoSuchColumnException { if (i < 0 || i > resultSet.get(rowPointer).size()) { throw new NoSuchColumnException("No such column: " + i); } return resultSet.get(rowPointer).get(i); }
java
public static String sqlEscapeString(final String str) { StringBuilder buffer = new StringBuilder(str.length() * 2); boolean neededEscaping = false; for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (needsEscaping((byte) c)) { neede...
java
public static long unpackTime(final int packedTime) { final int hours = (packedTime & MASK_HOURS); final int minutes = (packedTime & MASK_MINUTES) >> (START_BIT_MINUTES); final int seconds = (packedTime & MASK_SECONDS) >> (START_BIT_SECONDS); final int millis = (packedTime & MASK_MILLISE...
java
public static boolean isJava5() { if (!java5Determined) { try { java.util.Arrays.copyOf(new byte[0], 0); isJava5 = false; } catch (java.lang.NoSuchMethodError e) { isJava5 = true; } java5Determined = true; }...
java
public void setTime(final int parameterIndex, final Time x) throws SQLException { if(x == null) { setNull(parameterIndex, Types.TIME); return; } setParameter(parameterIndex, new TimeParameter(x.getTime())); }
java
private QueryResult createDrizzleQueryResult(final ResultSetPacket packet) throws IOException, QueryException { final List<ColumnInformation> columnInformation = new ArrayList<ColumnInformation>(); for (int i = 0; i < packet.getFieldCount(); i++) { final RawPacket rawPacket = packetFetcher.g...
java
public Time getTime() throws ParseException { if (rawBytes == null) { return null; } String rawValue = getString(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setLenient(false); final java.util.Date utilTime = sdf.parse(rawValue); re...
java
public PreparedStatement prepareStatement(final String sql) throws SQLException { if (parameterizedBatchHandlerFactory == null) { this.parameterizedBatchHandlerFactory = new DefaultParameterizedBatchHandlerFactory(); } final String strippedQuery = Utils.stripQuery(sql); retur...
java
public boolean getAutoCommit() throws SQLException { Statement stmt = createStatement(); ResultSet rs = stmt.executeQuery("select @@autocommit"); rs.next(); boolean autocommit = rs.getBoolean(1); rs.close(); stmt.close(); return autocommit; }
java
public void close() throws SQLException { if (isClosed()) return; try { this.timeoutExecutor.shutdown(); protocol.close(); } catch (QueryException e) { throw SQLExceptionMapper.get(e); } }
java
public DatabaseMetaData getMetaData() throws SQLException { return new CommonDatabaseMetaData.Builder(protocol.getDatabaseType(), this). url("jdbc:drizzle://" + protocol.getHost() + ":" + protocol.getPort() + "/" + protocol.getDatabase()). ...
java
public List<RawPacket> startBinlogDump(final int position, final String logfile) throws SQLException { try { return this.protocol.startBinlogDump(position, logfile); } catch (BinlogDumpException e) { throw SQLExceptionMapper.getSQLException("Could not dump binlog", e); } ...
java
protected void addCommandLineArgument(StringBuilder buffer,String argument,String value) { if((value!=null)&&(value.length()>0)) { buffer.append(argument); buffer.append(Fax4jExeConstants.SPACE_STR); buffer.append(Fax4jExeConstants.VALUE_WRAPPER); buff...
java
protected String createProcessCommand(String commandArguments) { //create command StringBuilder buffer=new StringBuilder(500); buffer.append("\""); buffer.append(this.fax4jExecutableFileLocation); buffer.append("\""); buffer.append(Fax4jExeConstants.SPACE_STR); ...
java
protected String createProcessCommandArgumentsForSubmitFaxJob(FaxJob faxJob) { //get values from fax job String targetAddress=faxJob.getTargetAddress(); String targetName=faxJob.getTargetName(); String senderName=faxJob.getSenderName(); File file=faxJob.getFile(); Str...
java
protected String createProcessCommandArgumentsForExistingFaxJob(String faxActionTypeArgument,FaxJob faxJob) { //get values from fax job String faxJobID=faxJob.getID(); //init buffer StringBuilder buffer=new StringBuilder(); //create command line arguments ...
java
public final synchronized void initialize(Object flowOwner) { if(this.initialized) { throw new FaxException("Vendor policy already initialized."); } if(flowOwner==null) { throw new FaxException("Flow owner not provided."); } /...
java
@Override protected HTTPClientConfiguration createHTTPClientConfiguration() { CommonHTTPClientConfiguration configuration=new CommonHTTPClientConfiguration(); configuration.setHostName("api.phaxio.com"); configuration.setSSL(true); configuration.setMethod(FaxActionType.SUBMIT_FAX...
java
public void updateFaxJob(FaxJob faxJob,HTTPResponse httpResponse,FaxActionType faxActionType) { //get path String path=this.getPathToResponseData(faxActionType); //get fax job ID String id=this.findValue(httpResponse,path); if(id!=null) { faxJob....
java
public FaxJobStatus getFaxJobStatus(HTTPResponse httpResponse) { //get path String path=this.getPathToResponseData(FaxActionType.GET_FAX_JOB_STATUS); //get fax job status string String faxJobStatusStr=this.findValue(httpResponse,path); FaxJobStatus faxJobStatus=FaxJ...
java
protected String getVBSFailedLineErrorMessage(String errorPut) { String message=""; if(errorPut!=null) { String prefix=".vbs("; int start=errorPut.indexOf(prefix); if(start!=-1) { start=start+prefix.length(); int...
java
protected void logEvent(FaxClientSpiProxyEventType eventType,Method method,Object[] arguments,Object output,Throwable throwable) { //init log data int amount=3; int argumentsAmount=0; if(arguments!=null) { argumentsAmount=arguments.length; } if(eve...
java
public final void preMethodInvocation(Method method,Object[] arguments) { this.logEvent(FaxClientSpiProxyEventType.PRE_EVENT_TYPE,method,arguments,null,null); }
java
public final void postMethodInvocation(Method method,Object[] arguments,Object output) { this.logEvent(FaxClientSpiProxyEventType.POST_EVENT_TYPE,method,arguments,output,null); }
java
public final void onMethodInvocationError(Method method,Object[] arguments,Throwable throwable) { this.logEvent(FaxClientSpiProxyEventType.ERROR_EVENT_TYPE,method,arguments,null,throwable); }
java
public FaxJobPriority getPriority() { int priority=Job.PRIORITY_NORMAL; try { priority=this.JOB.getPriority(); } catch(Exception exception) { throw new FaxException("Error while extracting job priority.",exception); } FaxJobPri...
java
public void setPriority(FaxJobPriority priority) { try { if(priority==FaxJobPriority.HIGH_PRIORITY) { this.JOB.setPriority(Job.PRIORITY_HIGH); } else { this.JOB.setPriority(Job.PRIORITY_NORMAL); }...
java
public String getTargetAddress() { String value=null; try { value=this.JOB.getDialstring(); } catch(Exception exception) { throw new FaxException("Error while extracting job target address.",exception); } return value; }
java
public void setTargetAddress(String targetAddress) { try { this.JOB.setDialstring(targetAddress); } catch(Exception exception) { throw new FaxException("Error while setting job target address.",exception); } }
java
public String getSenderName() { String value=null; try { value=this.JOB.getFromUser(); } catch(Exception exception) { throw new FaxException("Error while extracting job sender name.",exception); } return value; }
java
public void setSenderName(String senderName) { try { this.JOB.setFromUser(senderName); } catch(Exception exception) { throw new FaxException("Error while setting job sender name.",exception); } }
java
public void setProperty(String key,String value) { try { this.JOB.setProperty(key,value); } catch(Exception exception) { throw new FaxException("Error while setting job property.",exception); } }
java
protected String formatHTTPResource(HTTPFaxClientSpi faxClientSpi,FaxActionType faxActionType,FaxJob faxJob) { //get resource String resourceTemplate=faxClientSpi.getHTTPResource(faxActionType); //format resource String resource=SpiUtil.formatTemplate(resourceTemplate,faxJob...
java
protected String formatHTTPURLParameters(HTTPFaxClientSpi faxClientSpi,FaxJob faxJob) { //get URL parameters String urlParametersTemplate=faxClientSpi.getHTTPURLParameters(); //format URL parameters String urlParameters=SpiUtil.formatTemplate(urlParametersTemplate,faxJob,Spi...
java
private static void loadProperties(Properties properties,InputStream inputStream,boolean internal) { try { properties.load(inputStream); LibraryConfigurationLoader.closeResource(inputStream); } catch(Exception exception) { LibraryConfigurat...
java
public static Properties readInternalConfiguration() { //init properties Properties properties=new Properties(); //get class loader ClassLoader classLoader=ReflectionHelper.getThreadContextClassLoader(); //load internal properties InputStream inputStream=cla...
java
public static Properties readInternalAndExternalConfiguration() { //read properties Properties properties=LibraryConfigurationLoader.readInternalConfiguration(); ClassLoader classLoader=ReflectionHelper.getThreadContextClassLoader(); InputStream inputStream=classLoader.getResourceAs...
java
public boolean implies(final MqttTopicPermission other) { if (other == null) { return false; } return implies(other.getTopic(), other.splitTopic, other.getQos(), other.getActivity()); }
java
private boolean topicImplicity(final String topic, final String[] splitTopic) { try { return topicMatcher.matches(stripedTopic, this.splitTopic, nonWildCard, endsWithWildCard, rootWildCard, topic, splitTopic); } catch (InvalidTopicException e) { return false; } }
java
private boolean getQosImplicity(final QOS qos) { if (this.getQos() == QOS.ALL) { return true; } if (qos == QOS.ALL) { return false; } else if (this.getQos() == QOS.ZERO_ONE) { return (qos == QOS.ZERO) || (qos == QOS.ONE) || (qos == QOS.ZERO_ONE); ...
java
private boolean getActivityImplicity(final ACTIVITY activity) { if (this.activity == ACTIVITY.ALL) { return true; } if ((activity == ACTIVITY.SUBSCRIBE) && (this.activity == ACTIVITY.PUBLISH)) { return false; } else if ((activity == ACTIVITY.PUBLISH) && (this.act...
java
@Override protected void initializeMailTemplates() { //mail address template this.mailAddressTemplate=FaxClientSpiConfigurationConstants.MAIL_ADDRESS_TEMPLATE_VALUE.toString(); //mail subject template this.mailSubjectTemplate=FaxClientSpiConfigurationConstants.MAIL_SUBJECT_TEMPL...
java
protected Object[] setupSubmitFaxJobInput(FaxJob faxJob) { //init list List<Object> inputList=new LinkedList<Object>(); //set fax server information inputList.add(this.faxServerName); //set fax values File file=faxJob.getFile(); inputList.add(file); ...
java
protected Object formatObject(Object object) { Object formattedObject=object; if(object==null) { formattedObject=""; } else if(object instanceof String) { //get string String string=(String)object; //remove ...
java
protected FaxJobStatus invokeExistingFaxJobAction(String scriptName,FaxJob faxJob,FaxActionType faxActionType) { //initialize array Object[] input=new String[2]; //set fax server information input[0]=this.faxServerName; //set fax job ID input[1]=faxJob.getID...
java
protected FaxJobStatus invokeScript(FaxJob faxJob,String name,Object[] input,FaxActionType faxActionType) { //generate script String script=this.generateScript(name,input); //invoke script ProcessOutput processOutput=this.invokeScript(script); //validate out...
java
protected ProcessOutput invokeScript(String script) { File file=null; try { //create temporary file file=File.createTempFile("fax4j_",".vbs"); } catch(IOException exception) { throw new FaxException("Unable to create temporary vbscr...
java
protected String generateScript(String name,Object[] input) { //get template String template=VBSFaxClientSpi.VBS_SCRIPTS.get(name); if((template==null)||(template.length()==0)) { this.throwUnsupportedException(); } //get common script Stri...
java
protected static final Logger initializeLogger() { //get logger Logger logger=Logger.getLogger(FaxClient.class.getName()); //enable all log events (fax4j logger filters out uneeded log events) logger.setLevel(Level.ALL); logger.setFilter(null); //ena...
java