Java Code Examples for java.util.List#isEmpty()

The following examples show how to use java.util.List#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RegionMaker.java    From jadx with Apache License 2.0 6 votes vote down vote up
private boolean canInsertBreak(BlockNode exit) {
	if (exit.contains(AFlag.RETURN)
			|| BlockUtils.checkLastInsnType(exit, InsnType.BREAK)) {
		return false;
	}
	List<BlockNode> simplePath = BlockUtils.buildSimplePath(exit);
	if (!simplePath.isEmpty()) {
		BlockNode lastBlock = simplePath.get(simplePath.size() - 1);
		if (lastBlock.contains(AFlag.RETURN)
				|| lastBlock.getSuccessors().isEmpty()) {
			return false;
		}
	}
	// check if there no outer switch (TODO: very expensive check)
	Set<BlockNode> paths = BlockUtils.getAllPathsBlocks(mth.getEnterBlock(), exit);
	for (BlockNode block : paths) {
		if (BlockUtils.checkLastInsnType(block, InsnType.SWITCH)) {
			return false;
		}
	}
	return true;
}
 
Example 2
Source File: InsnRemover.java    From Box with Apache License 2.0 6 votes vote down vote up
private static void removeAll(List<InsnNode> insns, List<InsnNode> toRemove) {
	if (toRemove == null || toRemove.isEmpty()) {
		return;
	}
	for (InsnNode rem : toRemove) {
		int insnsCount = insns.size();
		boolean found = false;
		for (int i = 0; i < insnsCount; i++) {
			if (insns.get(i) == rem) {
				insns.remove(i);
				found = true;
				break;
			}
		}
		if (!found && Consts.DEBUG) { // TODO: enable this
			throw new JadxRuntimeException("Can't remove insn:\n " + rem
					+ "\nnot found in list:\n " + Utils.listToString(insns, "\n "));
		}
	}
}
 
Example 3
Source File: JsonPMessageConverter.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void writeInternal( RootNode rootNode, HttpOutputMessage outputMessage ) throws IOException, HttpMessageNotWritableException
{
    List<String> callbacks = Lists.newArrayList( contextService.getParameterValues( DEFAULT_CALLBACK_PARAMETER ) );

    String callbackParam;

    if ( callbacks.isEmpty() )
    {
        callbackParam = DEFAULT_CALLBACK_PARAMETER;
    }
    else
    {
        callbackParam = callbacks.get( 0 );
    }

    rootNode.getConfig().getProperties().put( Jackson2JsonNodeSerializer.JSONP_CALLBACK, callbackParam );

    super.writeInternal( rootNode, outputMessage );
}
 
Example 4
Source File: DefaultZookeeperEnsembleService.java    From hermes with Apache License 2.0 6 votes vote down vote up
@Override
public com.ctrip.hermes.metaservice.model.ZookeeperEnsemble getPrimaryZookeeperEnsemble() {
	List<com.ctrip.hermes.metaservice.model.ZookeeperEnsemble> primaryZk;
	try {
		primaryZk = m_dao.findPrimary(ZookeeperEnsembleEntity.READSET_FULL);
	} catch (DalException e) {
		log.error("Can not get primary zookeeper ensemble from db!", e);
		throw new RuntimeException(String.format("Can not get primary zookeeper ensemble from db for reason: %s",
		      e.getMessage()));
	}
	if (primaryZk.size() >= 1) {
		log.error("Existing {} primary zookeeper ensemble in db, will return the first one.", primaryZk.size());
	} else if (primaryZk.isEmpty()) {
		log.error("No primary zookeeper ensemble exists in db!");
		return null;
	}

	return primaryZk.get(0);
}
 
Example 5
Source File: NotesViewEntryData.java    From domino-jna with Apache License 2.0 6 votes vote down vote up
@Override
public Long getAsLong(String columnName, Long defaultValue) {
	Object val = get(columnName);
	if (val instanceof Number) {
		return ((Number) val).longValue();
	}
	else if (val instanceof List) {
		List<?> valAsList = (List<?>) val;
		if (!valAsList.isEmpty()) {
			Object firstVal = valAsList.get(0);
			if (firstVal instanceof Number) {
				return ((Number) firstVal).longValue();
			}
		}
	}
	return defaultValue;
}
 
Example 6
Source File: BattlePanel.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
BombardComponent(
    final Unit unit,
    final Territory unitTerritory,
    final Collection<Territory> territories,
    final boolean noneAvailable) {
  this.setLayout(new BorderLayout());
  final String unitName = unit.getType().getName() + " in " + unitTerritory;
  final JLabel label = new JLabel("Which territory should " + unitName + " bombard?");
  this.add(label, BorderLayout.NORTH);
  final List<Object> listElements = new ArrayList<>(territories);
  if (noneAvailable) {
    listElements.add(0, "None");
  }
  list = new JList<>(SwingComponents.newListModel(listElements));
  list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  if (!listElements.isEmpty()) {
    list.setSelectedIndex(0);
  }
  final JScrollPane scroll = new JScrollPane(list);
  this.add(scroll, BorderLayout.CENTER);
}
 
Example 7
Source File: SingularityTaskIdHistory.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static SingularityTaskIdHistory fromTaskIdAndTaskAndUpdates(
  SingularityTaskId taskId,
  SingularityTask task,
  List<SingularityTaskHistoryUpdate> updates
) {
  ExtendedTaskState lastTaskState = null;
  long updatedAt = taskId.getStartedAt();

  if (updates != null && !updates.isEmpty()) {
    SingularityTaskHistoryUpdate lastUpdate = Collections.max(updates);
    lastTaskState = lastUpdate.getTaskState();
    updatedAt = lastUpdate.getTimestamp();
  }

  return new SingularityTaskIdHistory(
    taskId,
    updatedAt,
    Optional.ofNullable(lastTaskState),
    task.getTaskRequest().getPendingTask().getRunId()
  );
}
 
Example 8
Source File: OkrWorkProcessIdentityService.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 判断一个工作是否是用户阅知的工作, 用户是否在工作的干系人身份中拥有阅知者身份
 * @param workId
 * @return
 * @throws Exception 
 */
public Boolean isMyReadCenter( String userIdentity, String centerId ) throws Exception {
	if( userIdentity == null || userIdentity.isEmpty() ){
		throw new Exception("user identity is null, can not query work person.");
	}
	if( centerId == null || centerId.isEmpty() ){
		throw new Exception("centerId is null, can not query work person.");
	}
	List<String> ids = okrWorkPersonService.listByWorkAndIdentity( centerId, null, userIdentity, "阅知者", null );
	if( ids != null && !ids.isEmpty() ){
		return true;
	}
	return false;
}
 
Example 9
Source File: HttpExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<MimeRequest> precisionRequests(ExchangeInfo info, long delay) {
    List<MimeRequest> requests = this.precisionsRequests(info, delay);
    if (requests.isEmpty()) {
        return this.depthRequests(info, delay);
    }
    return requests;
}
 
Example 10
Source File: BaseDemoActivity.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
/**
 * shareURL
 *
 * Generates a message that is sent out via email, chat, social media, etc.
 * This message contains the URL to the website that holds the streaming
 * data, as well as a signature block.
 *
 */
private void shareURL() {
    String url = getSharedUrl();
    String message = String.format(getString(R.string.share_message), url, BuildConfig.MICROSITE_URL);

    List<Intent> targetedSharedIntents = new ArrayList<Intent>();
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");

    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(shareIntent, 0);
    if (!resInfo.isEmpty()) {
        for (ResolveInfo resolveInfo: resInfo) {
            String packageName = resolveInfo.activityInfo.packageName;
            Timber.d("package: " + packageName);

            Intent targetedSharedIntent = new Intent(Intent.ACTION_SEND);
            targetedSharedIntent.setType("text/plain");

            if (TextUtils.equals(packageName, "com.google.android.apps.docs")) {
                // copy the url to the clipboard
                targetedSharedIntent.putExtra(Intent.EXTRA_TEXT, url);
            } else {
                // everything else...
                targetedSharedIntent.putExtra(Intent.EXTRA_TEXT, message);
            }

            targetedSharedIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));

            targetedSharedIntent.setPackage(packageName);
            targetedSharedIntents.add(targetedSharedIntent);
        }

        Intent chooserIntent = Intent.createChooser(targetedSharedIntents.remove(0), getString(R.string.share_link));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedSharedIntents.toArray(new Parcelable[]{}));
        startActivity(chooserIntent);
    }
}
 
Example 11
Source File: SAMLUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
private static List<String> parseRolesInAssertion(org.opensaml.saml2.core.Assertion assertion,
            String roleAttributeName) {
        List<org.opensaml.saml2.core.AttributeStatement> attributeStatements = 
            assertion.getAttributeStatements();
        if (attributeStatements == null || attributeStatements.isEmpty()) {
            return null;
        }
        List<String> roles = new ArrayList<String>();
        
        for (org.opensaml.saml2.core.AttributeStatement statement : attributeStatements) {
            
            List<org.opensaml.saml2.core.Attribute> attributes = statement.getAttributes();
            for (org.opensaml.saml2.core.Attribute attribute : attributes) {
                
                if (attribute.getName().equals(roleAttributeName)) {
                    for (XMLObject attributeValue : attribute.getAttributeValues()) {
                        Element attributeValueElement = attributeValue.getDOM();
                        String value = attributeValueElement.getTextContent();
                        roles.add(value);                    
                    }
                    if (attribute.getAttributeValues().size() > 1) {
//                        Don't search for other attributes with the same name if                         
//                        <saml:Attribute xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
//                             AttributeNamespace="http://schemas.xmlsoap.org/claims" AttributeName="roles">
//                        <saml:AttributeValue>Value1</saml:AttributeValue>
//                        <saml:AttributeValue>Value2</saml:AttributeValue>
//                        </saml:Attribute>
                        break;
                    }
                }
                
            }
        }
        return Collections.unmodifiableList(roles);
    }
 
Example 12
Source File: MithraTestResource.java    From reladomo with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to insert test data into a test database. This method assumes that setUp() has been called in this instance
 * of MithraTestResource and that the MithraObject type has been included in the runtime configuration.
 *
 * @param dataObjects
 */
private void insertTestData(List<? extends MithraDataObject> dataObjects, Object source)
{
    if (dataObjects != null && !dataObjects.isEmpty())
    {
        MithraDataObject firstData = dataObjects.get(0);
        RelatedFinder finder = firstData.zGetMithraObjectPortal().getFinder();

        ((MithraAbstractDatabaseObject) finder.getMithraObjectPortal().getDatabaseObject()).insertData(
                Arrays.asList(finder.getPersistentAttributes()), dataObjects, source
        );
        finder.getMithraObjectPortal().clearQueryCache();
    }
}
 
Example 13
Source File: TomcatRunConfiguration.java    From SmartTomcat with Apache License 2.0 5 votes vote down vote up
protected TomcatRunConfiguration(@NotNull Project project, @NotNull ConfigurationFactory factory, String name) {
    super(project, factory, name);
    TomcatInfoConfigs applicationService = ServiceManager.getService(TomcatInfoConfigs.class);
    List<TomcatInfo> tomcatInfos = applicationService.getTomcatInfos();
    if (!tomcatInfos.isEmpty()) {
        this.tomcatInfo = tomcatInfos.get(0);
    }
}
 
Example 14
Source File: ConfigurationPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Generate download message from extra modules texts
 * @param extraModulesTexts
 * @return String Text to set in download label
 */
protected String generateDownloadMessageFromExtraModulesTexts(List<String> extraModulesTexts) {
    StringBuilder sbDownload = new StringBuilder();
    if (!extraModulesTexts.isEmpty()) {
        sbDownload.append("<html><body>");
        for (int i = 0; i < extraModulesTexts.size(); i++) {
            sbDownload.append(extraModulesTexts.get(i));
            if (extraModulesTexts.size() > 1 && i < extraModulesTexts.size() - 1) {
                sbDownload.append("<br>");
            }
        }
        sbDownload.append("</body></html>");
    }
    return sbDownload.toString();
}
 
Example 15
Source File: ShouldExtensions.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Ensure that the given type extends specific types.
 *
 * @param type the type to check.
 * @param expectedTypes the qualified names of the expected types, separated by comas.
 * @return the validation status.
 */
public static boolean shouldExtend(Class<?> type, String expectedTypes) {
	if (type == null) {
		return false;
	}
	try {
		final Class<?> st = type.getSuperclass();
		final List<Class<?>> types = new LinkedList<>();
		if (st == null || Object.class.equals(st)) {
			if (type.isInterface()) {
				types.addAll(Arrays.asList(type.getInterfaces()));
			}
		} else {
			types.add(st);
		}
		//
		if (expectedTypes == null || expectedTypes.isEmpty()) {
			return types.isEmpty();
		}
		for (final String expectedType : expectedTypes.split("\\s*,\\s*")) { //$NON-NLS-1$
			final Class<?> et = ReflectionUtil.forName(expectedType);
			if (!types.remove(et)) {
				return false;
			}
		}
		return types.isEmpty();
	} catch (Throwable e) {
		//
	}
	return false;
}
 
Example 16
Source File: ConcurrentMapEventStore.java    From Moss with Apache License 2.0 5 votes vote down vote up
protected boolean doAppend(List<InstanceEvent> events) {
    if (events.isEmpty()) {
        return true;
    }

    InstanceId id = events.get(0).getInstance();
    if (!events.stream().allMatch(event -> event.getInstance().equals(id))) {
        throw new IllegalArgumentException("'events' must only refer to the same instance.");
    }

    List<InstanceEvent> oldEvents = eventLog.computeIfAbsent(id,
        (key) -> new ArrayList<>(maxLogSizePerAggregate + 1));

    long lastVersion = getLastVersion(oldEvents);
    if (lastVersion >= events.get(0).getVersion()) {
        throw createOptimisticLockException(events.get(0), lastVersion);
    }

    List<InstanceEvent> newEvents = new ArrayList<>(oldEvents);
    newEvents.addAll(events);

    if (newEvents.size() > maxLogSizePerAggregate) {
        log.debug("Threshold for {} reached. Compacting events", id);
        compact(newEvents);
    }

    if (eventLog.replace(id, oldEvents, newEvents)) {
        log.debug("Events appended to log {}", events);
        return true;
    }

    log.debug("Unsuccessful attempot append the events {} ", events);
    return false;
}
 
Example 17
Source File: BuilderManager.java    From OpenRTS with MIT License 5 votes vote down vote up
private static <T extends Builder> List<T> getAllBuilders(String type, Class<T> clazz) {
	List<T> res = new ArrayList<>();
	res.addAll((Collection<? extends T>) (builders.get(type)).values());
	if (res.isEmpty()) {
		throw new TechnicalException("type '" + type + "' dosen't seem to have any element.");
	}
	return res;
}
 
Example 18
Source File: Lists.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
public static <V> V firstOrDefault(List<V> list, V defaultValue) {
    return list.isEmpty() ? defaultValue : list.get(0);
}
 
Example 19
Source File: AttackTableTab.java    From dsworkbench with Apache License 2.0 4 votes vote down vote up
private void sendAttacksToBrowser() {
    List<Attack> attacks = getSelectedAttacks();
    if (attacks.isEmpty()) {
        showInfo("Keine Befehle ausgewählt");
        return;
    }
    int sentAttacks = 0;
    int ignoredAttacks = 0;
    UserProfile profile = DSWorkbenchAttackFrame.getSingleton().getQuickProfile();
    boolean clickAccountEmpty = false;

    for (Attack a : attacks) {
        if (!a.isTransferredToBrowser()) {
            if (attacks.size() > 1) {//try to use click in case of multiple attacks
                if (!DSWorkbenchAttackFrame.getSingleton().decreaseClickAccountValue()) {
                    //no click left
                    clickAccountEmpty = true;
                    break;
                }
            }

            if (BrowserInterface.sendAttack(a, profile)) {
                a.setTransferredToBrowser(true);
                sentAttacks++;
            } else {//give click back in case of an error and for multiple attacks
                if (attacks.size() > 1) {
                    DSWorkbenchAttackFrame.getSingleton().increaseClickAccountValue();
                }
            }
        } else {
            ignoredAttacks++;
        }
    }

    if (sentAttacks == 1) {
        jxAttackTable.getSelectionModel().setSelectionInterval(jxAttackTable.getSelectedRow() + 1, jxAttackTable.getSelectedRow() + 1);
    } else {
        jxAttackTable.getSelectionModel().setSelectionInterval(jxAttackTable.getSelectedRow() + sentAttacks, jxAttackTable.getSelectedRow() + sentAttacks);
    }

    String usedProfile = "";
    if (profile != null) {
        usedProfile = "als " + profile.toString();
    }
    String message = "<html>" + sentAttacks + " von " + attacks.size() + " Befehle(n) " + usedProfile + " in den Browser &uuml;bertragen";
    if (ignoredAttacks != 0) {
        message += "<br/>" + ignoredAttacks + " Befehl(e) ignoriert, da sie bereits &uuml;bertragen wurden";
    }

    if (clickAccountEmpty) {
        message += "<br/>Keine weiteren Klicks auf dem Klick-Konto!";
    }
    message += "</html>";
    showInfo(message);
}
 
Example 20
Source File: BankDetailsServiceAccountImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * In this implementation, we use the O2M in payment mode.
 *
 * @param company
 * @param paymentMode
 * @return
 * @throws AxelorException
 */
@Override
public String createCompanyBankDetailsDomain(
    Partner partner, Company company, PaymentMode paymentMode, Integer operationTypeSelect)
    throws AxelorException {

  AppAccountService appAccountService = Beans.get(AppAccountService.class);

  if (!appAccountService.isApp("account")
      || !appAccountService.getAppBase().getManageMultiBanks()) {
    return super.createCompanyBankDetailsDomain(
        partner, company, paymentMode, operationTypeSelect);
  } else {

    if (partner != null) {
      partner = Beans.get(PartnerRepository.class).find(partner.getId());
    }

    List<BankDetails> authorizedBankDetails = new ArrayList<>();

    if (partner != null
        && partner.getFactorizedCustomer()
        && operationTypeSelect != null
        && (operationTypeSelect.intValue() == InvoiceRepository.OPERATION_TYPE_CLIENT_SALE
            || operationTypeSelect.intValue()
                == InvoiceRepository.OPERATION_TYPE_CLIENT_REFUND)) {

      authorizedBankDetails = createCompanyBankDetailsDomainFromFactorPartner(company);
    } else {

      if (paymentMode == null) {
        return "self.id IN (0)";
      }
      List<AccountManagement> accountManagementList = paymentMode.getAccountManagementList();

      authorizedBankDetails = new ArrayList<>();

      for (AccountManagement accountManagement : accountManagementList) {
        if (accountManagement.getCompany() != null
            && accountManagement.getCompany().equals(company)) {
          authorizedBankDetails.add(accountManagement.getBankDetails());
        }
      }
    }

    if (authorizedBankDetails.isEmpty()) {
      return "self.id IN (0)";
    } else {
      return "self.id IN ("
          + StringTool.getIdListString(authorizedBankDetails)
          + ") AND self.active = true";
    }
  }
}