code
stringlengths
73
34.1k
label
stringclasses
1 value
private ReferenceFactory<?> createFactory(final Constructor<?> constructor) { return manager -> { try { return (ReferenceCounted<?>) constructor.newInstance(manager); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new SerializationExceptio...
java
@SuppressWarnings("unchecked") private T readObject(Class<T> type, BufferInput<?> buffer, Serializer serializer) { try { Constructor<?> constructor = constructorMap.get(type); if (constructor == null) { try { constructor = type.getDeclaredConstructor(); constructor.setAcces...
java
private static File[] loadXmlFiles(final File directory) { return directory.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.getName().endsWith(".xml"); } }); }
java
private static void generateJavaFiles(final StatusUpdateTemplate template, final String workingPath) throws FileNotFoundException { final String javaPath = WORKING_DIR + template.getName() + ".java"; final File javaFile = new File(javaPath); final String[] optionsAndSources = { "-classpath", workingPath, "...
java
private static void storeStatusUpdateTemplate( final AbstractGraphDatabase graphDatabase, final StatusUpdateTemplate template, final Node previousTemplateNode) { final Transaction transaction = graphDatabase.beginTx(); try { // create template node final Node templateNode = StatusUpdateTemplate.createTe...
java
public static void loadStatusUpdateTemplates(final String rootDir, final Configuration config, final AbstractGraphDatabase graphDatabase) throws ParserConfigurationException, SAXException, IOException { // set working directory final String workingPath = rootDir + "classes/"; final String targetPackage =...
java
public static StatusUpdate instantiateStatusUpdate( final String typeIdentifier, final FormItemList values) throws StatusUpdateInstantiationFailedException { final StatusUpdateTemplate template = getStatusUpdateTemplate(typeIdentifier); final Class<?> templateInstantiationClass = template .getInstantiatio...
java
public static DeleteUserRequest checkRequest( final HttpServletRequest request, final DeleteRequest deleteRequest, final DeleteUserResponse deleteUserResponse) { final Node user = checkUserIdentifier(request, deleteUserResponse); if (user != null) { return new DeleteUserRequest(deleteRequest.getType(), ...
java
public void addFriendById(String userId, String name, FriendGroup friendGroup) { if (name == null && getRiotApi() != null) { try { name = getRiotApi().getName(userId); } catch (final IOException e) { e.printStackTrace(); } } try { connection .getRoster() .createEntry( Strin...
java
public boolean addFriendByName(String name, FriendGroup friendGroup) { if (getRiotApi() != null) { try { final StringBuilder buf = new StringBuilder(); buf.append("sum"); buf.append(getRiotApi().getSummonerId(name)); buf.append("@pvp.net"); addFriendById(buf.toString(), name, friendGroup); ...
java
public FriendGroup addFriendGroup(String name) { final RosterGroup g = connection.getRoster().createGroup(name); if (g != null) { return new FriendGroup(this, connection, g); } return null; }
java
public void disconnect() { connection.getRoster().removeRosterListener(leagueRosterListener); try { connection.disconnect(); } catch (final NotConnectedException e) { e.printStackTrace(); } stop = true; }
java
public Friend getFriend(Filter<Friend> filter) { for (final RosterEntry e : connection.getRoster().getEntries()) { final Friend f = new Friend(this, connection, e); if (filter.accept(f)) { return f; } } return null; }
java
public Friend getFriendById(String xmppAddress) { final RosterEntry entry = connection.getRoster().getEntry( StringUtils.parseBareAddress(xmppAddress)); if (entry != null) { return new Friend(this, connection, entry); } return null; }
java
public FriendGroup getFriendGroupByName(String name) { final RosterGroup g = connection.getRoster().getGroup(name); if (g != null) { return new FriendGroup(this, connection, g); } return addFriendGroup(name); }
java
public List<FriendGroup> getFriendGroups() { final ArrayList<FriendGroup> groups = new ArrayList<>(); for (final RosterGroup g : connection.getRoster().getGroups()) { groups.add(new FriendGroup(this, connection, g)); } return groups; }
java
public List<Friend> getFriends() { return getFriends(new Filter<Friend>() { public boolean accept(Friend e) { return true; } }); }
java
public List<Friend> getFriends(Filter<Friend> filter) { final ArrayList<Friend> friends = new ArrayList<>(); for (final RosterEntry e : connection.getRoster().getEntries()) { final Friend f = new Friend(this, connection, e); if (filter.accept(f)) { friends.add(f); } } return friends; }
java
public String getName(boolean forcedUpdate) { if ((name == null || forcedUpdate) && getRiotApi() != null) { try { name = getRiotApi().getName(connection.getUser()); } catch (final IOException e) { e.printStackTrace(); } } return name; }
java
public List<Friend> getOfflineFriends() { return getFriends(new Filter<Friend>() { public boolean accept(Friend friend) { return !friend.isOnline(); } }); }
java
public List<Friend> getOnlineFriends() { return getFriends(new Filter<Friend>() { public boolean accept(Friend friend) { return friend.isOnline(); } }); }
java
public List<Friend> getPendingFriendRequests() { return getFriends(new Filter<Friend>() { public boolean accept(Friend friend) { return friend.getFriendStatus() == FriendStatus.ADD_REQUEST_PENDING; } }); }
java
public int threads() { int threads = reader.getInteger(THREADS, DEFAULT_THREADS); if (threads == -1) { return Runtime.getRuntime().availableProcessors(); } return threads; }
java
public SslProtocol sslProtocol() { String protocol = reader.getString(SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL).replace(".", "_"); try { return SslProtocol.valueOf(protocol); } catch (IllegalArgumentException e) { throw new ConfigurationException("unknown SSL protocol: " + protocol, e); } }
java
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) { channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE); handler = new ServerHandler(connections, listener, context, transport.properties()); final ServerBootstrap bootst...
java
static Runnable logFailure(final Runnable runnable, Logger logger) { return () -> { try { runnable.run(); } catch (Throwable t) { if (!(t instanceof RejectedExecutionException)) { logger.error("An uncaught exception occurred", t); } throw t; } }; }
java
public boolean delete() { try { con.getRoster().removeEntry(get()); return true; } catch (XMPPException | NotLoggedInException | NoResponseException | NotConnectedException e) { e.printStackTrace(); } return false; }
java
public FriendStatus getFriendStatus() { for (final FriendStatus status : FriendStatus.values()) { if (status.status == get().getStatus()) { return status; } } return null; }
java
public FriendGroup getGroup() { final Collection<RosterGroup> groups = get().getGroups(); if (groups.size() > 0) { return new FriendGroup(api, con, get().getGroups().iterator() .next()); } return null; }
java
public String getName(boolean forcedUpdate) { String name = get().getName(); if ((name == null || forcedUpdate) && api.getRiotApi() != null) { try { name = api.getRiotApi().getName(getUserId()); setName(name); } catch (final IOException e) { e.printStackTrace(); } } return name; ...
java
public void sendMessage(String message) { try { getChat().sendMessage(message); } catch (XMPPException | NotConnectedException e) { e.printStackTrace(); } }
java
@SuppressWarnings("unchecked") protected void addStatusMessage(final String statusMessage, final String solution) { this.json.put(ProtocolConstants.SOLUTION, solution); this.json.put(ProtocolConstants.STATUS_MESSAGE, statusMessage); }
java
public void error(final int errorCode, final String message) { try { this.response.sendError(errorCode, message); } catch (final IOException e) { e.printStackTrace(); } }
java
protected AbstractBuffer reset(long offset, long capacity, long maxCapacity) { this.offset = offset; this.capacity = 0; this.initialCapacity = capacity; this.maxCapacity = maxCapacity; capacity(initialCapacity); references.set(0); rewind(); return this; }
java
protected void checkOffset(long offset) { if (offset(offset) < this.offset) { throw new IndexOutOfBoundsException(); } else if (limit == -1) { if (offset > maxCapacity) throw new IndexOutOfBoundsException(); } else { if (offset > limit) throw new IndexOutOfBoundsException()...
java
protected long checkSlice(long offset, long length) { checkOffset(offset); if (limit == -1) { if (offset + length > capacity) { if (capacity < maxCapacity) { capacity(calculateCapacity(offset + length)); } else { throw new BufferUnderflowException(); } } ...
java
public static ReadRequest checkRequest(final HttpServletRequest request, final ReadResponse readResponse) { final Node user = checkUserIdentifier(request, readResponse); if (user != null) { final Node poster = checkPosterIdentifier(request, readResponse); if (poster != null) { final int numItems = chec...
java
private static Node checkPosterIdentifier(final HttpServletRequest request, final ReadResponse response) { final String posterId = request .getParameter(ProtocolConstants.Parameters.Read.POSTER_IDENTIFIER); if (posterId != null) { final Node user = NeoUtils.getUserByIdentifier(posterId); if (user != nu...
java
private static int checkNumItems(final HttpServletRequest request, final ReadResponse response) { final String sNumItems = request .getParameter(ProtocolConstants.Parameters.Read.NUM_ITEMS); if (sNumItems != null) { int numItems; try { numItems = Integer.valueOf(sNumItems); if (numItems > 0) { ...
java
private static Boolean checkOwnUpdates(final HttpServletRequest request, final ReadResponse response) { final String sOwnUpdates = request .getParameter(ProtocolConstants.Parameters.Read.OWN_UPDATES); if (sOwnUpdates != null) { try { final int iOwnUpdates = Integer.valueOf(sOwnUpdates); return (iO...
java
public SSLEngine initSslEngine(boolean client) throws Exception { // Load the keystore KeyStore keyStore = loadKeystore(properties.sslKeyStorePath(), properties.sslKeyStorePassword()); // Setup the keyManager to use our keystore KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyMan...
java
private void initialize() throws IllegalArgumentException, IllegalAccessException { Field[] fields = this.getClass().getFields(); for (Field f : fields) { if (this.getProperty(f.getName()) == null) { System.err.print("Property '" + f.getName() + "' not defined in config file"); } if (f.getType...
java
public int weightOf(String suggestion) { Node n = getNode(suggestion); return (n != null) ? n.weight : -1; }
java
public void put(String suggestion, int weight, String key) { if(suggestion.isEmpty() || weight < 0) throw new IllegalArgumentException(); if(root == null) { root = new Node(suggestion, weight, key, 0, null); size++; return; } int i = 0; ...
java
public void remove(String suggestion) { Node n = getNode(suggestion); if(n == null) return; n.weight = -1; size--; Node m = n; if(n.mid == null) { Node replacement = removeNode(n); if(replacement != null) replacement.par...
java
private void updateEgoNetwork(final Node user) { Node followedReplica, followingUser, lastPosterReplica; Node prevReplica, nextReplica; // loop through users following for (Relationship relationship : user.getRelationships( SocialGraphRelationshipType.REPLICA, Direction.INCOMING)) { // load each replica...
java
private void removeFromReplicaLayer(final Node followedReplica) { final Node prev = NeoUtils.getPrevSingleNode(followedReplica, SocialGraphRelationshipType.GRAPHITY); final Node next = NeoUtils.getNextSingleNode(followedReplica, SocialGraphRelationshipType.GRAPHITY); // bridge the user replica in the rep...
java
private void updateReplicaLayerStatusUpdateDeletion(final Node user, final Node statusUpdate) { final Node lastUpdate = NeoUtils.getNextSingleNode(user, SocialGraphRelationshipType.UPDATE); // update the ego network if the removal targets the last recent status // update if (statusUpdate.equals(lastUpda...
java
private static long getLastUpdateByReplica(final Node userReplica) { final Node user = NeoUtils.getNextSingleNode(userReplica, SocialGraphRelationshipType.REPLICA); if (user.hasProperty(Properties.User.LAST_UPDATE)) { return (long) user.getProperty(Properties.User.LAST_UPDATE); } return 0; }
java
public static CreateFollowRequest checkRequest( final FormItemList formItemList, final CreateRequest createRequest, final CreateFollowResponse createFollowResponse) { final Node user = checkUserIdentifier(formItemList, createFollowResponse); if (user != null) { final Node followed = checkFollowedIdenti...
java
public boolean removeFooterView(View v) { if (mFooterViewInfos.size() > 0) { boolean result = false; ListAdapter adapter = getAdapter(); if (adapter != null && ((HeaderFooterViewGridAdapter) adapter).removeFooter(v)) { result = true; } ...
java
public Messages reserve(int numberOfMessages, int timeout, int wait) throws IOException { if (numberOfMessages < 1 || numberOfMessages > 100) { throw new IllegalArgumentException("numberOfMessages has to be within 1..100"); } MessagesReservationModel payload = new MessagesReservatio...
java
public Message peek() throws IOException { Messages msgs = peek(1); Message msg; try { msg = msgs.getMessage(0); } catch (IndexOutOfBoundsException e) { throw new EmptyQueueException(); } return msg; }
java
public Messages peek(int numberOfMessages) throws IOException { if (numberOfMessages < 1 || numberOfMessages > 100) { throw new IllegalArgumentException("numberOfMessages has to be within 1..100"); } IronReader reader = client.get("queues/" + name + "/messages?n=" + numberOfMessages)...
java
public MessageOptions touchMessage(String id, String reservationId, int timeout) throws IOException { return touchMessage(id, reservationId, (long) timeout); }
java
public String push(String msg, long delay) throws IOException { Message message = new Message(); message.setBody(msg); message.setDelay(delay); Messages msgs = new Messages(message); IronReader reader = client.post("queues/" + name + "/messages", msgs); Ids ids = gson.f...
java
public Ids pushMessages(String[] msg, long delay) throws IOException { ArrayList<Message> messages = new ArrayList<Message>(); for (String messageName: msg){ Message message = new Message(); message.setBody(messageName); message.setDelay(delay); messages.a...
java
public QueueModel getInfoAboutQueue() throws IOException { IronReader reader = client.get("queues/" + name); QueueContainer queueContainer = gson.fromJson(reader.reader, QueueContainer.class); reader.close(); return queueContainer.getQueue(); }
java
public Message getMessageById(String id) throws IOException { String url = "queues/" + name + "/messages/" + id; IronReader reader = client.get(url); MessageContainer container = gson.fromJson(reader.reader, MessageContainer.class); reader.close(); return container.getMessage(); ...
java
public void addSubscribers(Subscribers subscribers) throws IOException { String payload = gson.toJson(subscribers); IronReader reader = client.post("queues/" + name + "/subscribers", payload); reader.close(); }
java
public void replaceSubscribers(Subscribers subscribers) throws IOException { String payload = gson.toJson(subscribers); IronReader reader = client.put("queues/" + name + "/subscribers", payload); reader.close(); }
java
public void removeSubscribers(Subscribers subscribers) throws IOException { String url = "queues/" + name + "/subscribers"; String jsonMessages = gson.toJson(subscribers); IronReader reader = client.delete(url, jsonMessages); reader.close(); }
java
public SubscribersInfo getPushStatusForMessage(String messageId) throws IOException { String url = "queues/" + name + "/messages/" + messageId + "/subscribers"; IronReader reader = client.get(url); SubscribersInfo subscribersInfo = gson.fromJson(reader.reader, SubscribersInfo.class); rea...
java
public void deletePushMessageForSubscriber(String messageId, String reservationId, String subscriberName) throws IOException { deleteMessage(messageId, reservationId, subscriberName); }
java
public QueueModel updateAlerts(ArrayList<Alert> alerts) throws IOException { QueueModel payload = new QueueModel(alerts); return this.update(payload); }
java
public void deleteAlertsFromQueue(ArrayList<Alert> alert_ids) throws IOException { String url = "queues/" + name + "/alerts"; Alerts alert = new Alerts(alert_ids); String jsonMessages = gson.toJson(alert); IronReader reader = client.delete(url, jsonMessages); reader.close(); ...
java
public void deleteAlertFromQueueById(String alert_id) throws IOException { String url = "queues/" + name + "/alerts/" + alert_id; IronReader reader = client.delete(url); reader.close(); }
java
public boolean isExpired(int seconds) { long diff = localIssuedAt.getTime() - issuedAt.getTime(); long localExpiresAtTime = expiresAt.getTime() + diff; return (new Date().getTime() - seconds * 1000) >= localExpiresAtTime; }
java
private void scheduleAcknowledgment(final String topic) { if (!acknowledgeScheduled.has(topic)) { acknowledgeScheduled.set(topic, true); Platform.scheduler().scheduleDelay(acknowledgeDelayMillis, new Handler<Void>() { @Override public void handle(Void event) { if (acknowledgeSc...
java
@Override public FutureResultImpl<T> setFailure(Throwable throwable) { this.throwable = throwable; failed = true; checkCallHandler(); return this; }
java
@Override public FutureResultImpl<T> setHandler(Handler<AsyncResult<T>> handler) { this.handler = handler; checkCallHandler(); return this; }
java
@Override public FutureResultImpl<T> setResult(T result) { this.result = result; succeeded = true; checkCallHandler(); return this; }
java
public BackOffParameters next() { int ret = Math.min(nextBackOffTime, maxBackOff); nextBackOffTime += backOffTime; if (nextBackOffTime <= 0) { nextBackOffTime = Integer.MAX_VALUE; } backOffTime = ret; int randomizeTime = (int) (backOffTime * (1.0 + (Math.random() * randomizationFactor)));...
java
public Object getItem(ELContext context, int i) { if (originalListObject == null) { originalListObject = orig.getValue(context); if (originalListObject instanceof Collection) { type = TypesEnum.ACollection; } else if (originalListObject instanceof Iterator) { ...
java
@Override public int doEndTag() throws JspException { // produce a Document by parsing whatever the attributes tell us to use Object xmlText = this.xml; if (xmlText == null) { // if the attribute was specified, use the body as 'xml' if (bodyContent != null && bodyCont...
java
private Document parseInputSourceWithFilter(InputSource s, XMLFilter f) throws JspException { try { XMLReader xr = XmlUtil.newXMLReader(entityResolver); // (note that we overwrite the filter's parent. this seems // to be expected usage. we could cache and reset the old...
java
private Document parseInputSource(InputSource s) throws JspException { try { DocumentBuilder db = XmlUtil.newDocumentBuilder(); db.setEntityResolver(entityResolver); return db.parse(s); } catch (SAXException e) { throw new JspException(e); } catch ...
java
public void setScope(String scope) { if (scope.equalsIgnoreCase("page")) { this.scope = PageContext.PAGE_SCOPE; } else if (scope.equalsIgnoreCase("request")) { this.scope = PageContext.REQUEST_SCOPE; } else if (scope.equalsIgnoreCase("session")) { this.scope =...
java
public static String getContentTypeAttribute(String input, String name) { int begin; int end; int index = input.toUpperCase().indexOf(name.toUpperCase()); if (index == -1) { return null; } index = index + name.length(); // positioned after the attribute name ...
java
public Map getAsMap() { if (mMap != null) { return mMap; } else { Map m = convertToMap(); if (!isMutable()) { mMap = m; } return m; } }
java
Map convertToMap() { Map ret = new HashMap(); for (Enumeration e = enumerateKeys(); e.hasMoreElements();) { Object key = e.nextElement(); Object value = getValue(key); ret.put(key, value); } return ret; }
java
@Override public int doEndTag() throws JspException { Tag t = findAncestorWithClass(this, ParamParent.class); if (t == null) { throw new JspTagException( Resources.getMessage("PARAM_OUTSIDE_PARENT")); } // take no action for null or empty names ...
java
public static String[] union(String[] arr1, String[] arr2) { Set<String> set = new HashSet<String>(); for (String str : arr1) { set.add(str); } for (String str : arr2) { set.add(str); } String[] result = {}; return set.toArray(result); }
java
public static String[] intersect(String[] arr1, String[] arr2) { Map<String, Boolean> map = new HashMap<String, Boolean>(); LinkedList<String> list = new LinkedList<String>(); for (String str : arr1) { if (!map.containsKey(str)) { map.put(str, Boolean.FALSE); } } for (String str : arr2) { if (map...
java
public static String[] minus(String[] arr1, String[] arr2) { LinkedList<String> list = new LinkedList<String>(); LinkedList<String> history = new LinkedList<String>(); String[] longerArr = arr1; String[] shorterArr = arr2; if (arr1.length > arr2.length) { longerArr = arr2; shorterArr = arr1; } for (...
java
@Override public int doEndTag() throws JspException { try { conn.commit(); } catch (SQLException e) { throw new JspTagException( Resources.getMessage("TRANSACTION_COMMIT_ERROR", e.toString()), e); } return EVAL_P...
java
public void doCatch(Throwable t) throws Throwable { if (conn != null) { try { conn.rollback(); } catch (SQLException e) { // Ignore to not hide orignal exception } } throw t; }
java
public void setIsolation(String iso) throws JspTagException { if (TRANSACTION_READ_COMMITTED.equals(iso)) { isolation = Connection.TRANSACTION_READ_COMMITTED; } else if (TRANSACTION_READ_UNCOMMITTED.equals(iso)) { isolation = Connection.TRANSACTION_READ_UNCOMMITTED; } el...
java
public static BeanInfoManager getBeanInfoManager(Class pClass) { BeanInfoManager ret = (BeanInfoManager) mBeanInfoManagerByClass.get(pClass); if (ret == null) { ret = createBeanInfoManager(pClass); } return ret; }
java
public static BeanInfoProperty getBeanInfoProperty (Class pClass, String pPropertyName, Logger pLogger) throws ELException { return getBeanInfoManager(pClass).getProperty(pPropertyName, pLogger); }
java
public static BeanInfoIndexedProperty getBeanInfoIndexedProperty (Class pClass, String pIndexedPropertyName, Logger pLogger) throws ELException { return getBeanInfoManager (pClass).getIndexedProperty(pIndexedPropertyName, pLogger); }
java
void checkInitialized(Logger pLogger) throws ELException { if (!mInitialized) { synchronized (this) { if (!mInitialized) { initialize(pLogger); mInitialized = true; } } } }
java
void initialize(Logger pLogger) throws ELException { try { mBeanInfo = Introspector.getBeanInfo(mBeanClass); mPropertyByName = new HashMap(); mIndexedPropertyByName = new HashMap(); PropertyDescriptor[] pds = mBeanInfo.getPropertyDescriptors(); ...
java
public BeanInfoProperty getProperty(String pPropertyName, Logger pLogger) throws ELException { checkInitialized(pLogger); return (BeanInfoProperty) mPropertyByName.get(pPropertyName); }
java
public BeanInfoIndexedProperty getIndexedProperty (String pIndexedPropertyName, Logger pLogger) throws ELException { checkInitialized(pLogger); return (BeanInfoIndexedProperty) mIndexedPropertyByName.get(pIndexedPropertyName); }
java
public EventSetDescriptor getEventSet(String pEventSetName, Logger pLogger) throws ELException { checkInitialized(pLogger); return (EventSetDescriptor) mEventSetByName.get(pEventSetName); }
java
static Method getPublicMethod(Method pMethod) { if (pMethod == null) { return null; } // See if the method is already available from a public class Class cl = pMethod.getDeclaringClass(); if (Modifier.isPublic(cl.getModifiers())) { return pMethod; ...
java
static Method getPublicMethod(Class pClass, Method pMethod) { // See if this is a public class declaring the method if (Modifier.isPublic(pClass.getModifiers())) { try { Method m; try { m = pClass.getDeclar...
java
@Override public int doStartTag() throws JspException { // Sanity check if (context != null && (!context.startsWith("/") || !url.startsWith("/"))) { throw new JspTagException( Resources.getMessage("IMPORT_BAD_RELATIVE")); } // reset pa...
java
public void doFinally() { try { // If we exposed a Reader in doStartTag(), close it. if (varReader != null) { // 'r' can be null if an exception was thrown... if (r != null) { r.close(); } pageContext.rem...
java