Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

In this page you can find the example usage for java.util HashMap isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:org.kuali.ole.module.purap.document.service.impl.PaymentRequestServiceImpl.java

/**
 * @see org.kuali.ole.module.purap.document.service.PaymentRequestService#populatePaymentRequest(org.kuali.ole.module.purap.document.PaymentRequestDocument)
 *///from  ww  w  .j ava  2s.c o  m
@Override
public void populatePaymentRequest(PaymentRequestDocument paymentRequestDocument) {

    PurchaseOrderDocument purchaseOrderDocument = paymentRequestDocument.getPurchaseOrderDocument();

    // make a call to search for expired/closed accounts
    HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList = getAccountsPayableService()
            .getExpiredOrClosedAccountList(paymentRequestDocument);
    if (paymentRequestDocument.getInvoiceIdentifier() == null) {
        paymentRequestDocument.populatePaymentRequestFromPurchaseOrder(purchaseOrderDocument,
                expiredOrClosedAccountList);
    }

    paymentRequestDocument.getDocumentHeader().setDocumentDescription(createPreqDocumentDescription(
            paymentRequestDocument.getPurchaseOrderIdentifier(), paymentRequestDocument.getVendorName()));

    // write a note for expired/closed accounts if any exist and add a message stating there were expired/closed accounts at the
    // top of the document
    getAccountsPayableService().generateExpiredOrClosedAccountNote(paymentRequestDocument,
            expiredOrClosedAccountList);

    // set indicator so a message is displayed for accounts that were replaced due to expired/closed status
    if (!expiredOrClosedAccountList.isEmpty()) {
        paymentRequestDocument.setContinuationAccountIndicator(true);
    }

    // add discount item
    calculateDiscount(paymentRequestDocument);
    // distribute accounts (i.e. proration)
    distributeAccounting(paymentRequestDocument);

    // set bank code to default bank code in the system parameter
    Bank defaultBank = bankService.getDefaultBankByDocType(paymentRequestDocument.getClass());
    if (defaultBank != null) {
        paymentRequestDocument.setBankCode(defaultBank.getBankCode());
        paymentRequestDocument.setBank(defaultBank);
    }
}

From source file:org.kuali.kfs.module.purap.document.service.impl.PaymentRequestServiceImpl.java

/**
 * @see org.kuali.kfs.module.purap.document.service.PaymentRequestService#populatePaymentRequest(org.kuali.kfs.module.purap.document.PaymentRequestDocument)
 *///  www  . j  av  a 2 s.  c  o  m
@Override
@NonTransactional
public void populatePaymentRequest(PaymentRequestDocument paymentRequestDocument) {

    PurchaseOrderDocument purchaseOrderDocument = paymentRequestDocument.getPurchaseOrderDocument();

    // make a call to search for expired/closed accounts
    HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList = getAccountsPayableService()
            .getExpiredOrClosedAccountList(paymentRequestDocument);

    paymentRequestDocument.populatePaymentRequestFromPurchaseOrder(purchaseOrderDocument,
            expiredOrClosedAccountList);

    paymentRequestDocument.getDocumentHeader().setDocumentDescription(createPreqDocumentDescription(
            paymentRequestDocument.getPurchaseOrderIdentifier(), paymentRequestDocument.getVendorName()));

    // write a note for expired/closed accounts if any exist and add a message stating there were expired/closed accounts at the
    // top of the document
    getAccountsPayableService().generateExpiredOrClosedAccountNote(paymentRequestDocument,
            expiredOrClosedAccountList);

    // set indicator so a message is displayed for accounts that were replaced due to expired/closed status
    if (!expiredOrClosedAccountList.isEmpty()) {
        paymentRequestDocument.setContinuationAccountIndicator(true);
    }

    // add discount item
    calculateDiscount(paymentRequestDocument);
    // distribute accounts (i.e. proration)
    distributeAccounting(paymentRequestDocument);

    // set bank code to default bank code in the system parameter
    Bank defaultBank = bankService.getDefaultBankByDocType(paymentRequestDocument.getClass());
    if (defaultBank != null) {
        paymentRequestDocument.setBankCode(defaultBank.getBankCode());
        paymentRequestDocument.setBank(defaultBank);
    }
}

From source file:org.apache.hadoop.hbase.master.assignment.AssignmentManager.java

private void processAssignQueue() {
    final HashMap<HRegionInfo, RegionStateNode> regions = waitOnAssignQueue();
    if (regions == null || regions.size() == 0 || !isRunning()) {
        return;/*from w  ww .  j  a v  a 2  s.com*/
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("PROCESS ASSIGN QUEUE regionCount=" + regions.size());
    }

    // TODO: Optimize balancer. pass a RegionPlan?
    final HashMap<HRegionInfo, ServerName> retainMap = new HashMap<HRegionInfo, ServerName>();
    final List<HRegionInfo> rrList = new ArrayList<HRegionInfo>();
    for (RegionStateNode regionNode : regions.values()) {
        if (regionNode.getRegionLocation() != null) {
            retainMap.put(regionNode.getRegionInfo(), regionNode.getRegionLocation());
        } else {
            rrList.add(regionNode.getRegionInfo());
        }
    }

    // TODO: connect with the listener to invalidate the cache
    final LoadBalancer balancer = getBalancer();

    // TODO use events
    List<ServerName> servers = master.getServerManager().createDestinationServersList();
    for (int i = 0; servers.size() < 1; ++i) {
        if (i % 4 == 0) {
            LOG.warn("no server available, unable to find a location for " + regions.size()
                    + " unassigned regions. waiting");
        }

        // the was AM killed
        if (!isRunning()) {
            LOG.debug("aborting assignment-queue with " + regions.size() + " not assigned");
            return;
        }

        Threads.sleep(250);
        servers = master.getServerManager().createDestinationServersList();
    }

    final boolean isTraceEnabled = LOG.isTraceEnabled();
    if (isTraceEnabled) {
        LOG.trace("available servers count=" + servers.size() + ": " + servers);
    }

    // ask the balancer where to place regions
    if (!retainMap.isEmpty()) {
        if (isTraceEnabled) {
            LOG.trace("retain assign regions=" + retainMap);
        }
        try {
            acceptPlan(regions, balancer.retainAssignment(retainMap, servers));
        } catch (HBaseIOException e) {
            LOG.warn("unable to retain assignment", e);
            addToPendingAssignment(regions, retainMap.keySet());
        }
    }

    // TODO: Do we need to split retain and round-robin?
    // the retain seems to fallback to round-robin/random if the region is not in the map.
    if (!rrList.isEmpty()) {
        Collections.sort(rrList);
        if (isTraceEnabled) {
            LOG.trace("round robin regions=" + rrList);
        }
        try {
            acceptPlan(regions, balancer.roundRobinAssignment(rrList, servers));
        } catch (HBaseIOException e) {
            LOG.warn("unable to round-robin assignment", e);
            addToPendingAssignment(regions, rrList);
        }
    }
}

From source file:mondrian.olap.Util.java

public static <T> Set<T> newIdentityHashSetFake() {
    final HashMap<T, Boolean> map = new HashMap<T, Boolean>();
    return new Set<T>() {
        public int size() {
            return map.size();
        }//  w  w  w. ja  v a2s.com

        public boolean isEmpty() {
            return map.isEmpty();
        }

        public boolean contains(Object o) {
            return map.containsKey(o);
        }

        public Iterator<T> iterator() {
            return map.keySet().iterator();
        }

        public Object[] toArray() {
            return map.keySet().toArray();
        }

        public <T> T[] toArray(T[] a) {
            return map.keySet().toArray(a);
        }

        public boolean add(T t) {
            return map.put(t, Boolean.TRUE) == null;
        }

        public boolean remove(Object o) {
            return map.remove(o) == Boolean.TRUE;
        }

        public boolean containsAll(Collection<?> c) {
            return map.keySet().containsAll(c);
        }

        public boolean addAll(Collection<? extends T> c) {
            throw new UnsupportedOperationException();
        }

        public boolean retainAll(Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        public boolean removeAll(Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        public void clear() {
            map.clear();
        }
    };
}

From source file:org.kuali.kfs.vnd.document.validation.impl.VendorRule.java

/**
 * Checks if the allow default indicator is set to false for this address the default indicator cannot be set to true/yes. If
 * "allow default indicator" is set to true/yes for address type, one address must have the default indicator set (no more, no
 * less) and only one campus to be set as default for this address.
 *
 * @param vendorDetail VendorDetail document
 * @return boolean false or true/*from   w ww  .  j a  v  a2s .  c o  m*/
 */

boolean validateDefaultAddressCampus(VendorDetail vendorDetail) {
    List<VendorAddress> vendorAddresses = vendorDetail.getVendorAddresses();
    String addressTypeCode;
    String addressTypeDesc;
    String campusCode;
    boolean valid = true;
    boolean previousValue = false;

    // This is a HashMap to store the default Address Type Codes and their associated default Indicator
    HashMap addressTypeCodeDefaultIndicator = new HashMap();

    // This is a HashMap to store Address Type Codes and Address Campus Codes for Default Addresses
    HashMap addressTypeDefaultCampus = new HashMap();

    // This is a HashSet for storing only the Address Type Codes which have at least one default Indicator set to true
    HashSet addressTypesHavingDefaultTrue = new HashSet();

    int i = 0;
    for (VendorAddress address : vendorAddresses) {
        addressTypeCode = address.getVendorAddressTypeCode();
        addressTypeDesc = address.getVendorAddressType().getVendorAddressTypeDescription();
        String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i + "]";
        GlobalVariables.getMessageMap().addToErrorPath(errorPath);
        String[] parameters = new String[] { addressTypeCode };

        // If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set (no
        // more, no less).
        // For example, if a vendor contains three PO type addresses and the PO address type is set to allow defaults in the
        // address type table,
        // then only one of these PO addresses can have the default indicator set to true/yes.

        if (findAllowDefaultAddressIndicatorHelper(address)) {
            if (address.isVendorDefaultAddressIndicator()) {
                addressTypesHavingDefaultTrue.add(addressTypeCode);
            }
            if (!addressTypeCodeDefaultIndicator.isEmpty()
                    && addressTypeCodeDefaultIndicator.containsKey(addressTypeCode)) {
                previousValue = ((Boolean) addressTypeCodeDefaultIndicator.get(addressTypeCode)).booleanValue();
            }

            if (addressTypeCodeDefaultIndicator.put(addressTypeCode,
                    address.isVendorDefaultAddressIndicator()) != null && previousValue
                    && address.isVendorDefaultAddressIndicator()) {
                GlobalVariables.getMessageMap().putError(
                        VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR,
                        VendorKeyConstants.ERROR_ADDRESS_DEFAULT_INDICATOR, addressTypeDesc);
                valid = false;
            }

        }
        // If "allow default indicator" is set to false/no for address type, the default indicator cannot be set to true/yes.
        else {
            if (address.isVendorDefaultAddressIndicator()) {
                GlobalVariables.getMessageMap().putError(
                        VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR,
                        VendorKeyConstants.ERROR_ADDRESS_DEFAULT_ADDRESS_NOT_ALLOWED, parameters);
                valid = false;
            }

        }

        List<VendorDefaultAddress> vendorDefaultAddresses = address.getVendorDefaultAddresses();

        // If "allow default indicator" is set to true/yes for address type, a campus can only be set on one of each type of
        // Address.
        // For example, Bloomington can not be included in the campus list for two PO type addresses.
        // Each campus can only have one default address.
        int j = 0;
        for (VendorDefaultAddress defaultAddress : vendorDefaultAddresses) {
            campusCode = (String) addressTypeDefaultCampus.put(addressTypeCode,
                    defaultAddress.getVendorCampusCode());
            if (StringUtils.isNotBlank(campusCode)
                    && campusCode.equalsIgnoreCase(defaultAddress.getVendorCampusCode())) {
                String[] newParameters = new String[] { defaultAddress.getVendorCampusCode(), addressTypeCode };
                GlobalVariables.getMessageMap().putError(
                        VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS + "[" + j + "]."
                                + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_CAMPUS,
                        VendorKeyConstants.ERROR_ADDRESS_DEFAULT_CAMPUS, newParameters);
                valid = false;
            }
            j++;
        }
        i++;
        GlobalVariables.getMessageMap().removeFromErrorPath(errorPath);
    }

    // If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set to true
    if (!addressTypeCodeDefaultIndicator.isEmpty()) {
        Set<String> addressTypes = addressTypeCodeDefaultIndicator.keySet();

        for (String addressType : addressTypes) {
            if (!addressTypesHavingDefaultTrue.contains(addressType)) {

                int addressIndex = 0;
                for (VendorAddress address : vendorAddresses) {
                    String[] parameters = new String[] {
                            address.getVendorAddressType().getVendorAddressTypeDescription() };
                    String propertyName = VendorPropertyConstants.VENDOR_ADDRESS + "[" + addressIndex + "]."
                            + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR;
                    if (address.getVendorAddressType().getVendorAddressTypeCode()
                            .equalsIgnoreCase(addressType)) {
                        putFieldError(propertyName, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_INDICATOR,
                                parameters);
                        break;
                    }
                    addressIndex++;
                }
                valid = false;
            }

        }
    }

    return valid;
}

From source file:com.MainFiles.Functions.java

public HashMap<String, String> getSwitchResponse(HashMap<String, String> Fields) throws InterruptedException {

    String strResponse = "";
    String strAccount = "";
    String strCardno = "";
    String strMessageToPOS = "";
    HashMap<String, String> OriginalFieldsToSwitch = new HashMap<String, String>();
    try {/*from www.ja  v  a 2 s.  c  o m*/
        if (Fields != null || !Fields.isEmpty()) {

            String Field_2 = Fields.get("2") == null ? "" : Fields.get("2").toString();
            String Field_11 = Fields.get("11") == null ? "" : Fields.get("11").toString();
            ;
            String Field_39 = Fields.get("39") == null ? "" : Fields.get("39").toString();
            String Field_37 = Fields.get("37") == null ? "" : Fields.get("37").toString();
            String Field_102 = Fields.get("102") == null ? "" : Fields.get("102").toString();

            switch (Field_39) {
            case "00":
                // 1. GET ALL THE CONTENTS FROM THE ORIGINAL HASHMAP USING THE REFERENCE_NUMBER
                OriginalFieldsToSwitch = (HashMap<String, String>) OuterHoldingQueue.get(Field_37.trim());
                OuterHoldingQueue.remove(Field_37);

                //2. ADD ACCOUNT NUMBER FROM SWITCH TO ORIGINAL HASHMAP THEN SEND TO ESB
                OriginalFieldsToSwitch.put("102", Field_102);

                //3. SEND THE NEW HASHMAP COLLECTION TO ECONNECT
                String strcardNumber = OriginalFieldsToSwitch.get("2") == null ? ""
                        : OriginalFieldsToSwitch.get("2").toString();
                String strProcessingCode = OriginalFieldsToSwitch.get("3") == null ? ""
                        : OriginalFieldsToSwitch.get("3").toString();
                String strAmount = OriginalFieldsToSwitch.get("4") == null ? ""
                        : OriginalFieldsToSwitch.get("4").toString();
                String strReferenceNumber = OriginalFieldsToSwitch.get("37") == null ? ""
                        : OriginalFieldsToSwitch.get("37").toString();
                String strField65 = OriginalFieldsToSwitch.get("65") == null ? ""
                        : OriginalFieldsToSwitch.get("65").toString();
                String strField68 = OriginalFieldsToSwitch.get("68") == null ? ""
                        : OriginalFieldsToSwitch.get("68").toString();
                String strNarration = OriginalFieldsToSwitch.get("88") == null ? ""
                        : OriginalFieldsToSwitch.get("88").toString();
                String strTransactionIdentifier = OriginalFieldsToSwitch.get("100") == null ? ""
                        : OriginalFieldsToSwitch.get("100").toString();
                String strAccountNumber = OriginalFieldsToSwitch.get("102") == null ? ""
                        : OriginalFieldsToSwitch.get("102").toString();
                String strCreditAccount = OriginalFieldsToSwitch.get("103") == null ? ""
                        : OriginalFieldsToSwitch.get("103").toString();
                String strAgentID = OriginalFieldsToSwitch.get("104") == null ? ""
                        : OriginalFieldsToSwitch.get("104").toString();
                String strPhoneNumber = OriginalFieldsToSwitch.get("PhoneNumber") == null ? ""
                        : OriginalFieldsToSwitch.get("PhoneNumber").toString();

                this.getESBResponse(strAgentID, strcardNumber, strProcessingCode, strAmount, strReferenceNumber,
                        strNarration, strTransactionIdentifier, strAccountNumber, strCreditAccount, strField65,
                        strPhoneNumber, strField68);
                break;

            default:
                String ResponseDescription = getResponsePostillion(Field_39);
                // 1. GENERATE MESSAGE TO SEND TO POS
                OriginalFieldsToSwitch = (HashMap<String, String>) OuterHoldingQueue.get(Field_37.trim());

                strMessageToPOS += this.strResponseHeader(OriginalFieldsToSwitch.get("68").toString()) + "#";
                strMessageToPOS += "AGENT ID:  " + OriginalFieldsToSwitch.get("104").toString() + "#";
                strMessageToPOS += "TRAN NUM:  " + OriginalFieldsToSwitch.get("37").toString() + "#";
                strMessageToPOS += "--------------------------------" + "#";
                strMessageToPOS += "                                " + "#";
                strMessageToPOS += "        PIN VERIFICATION        " + "#";
                strMessageToPOS += "                                " + "#";
                strMessageToPOS += "    PIN VERIFICATION FAILED     " + "#";
                strMessageToPOS += padEqual(ResponseDescription) + " #";
                strMessageToPOS += " " + "#";
                strMessageToPOS += this.strResponseFooter(OriginalFieldsToSwitch.get("104").toString()) + "#";
                SendPOSResponse(strMessageToPOS, Field_37);

                // 2. REMOVE THE HASHMAP FROM THE OUTERMAP COLLECTION MAP
                OuterHoldingQueue.remove(Field_37);
                break;

            }
        }
    } catch (Exception ex) {
        this.log("Error on getSwitchResponse() " + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "ERROR");
    }
    return OriginalFieldsToSwitch;
}

From source file:hydrograph.ui.graph.editor.RenameJobParticipant.java

@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    final HashMap<IFile, RenameResourceChange> changes = new HashMap<IFile, RenameResourceChange>();
    final String newName = ResourceChangeUtil.removeExtension(getArguments().getNewName());

    if (modifiedResource.getParent() != null) {
        if (!StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(),
                CustomMessages.ProjectSupport_JOBS)) {
            List<IResource> memberList = new ArrayList<IResource>(modifiedResource.getProject()
                    .getFolder(modifiedResource.getParent().getName()).members().length);
            ResourceChangeUtil.addMembersToList(memberList,
                    modifiedResource.getProject().getFolder(modifiedResource.getParent().getName()));
            final String fileName = ResourceChangeUtil.removeExtension(modifiedResource.getName());
            for (IResource resource : memberList) {
                if (Pattern.matches(fileName + Constants.EXTENSION, resource.getName())) {
                    if ((StringUtils.equalsIgnoreCase(Messages.XML_EXT, resource.getFileExtension())
                            || StringUtils.equalsIgnoreCase(Messages.JOB_EXT, resource.getFileExtension()))
                            && !(StringUtils.equalsIgnoreCase(modifiedResource.getName(),
                                    resource.getName()))) {
                        getRenameChanges(changes, newName, resource);
                    }/*from w ww .ja  va 2s.co m*/
                }
            }
        } else if (StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(),
                CustomMessages.ProjectSupport_JOBS)
                || StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(),
                        CustomMessages.ProjectSupport_PARAM)) {
            List<IResource> memberList = new ArrayList<IResource>(modifiedResource.getProject()
                    .getFolder(CustomMessages.ProjectSupport_PARAM).members().length
                    + modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_JOBS)
                            .members().length);
            ResourceChangeUtil.addMembersToList(memberList,
                    modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_JOBS));
            ResourceChangeUtil.addMembersToList(memberList,
                    modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_PARAM));
            final String fileName = ResourceChangeUtil.removeExtension(modifiedResource.getName());
            for (IResource resource : memberList) {
                if (Pattern.matches(fileName + Constants.EXTENSION, resource.getName())) {
                    if ((StringUtils.equalsIgnoreCase(Messages.XML_EXT, resource.getFileExtension())
                            || StringUtils.equalsIgnoreCase(Messages.PROPERTIES_EXT,
                                    resource.getFileExtension())
                            || StringUtils.equalsIgnoreCase(Messages.JOB_EXT, resource.getFileExtension()))
                            && !(StringUtils.equalsIgnoreCase(modifiedResource.getName(),
                                    resource.getName()))) {
                        getRenameChanges(changes, newName, resource);
                    }
                    ;
                }
            }
        }
    }

    if (changes.isEmpty()) {
        return null;
    }

    CompositeChange result = new CompositeChange("Rename Job Related Files");
    for (Iterator<RenameResourceChange> iter = changes.values().iterator(); iter.hasNext();) {
        result.add((Change) iter.next());
    }
    return result;
}

From source file:com.zenesis.qx.remote.ProxyTypeImpl.java

/**
 * Constructor, used for defining interfaces which are to be proxied
 * @param className/*from  w  ww  .  j a va  2 s. c  o m*/
 * @param methods
 */
public ProxyTypeImpl(ProxyType superType, Class clazz, Set<ProxyType> interfaces) {
    super();
    if (interfaces == null)
        interfaces = Collections.EMPTY_SET;
    this.superType = superType;
    this.interfaces = interfaces;
    this.clazz = clazz;

    MethodsCompiler methodsCompiler = new MethodsCompiler();

    // Get a complete list of methods from the interfaces that the new class has to 
    //   implement; we include methods marked as DoNotProxy so that we can check for 
    //   conflicting instructions
    if (!clazz.isInterface()) {
        // Get a full list of the interfaces which our class has to implement
        HashSet<ProxyType> allInterfaces = new HashSet<ProxyType>();
        getAllInterfaces(allInterfaces, interfaces);

        for (ProxyType ifcType : allInterfaces) {
            try {
                methodsCompiler.addMethods(Class.forName(ifcType.getClassName()), true);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException("Cannot find class " + ifcType.getClassName());
            }
        }
    }

    boolean defaultProxy = false;
    if (clazz.isInterface())
        defaultProxy = true;
    else {
        for (Class tmp = clazz; tmp != null; tmp = tmp.getSuperclass()) {
            if (factoryMethod == null) {
                for (Method method : tmp.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(FactoryMethod.class)) {
                        if (!Modifier.isStatic(method.getModifiers()))
                            throw new IllegalStateException("Cannot use method " + method
                                    + " as FactoryMethod because it is not static");
                        factoryMethod = method;
                        method.setAccessible(true);
                        break;
                    }
                }
            }
            if (tmp.isAnnotationPresent(AlwaysProxy.class)) {
                defaultProxy = true;
                break;
            } else if (tmp.isAnnotationPresent(ExplicitProxyOnly.class)) {
                break;
            }
        }
    }

    // If the class does not have any proxied interfaces or the class is marked with
    //   the AlwaysProxy annotation, then we take methods from the class definition
    methodsCompiler.addMethods(clazz, defaultProxy);

    methodsCompiler.checkValid();
    methodsCompiler.removeSuperTypeMethods();

    // Load properties
    HashMap<String, ProxyEvent> events = new HashMap<String, ProxyEvent>();
    HashMap<String, ProxyProperty> properties = new HashMap<String, ProxyProperty>();
    Properties annoProperties = (Properties) clazz.getAnnotation(Properties.class);
    if (annoProperties != null) {
        for (Property anno : annoProperties.value()) {
            ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }
    for (Field field : clazz.getDeclaredFields()) {
        Property anno = field.getAnnotation(Property.class);
        if (anno != null) {
            ProxyProperty property = new ProxyPropertyImpl(clazz,
                    anno.value().length() > 0 ? anno.value() : field.getName(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }

    for (Method method : clazz.getDeclaredMethods()) {
        String name = method.getName();
        if (name.length() < 4 || !name.startsWith("get") || !Character.isUpperCase(name.charAt(3)))
            continue;
        Property anno = method.getAnnotation(Property.class);
        if (anno == null)
            continue;

        name = Character.toLowerCase(name.charAt(3)) + name.substring(4);
        if (properties.containsKey(name))
            continue;

        ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value().length() > 0 ? anno.value() : name,
                anno, annoProperties);
        properties.put(property.getName(), property);
        ProxyEvent event = property.getEvent();
        if (event != null)
            events.put(event.getName(), event);
    }

    // Classes need to have all inherited properties added
    if (!clazz.isInterface()) {
        for (ProxyType ifc : interfaces)
            addProperties((ProxyTypeImpl) ifc, properties);
    }

    // Remove property accessors
    for (ProxyProperty prop : properties.values())
        methodsCompiler.removePropertyAccessors((ProxyPropertyImpl) prop);

    // Load events
    if (clazz.isAnnotationPresent(Events.class)) {
        Events annoEvents = (Events) clazz.getAnnotation(Events.class);
        for (Event annoEvent : annoEvents.value()) {
            if (!events.containsKey(annoEvent.value()))
                events.put(annoEvent.value(), new ProxyEvent(annoEvent));
        }
    }

    // Classes need to have all inherited events added
    if (!clazz.isInterface()) {
        for (ProxyType type : interfaces)
            addEvents((ProxyTypeImpl) type, events);
    }

    // Save
    this.properties = properties.isEmpty() ? null : properties;
    this.events = events.isEmpty() ? null : events;
    this.methods = methodsCompiler.toArray();
}

From source file:eu.edisonproject.training.wsd.BabelNet.java

private Set<Term> babelNetDisambiguation(String language, String lemma, Set<String> ngarms) {
    if (ngarms.isEmpty()) {
        return null;
    }//  w ww . ja v  a  2s  .  co  m
    if (ngarms.size() == 1 && ngarms.iterator().next().length() <= 1) {
        return null;
    }

    HashMap<CharSequence, Double> idsMap = new HashMap<>();
    Map<CharSequence, Term> termMap = new HashMap<>();
    Set<Term> terms = new HashSet<>();
    int count = 0;
    int breaklimit = 1000;
    int oneElementlimit = 65;
    int difflimit = 60;
    Double persent;
    for (String n : ngarms) {
        if (n.length() <= 1) {
            continue;
        }
        count++;
        if (idsMap.size() == 1 && count > oneElementlimit) {
            //                Double score = idsMap.values().iterator().next();
            //                if (score >= 10) {
            break;
            //                }
        }

        if ((count % 2) == 0 && idsMap.size() >= 2 && count > difflimit) {
            ValueComparator bvc = new ValueComparator(idsMap);
            TreeMap<CharSequence, Double> sorted_map = new TreeMap(bvc);
            sorted_map.putAll(idsMap);
            Iterator<CharSequence> iter = sorted_map.keySet().iterator();
            Double first = idsMap.get(iter.next());
            Double second = idsMap.get(iter.next());

            persent = first / (first + second);
            if (persent > 0.65) {
                break;
            }
        }
        if (count > breaklimit) {
            break;
        }

        String clearNg = n.replaceAll("_", " ");
        if (clearNg == null) {
            continue;
        }
        if (clearNg.startsWith(" ")) {
            clearNg = clearNg.replaceFirst(" ", "");
        }
        if (clearNg.endsWith(" ")) {
            clearNg = clearNg.substring(0, clearNg.length() - 1);
        }

        Pair<Term, Double> termPair = null;
        try {
            termPair = babelNetDisambiguation(language, lemma, clearNg);
        } catch (Exception ex) {
            if (ex.getMessage() != null && ex.getMessage().contains("Your key is not valid")) {
                try {
                    termPair = babelNetDisambiguation(language, lemma, clearNg);
                } catch (Exception ex1) {
                    //                       LOGGER.log(Level.WARNING, ex1, null);
                }
            } else {
                LOGGER.log(Level.WARNING, null, ex);
            }
        }
        if (termPair != null) {
            termMap.put(termPair.first.getUid(), termPair.first);
            Double score;
            if (idsMap.containsKey(termPair.first.getUid())) {
                score = idsMap.get(termPair.first.getUid());
                //                    score++;
                score += termPair.second;
            } else {
                //                    score = 1.0;
                score = termPair.second;
            }
            idsMap.put(termPair.first.getUid(), score);
        }
    }
    if (!idsMap.isEmpty()) {
        ValueComparator bvc = new ValueComparator(idsMap);
        TreeMap<CharSequence, Double> sorted_map = new TreeMap(bvc);
        sorted_map.putAll(idsMap);
        count = 0;
        Double firstScore = idsMap.get(sorted_map.firstKey());
        terms.add(termMap.get(sorted_map.firstKey()));
        idsMap.remove(sorted_map.firstKey());
        for (CharSequence tvID : sorted_map.keySet()) {
            if (count >= 1) {
                Double secondScore = idsMap.get(tvID);
                persent = secondScore / (firstScore + secondScore);
                if (persent > 0.2) {
                    terms.add(termMap.get(tvID));
                }
                if (count >= 2) {
                    break;
                }
            }
            count++;
        }
        return terms;
    }
    return null;
}

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * This method handles the <code>request=logout</code> user request. <br>
 * <br>// w w w.  j  a  va  2  s .  c  o m
 * <b>Description:</b> <br>
 * The request can be used to logout a user by sending a saml logoutrequest. <br>
 * e.g. if the user sends a normal request=logout but actually was a saml user and should have send a samlrequest <br>
 * <br>
 * <b>Preconditions:</b> <br>
 * Valid TGT <br>
 * <br>
 * <b>Postconditions:</b> <br>
 * <br>
 * 
 * @param htServiceRequest
 *            HashMap containing request parameters
 * @param servletResponse
 *            Used to send (HTTP) information back to user
 * @param pwOut
 *            Used to write information back to the user (HTML)
 * @throws ASelectException
 */
private void handleSamlLogout(HashMap htServiceRequest, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse, PrintWriter pwOut) throws ASelectException {
    String sMethod = "handleSamlLogout";
    String sRemoteAsUrl = null;

    _systemLogger.log(Level.FINER, _sModule, sMethod, "handleSamlLogout");

    String sTgt = (String) htServiceRequest.get("aselect_credentials_tgt");

    if (_htTGTContext != null) { // must be true for samllogout
        LogoutRequestSender logoutRequestSender = new LogoutRequestSender();
        //            String sIssuer = (String)_htTGTContext.get("sp_issuer");
        String sIssuer = _sServerUrl; // set idp as issuer
        String sNameID = (String) _htTGTContext.get("name_id");
        String sAppId = (String) _htTGTContext.get("app_id");
        //  find a way to get the default, maybe from application section
        // If we allow this we must sanitize this url !!!
        String sLogoutReturnUrl = (String) htServiceRequest.get("logout_return_url");
        if (sLogoutReturnUrl != null) {
            _systemLogger.log(Level.FINER, _sModule, sMethod,
                    "Found logout_return_url in request: " + sLogoutReturnUrl);
            // For backward compatibility, avoid double decoding
            boolean doDecode = true; // backward compatibility
            HashMap<String, Vector<String>> parameters2decode = _configManager.getParameters2decode();
            if (parameters2decode != null && !parameters2decode.isEmpty()) {
                Vector<String> appl = parameters2decode.get("logout_return_url");
                if (Utils.hasValue(sAppId) && appl != null && appl.contains(sAppId)) { // already decoded
                    doDecode = false;
                    _systemLogger.log(Level.FINER, _sModule, sMethod, "logout_return_url already urldecoded");
                }
            }
            if (doDecode) {
                try {
                    sLogoutReturnUrl = URLDecoder.decode(sLogoutReturnUrl, "UTF-8");
                    _systemLogger.log(Level.FINER, _sModule, sMethod,
                            "logout_return_url after decoding: " + sLogoutReturnUrl);
                } catch (UnsupportedEncodingException e) {
                    _systemLogger.log(Level.WARNING, _sModule, sMethod,
                            "Unable to urldecode, unsupported encoding UTF-8");
                    throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
                }
            }
        }
        // We need to get the logout url from somewhere too
        String url = _sServerUrl + "/saml20_idp_slo_http_request";

        // 20120611, Bauke: added "usi"
        String sUsi = (String) _htTGTContext.get("usi");
        if (Utils.hasValue(sUsi)) // overwrite
            _timerSensor.setTimerSensorId(sUsi);
        if (Utils.hasValue(sAppId))
            _timerSensor.setTimerSensorAppId(sAppId);

        _systemLogger.log(Level.FINER, _sModule, sMethod, "Compose sendLogoutRequest to: " + url);

        logoutRequestSender.sendLogoutRequest(servletRequest, servletResponse, sTgt, url, sIssuer/* issuer */,
                sNameID, "urn:oasis:names:tc:SAML:2.0:logout:user", sLogoutReturnUrl, null, null);

        return;
    } else {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "No tgt found!");
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
    }
}