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.apache.ranger.service.XResourceService.java

public List<VXPermMap> updatePermMaps(List<VXPermMap> vxPermMaps) {
    List<VXPermMap> updatedPermList = new ArrayList<VXPermMap>();

    List<Long> listOfUser = new ArrayList<Long>();
    List<Long> listOfGroup = new ArrayList<Long>();

    //[1] : Populate perm maps for user and groups
    for (VXPermMap vxPermMap : vxPermMaps) {
        if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
            if (!listOfUser.contains(vxPermMap.getUserId())) {
                listOfUser.add(vxPermMap.getUserId());
            }/*from   w  w w.j a v a 2 s  . c  om*/
        } else if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
            if (!listOfGroup.contains(vxPermMap.getGroupId())) {
                listOfGroup.add(vxPermMap.getGroupId());
            }
        }
    }

    HashMap<Long, HashMap<Integer, VXPermMap>> userPermMap = new HashMap<Long, HashMap<Integer, VXPermMap>>();

    for (Long userId : listOfUser) {
        HashMap<Integer, VXPermMap> userPerm = new HashMap<Integer, VXPermMap>();
        for (VXPermMap vxPermMap : vxPermMaps) {
            if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_USER && vxPermMap.getUserId() == userId) {
                userPerm.put(vxPermMap.getPermType(), vxPermMap);
            }
        }
        userPermMap.put(userId, userPerm);
    }

    //[2] :
    HashMap<Long, HashMap<Integer, VXPermMap>> groupPermMap = new HashMap<Long, HashMap<Integer, VXPermMap>>();

    for (Long groupId : listOfGroup) {
        HashMap<Integer, VXPermMap> groupPerm = new HashMap<Integer, VXPermMap>();
        for (VXPermMap vxPermMap : vxPermMaps) {
            Long permGroupId = vxPermMap.getGroupId();
            int permFor = vxPermMap.getPermFor();
            if (permFor == AppConstants.XA_PERM_FOR_GROUP && permGroupId.equals(groupId)) {
                groupPerm.put(vxPermMap.getPermType(), vxPermMap);
            }
        }
        groupPermMap.put(groupId, groupPerm);
    }

    for (Long userId : listOfUser) {
        HashMap<Integer, VXPermMap> map = userPermMap.get(userId);
        VXPermMap vxPermMap = null;
        if (!map.isEmpty()) {
            vxPermMap = map.values().iterator().next();
        }

        if (vxPermMap == null) {
            continue;
        }

        if (map.get(AppConstants.XA_PERM_TYPE_READ) == null) {
            vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_READ);
            map.put(AppConstants.XA_PERM_TYPE_READ, vxPermMap);
        }

        if (map.size() > 1 && map.get(AppConstants.XA_PERM_TYPE_EXECUTE) == null) {
            vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_EXECUTE);
            map.put(AppConstants.XA_PERM_TYPE_EXECUTE, vxPermMap);
        }
        userPermMap.put(userId, map);
    }

    for (Long groupId : listOfGroup) {
        HashMap<Integer, VXPermMap> map = groupPermMap.get(groupId);
        VXPermMap vxPermMap = null;
        if (!map.isEmpty()) {
            vxPermMap = map.values().iterator().next();
        }

        if (vxPermMap == null) {
            continue;
        }

        if (map.get(AppConstants.XA_PERM_TYPE_READ) == null) {
            vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_READ);
            map.put(AppConstants.XA_PERM_TYPE_READ, vxPermMap);
        }

        if (map.size() > 1 && map.get(AppConstants.XA_PERM_TYPE_EXECUTE) == null) {
            vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_EXECUTE);
            map.put(AppConstants.XA_PERM_TYPE_EXECUTE, vxPermMap);
        }
        groupPermMap.put(groupId, map);
    }

    // [3] :
    for (Entry<Long, HashMap<Integer, VXPermMap>> entry : userPermMap.entrySet()) {
        for (Entry<Integer, VXPermMap> innerEntry : entry.getValue().entrySet()) {
            updatedPermList.add(innerEntry.getValue());
        }
    }

    for (Entry<Long, HashMap<Integer, VXPermMap>> entry : groupPermMap.entrySet()) {
        for (Entry<Integer, VXPermMap> innerEntry : entry.getValue().entrySet()) {
            updatedPermList.add(innerEntry.getValue());
        }
    }

    return updatedPermList;
}

From source file:org.webdavaccess.LocalFileSystemStorage.java

/**
 * Delete properties for given resource// www .  j a v a 2  s .  c o  m
 * 
 * @param resourceUri for which to delete properties
 */
public void deleteProperties(String resourceUri, Properties propertiesToDelete) {
    resourceUri = normalize(resourceUri);
    // Try cache first
    Properties props = (Properties) mPropertiesCache.get(resourceUri);
    if (props != null)
        mPropertiesCache.remove(resourceUri);
    File file = getPropertiesFile(resourceUri);
    if (file == null || !file.exists()) {
        return;
    }
    InputStream in = null;
    Properties persisted = new Properties();
    try {
        in = new FileInputStream(file);
        persisted.loadFromXML(in);
    } catch (Exception e) {
        log.warn("Failed to get properties from cache for " + resourceUri);
        return;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
    }
    boolean changed = false;
    Enumeration en = persisted.keys();
    HashMap toRemove = new HashMap();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        if (isResourceProperty(resourceUri, key)) {
            if (propertiesToDelete != null) {
                String newKey = getPropertyKey(resourceUri, key);
                if (propertiesToDelete.getProperty(newKey) != null)
                    toRemove.put(key, persisted.getProperty(key));
            } else {
                toRemove.put(key, persisted.getProperty(key));
            }
        }
    }
    changed = !toRemove.isEmpty();
    for (Iterator it = toRemove.keySet().iterator(); it.hasNext();) {
        String key = (String) it.next();
        persisted.remove(key);
    }
    if (changed) {
        // Store the updates properties
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            persisted.storeToXML(os, "");
        } catch (Exception e) {
            log.warn("Failed to store properties for " + resourceUri);
        } finally {
            if (os != null)
                try {
                    os.close();
                } catch (Exception e) {
                }
        }
    }
}

From source file:com.frostwire.gui.components.slides.YouTubeStreamURLExtractor.java

public String getYoutubeStreamURL() throws Exception {
    this.possibleconverts = new HashMap<DestinationFormat, ArrayList<Info>>();
    String decryptedLink = null;/*  w  w w .  j a va  2s .  c o  m*/

    String param = youtubePageUrl;

    String parameter = param.toString().replace("watch#!v", "watch?v");
    parameter = parameter.replaceFirst("(verify_age\\?next_url=\\/?)", "");
    parameter = parameter.replaceFirst("(%3Fv%3D)", "?v=");
    parameter = parameter.replaceFirst("(watch\\?.*?v)", "watch?v");
    parameter = parameter.replaceFirst("/embed/", "/watch?v=");
    parameter = parameter.replaceFirst("https", "http");

    Browser br = new Browser();

    br.setFollowRedirects(true);
    br.setCookiesExclusive(true);
    br.clearCookies("youtube.com");

    if (parameter.contains("watch#")) {
        parameter = parameter.replace("watch#", "watch?");
    }
    if (parameter.contains("v/")) {
        String id = new Regex(parameter, "v/([a-z\\-_A-Z0-9]+)").getMatch(0);
        if (id != null)
            parameter = "http://www.youtube.com/watch?v=" + id;
    }

    boolean prem = false;

    try {
        final HashMap<Integer, String[]> LinksFound = this.getLinks(parameter, prem, br, 0);
        String error = br.getRegex(
                "<div id=\"unavailable\\-message\" class=\"\">[\t\n\r ]+<span class=\"yt\\-alert\\-vertical\\-trick\"></span>[\t\n\r ]+<div class=\"yt\\-alert\\-message\">([^<>\"]*?)</div>")
                .getMatch(0);
        if (error == null)
            error = br.getRegex("<div class=\"yt\\-alert\\-message\">(.*?)</div>").getMatch(0);
        if ((LinksFound == null || LinksFound.isEmpty()) && error != null) {
            //logger.info("Video unavailable: " + parameter);
            //logger.info("Reason: " + error.trim());
            return decryptedLink;
        }
        if (LinksFound == null || LinksFound.isEmpty()) {
            if (br.getURL().toLowerCase(Locale.getDefault()).indexOf("youtube.com/get_video_info?") != -1
                    && !prem) {
                throw new IOException("DecrypterException.ACCOUNT");
            }
            throw new IOException("Video no longer available");
        }

        /* First get the filename */
        String YT_FILENAME = "";
        if (LinksFound.containsKey(-1)) {
            YT_FILENAME = LinksFound.get(-1)[0];
            LinksFound.remove(-1);
        }

        final boolean fast = false;//cfg.getBooleanProperty("FAST_CHECK2", false);
        //final boolean mp3 = cfg.getBooleanProperty("ALLOW_MP3", true);
        final boolean mp4 = true;//cfg.getBooleanProperty("ALLOW_MP4", true);
        //final boolean webm = cfg.getBooleanProperty("ALLOW_WEBM", true);
        //final boolean flv = cfg.getBooleanProperty("ALLOW_FLV", true);
        //final boolean threegp = cfg.getBooleanProperty("ALLOW_3GP", true);

        /* http://en.wikipedia.org/wiki/YouTube */
        final HashMap<Integer, Object[]> ytVideo = new HashMap<Integer, Object[]>() {
            /**
             * 
             */
            private static final long serialVersionUID = -3028718522449785181L;

            {
                // **** FLV *****
                //                if (mp3) {
                //                    this.put(0, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Mono" });
                //                    this.put(5, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Stereo" });
                //                    this.put(6, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Mono" });
                //                }
                //                if (flv) {
                //                    this.put(34, new Object[] { DestinationFormat.VIDEOFLV, "H.264", "AAC", "Stereo" });
                //                    this.put(35, new Object[] { DestinationFormat.VIDEOFLV, "H.264", "AAC", "Stereo" });
                //                }

                // **** 3GP *****
                //                if (threegp) {
                //                    this.put(13, new Object[] { DestinationFormat.VIDEO3GP, "H.263", "AMR", "Mono" });
                //                    this.put(17, new Object[] { DestinationFormat.VIDEO3GP, "H.264", "AAC", "Stereo" });
                //                }
                // **** MP4 *****
                if (mp4) {
                    this.put(18, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
                    this.put(22, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
                    this.put(37, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
                    //this.put(38, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
                }
                // **** WebM *****
                //                if (webm) {
                //                    this.put(43, new Object[] { DestinationFormat.VIDEOWEBM, "VP8", "Vorbis", "Stereo" });
                //                    this.put(45, new Object[] { DestinationFormat.VIDEOWEBM, "VP8", "Vorbis", "Stereo" });
                //                }
            }
        };

        /* check for wished formats first */
        String dlLink = "";
        String vQuality = "";
        DestinationFormat cMode = null;

        for (final Integer format : LinksFound.keySet()) {
            if (ytVideo.containsKey(format)) {
                cMode = (DestinationFormat) ytVideo.get(format)[0];
                vQuality = "(" + LinksFound.get(format)[1] + "_" + ytVideo.get(format)[1] + "-"
                        + ytVideo.get(format)[2] + ")";
            } else {
                cMode = DestinationFormat.UNKNOWN;
                vQuality = "(" + LinksFound.get(format)[1] + "_" + format + ")";
                /*
                 * we do not want to download unknown formats at the
                 * moment
                 */
                continue;
            }
            dlLink = LinksFound.get(format)[0];
            try {
                if (fast) {
                    this.addtopos(cMode, dlLink, 0, vQuality, format);
                } else if (br.openGetConnection(dlLink).getResponseCode() == 200) {
                    this.addtopos(cMode, dlLink, br.getHttpConnection().getLongContentLength(), vQuality,
                            format);
                }
            } catch (final Throwable e) {
                LOG.error("Error in youtube decrypt logic", e);
            } finally {
                try {
                    br.getHttpConnection().disconnect();
                } catch (final Throwable e) {
                }
            }
        }

        int lastFmt = 0;
        for (final Entry<DestinationFormat, ArrayList<Info>> next : this.possibleconverts.entrySet()) {
            final DestinationFormat convertTo = next.getKey();
            for (final Info info : next.getValue()) {
                final HttpDownloadLink thislink = new HttpDownloadLink(info.link);
                //thislink.setBrowserUrl(parameter);
                //thislink.setFinalFileName(YT_FILENAME + info.desc + convertTo.getExtFirst());
                thislink.setSize(info.size);
                String name = null;
                if (convertTo != DestinationFormat.AUDIOMP3) {
                    name = YT_FILENAME + info.desc + convertTo.getExtFirst();
                    name = FileUtils.getValidFileName(name);
                    thislink.setFileName(name);
                } else {
                    /*
                     * because demuxer will fail when mp3 file already
                     * exists
                     */
                    //name = YT_FILENAME + info.desc + ".tmp";
                    //thislink.setProperty("name", name);
                }
                //thislink.setProperty("convertto", convertTo.name());
                //thislink.setProperty("videolink", parameter);
                //thislink.setProperty("valid", true);
                //thislink.setProperty("fmtNew", info.fmt);
                //thislink.setProperty("LINKDUPEID", name);

                if (lastFmt < info.fmt) {
                    decryptedLink = thislink.getUrl();
                }
            }
        }
    } catch (final IOException e) {
        br.getHttpConnection().disconnect();
        //logger.log(java.util.logging.Level.SEVERE, "Exception occurred", e);
        return null;
    }

    return decryptedLink;
}

From source file:swift.selenium.WebHelper.java

/**
 * This method reads and returns data from each cell of a provided worksheet
 * /*from  w  w  w  .j  ava  2 s  .co m*/
 * @param reqValue
 * @param reqSheet
 * @param rowIndex
 * @param inputHashTable
 * @return
 * @throws IOException
 */
@SuppressWarnings("null")
public static String getCellData(String reqValue, HSSFSheet reqSheet, int rowIndex,
        HashMap<String, Object> inputHashTable) throws IOException {
    HSSFCell reqCell = null;
    Object actualvalue = null;
    String req = "";
    DataFormatter fmt = new DataFormatter();

    if (inputHashTable.isEmpty() == true) {
        inputHashTable = getValueFromHashMap(reqSheet);
    }
    HSSFRow rowActual = reqSheet.getRow(rowIndex);
    if (inputHashTable.get(reqValue) == null) {

        TransactionMapping.report.setStrMessage("Column " + reqValue + " not Found. Please Check input Sheet");
        TransactionMapping.pauseFun("Column " + reqValue + " not Found. Please Check input Sheet");
    } else {
        actualvalue = inputHashTable.get(reqValue);//rowHeader.getCell(colIndex).toString();         
        if (actualvalue != null) {
            int colIndex = Integer.parseInt(actualvalue.toString());
            reqCell = rowActual.getCell(colIndex);
            //TM 27-04-2015: Updated the code for formula in cells
            if (reqCell == null) {
                System.out.println(reqValue + " is Null");
            } else {
                HSSFWorkbook wb = reqCell.getSheet().getWorkbook(); //TM-05/05/2015: Get workbook instance from the worksheet
                HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); //TM-05/05/2015: To refresh all the formulas in the worksheet
                FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

                CellValue cellValue = evaluator.evaluate(reqCell);
                int type = 0;
                if (cellValue != null) {
                    type = cellValue.getCellType();
                } else {
                    type = reqCell.getCellType();
                }

                switch (type) {
                case HSSFCell.CELL_TYPE_BLANK:
                    req = "";
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(reqCell)) {
                        SimpleDateFormat form = new SimpleDateFormat(
                                Automation.configHashMap.get("DATEFORMAT").toString());
                        req = form.format(reqCell.getDateCellValue());
                    } else
                        req = fmt.formatCellValue(reqCell, evaluator);
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    req = reqCell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    req = Boolean.toString(reqCell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_ERROR:
                    req = "error";
                    break;
                }
            }
        }

        else {
            req = reqCell.getStringCellValue();
            System.out.println("null");
        }
    }
    return req;
}

From source file:org.apache.axis2.engine.MessageContextSaveATest.java

private void showMcMap(HashMap map) {
    if ((map != null) && (!map.isEmpty())) {
        Iterator itList = map.keySet().iterator();

        while (itList.hasNext()) {
            String key = (String) itList.next();

            MessageContext value = (MessageContext) map.get(key);
            String valueID = null;

            if (value != null) {
                valueID = value.getMessageID();

                log.debug("MessageContextSaveATest: showMcMap:  Message context   ID[" + valueID
                        + "]   Key Label [" + key + "]");

            }/*from  w w w .j a  v  a2 s  . c  o m*/
        }
    } else {
        log.debug("MessageContextSaveATest: showMcMap:  No entries to display for message contexts table.");
    }
}

From source file:org.apache.axis2.engine.MessageContextSaveCTest.java

private void showMCTable(OperationContext oc) {
    if (oc == null) {
        return;/* w  ww  . java 2s . c o m*/
    }

    HashMap mcTable = oc.getMessageContexts();

    if ((mcTable == null) || (mcTable.isEmpty())) {
        return;
    }

    Iterator it = mcTable.keySet().iterator();

    while (it.hasNext()) {
        String key = (String) it.next();
        MessageContext mc = (MessageContext) mcTable.get(key);

        if (mc != null) {
            String id = mc.getMessageID();
            log.debug("message context table entry:   label [" + key + "]    message ID [" + id + "]    ");
        }
    }

}

From source file:UnitTest1.java

public static void testAddJar() throws IOException, DScabiException, ExecutionException, InterruptedException {

    String action = "dao = new Dao(@localhost@, @27017@, @MetaDB@);"
            + "dao.setTableName(@ComputeMetaDataTable@);"
            + "jsonQuery = @{ @@Status@@ : @@Available@@, @@ComputePort@@ : @@4568@@ }@;"
            + "jsonResult = dao.executeQuery(jsonQuery);" + "return jsonResult;";

    String action2 = "import test.TestNew;" + "t = new TestNew();"
            + "dao = new Dao(@localhost@, @27017@, @MetaDB@);" + "dao.setTableName(@ComputeMetaDataTable@);"
            + "jsonQuery = @{ @@Status@@ : @@Available@@, @@ComputePort@@ : @@4568@@ }@;"
            + "jsonResult = dao.executeQuery(jsonQuery);"
            + "return @Result1 : @ + t.compute(null) + @ Result2: @ + jsonResult;";

    DMeta meta = new DMeta("localhost", "5000");
    DComputeUnit cu2 = new DComputeUnit() {

        public String compute(Dson jsonInput) {
            //System.out.println("compute() Testing 2 in remote. I'm from CU class from CNS");
            return "Hello from this Compute Unit, CU #" + jsonInput.getCU();
        }/*  w  ww  . java2  s  .  c o m*/
    };
    long time1 = System.currentTimeMillis();
    //String primeresult = cu2.compute(Dson.dummyDson());
    //String primeresult = c.executeObject(cu2);
    DCompute c = new DCompute(meta);
    HashMap<String, String> out1 = new HashMap<String, String>();
    HashMap<String, String> out2 = new HashMap<String, String>();
    HashMap<String, String> out3 = new HashMap<String, String>();
    HashMap<String, String> out4 = new HashMap<String, String>();

    /*
    c.executeObject(cu2).input(Dson.empty()).split(2).output(out1);
       c.executeClass(CU.class).input(Dson.empty()).split(5).output(out2);
    //c.executeClass(cu2.getClass()).input(Dson.empty()).maxSplit(2).output(out).perform();
    c.executeCode(action).input(Dson.empty()).split(7).splitRange(2, 6).output(out3);
    c.executeClassNameInJar("/home/anees/self/test.jar", "TestNew").split(3).output(out4);
       c.perform();
    c.finish();
    */
    /*
     c.addJar("/home/anees/self/test.jar");
     c.executeClass(CU.class).input(Dson.empty()).split(5).output(out1);
    c.perform();
     c.finish();
            
     c.addJar("/home/anees/self/test.jar");
       c.executeObject(cu2).input(Dson.empty()).split(2).output(out2);
    c.perform();
     c.finish();
            
     c.addJar("/home/anees/self/test.jar");
     c.executeCode(action2).input(Dson.empty()).split(4).output(out3);
    c.perform();
     c.finish();
    */
    c.addJar("/home/anees/self/test.jar");
    c.executeJar("/home/anees/self/test.jar", "TestNew").split(3).output(out4);
    c.perform();
    c.finish();

    //try {Thread.currentThread().sleep(20000);}
    //catch (Exception e) { }

    if (out1.isEmpty())
        System.out.println("out1 is empty");
    Set<String> st1 = out1.keySet();
    for (String s : st1) {
        log.debug("out1 for s : {} value : {}", s, out1.get(s));
        //System.out.println("out1 s : " + s + " value : " + out1.get(s));
    }

    if (out2.isEmpty())
        System.out.println("out2 is empty");
    Set<String> st2 = out2.keySet();
    for (String s : st2) {
        log.debug("out2 for s : {} value : {}", s, out2.get(s));

    }

    if (out3.isEmpty())
        System.out.println("out3 is empty");
    Set<String> st3 = out3.keySet();
    for (String s : st3) {
        log.debug("out3 for s : {} value : {}", s, out3.get(s));

    }

    if (out4.isEmpty())
        System.out.println("out4 is empty");
    Set<String> st4 = out4.keySet();
    for (String s : st4) {
        log.debug("out4 for s : {} value : {}", s, out4.get(s));

    }
    long time2 = System.currentTimeMillis();
    //log.debug("prime number check result : {}", primeresult);

    //log.debug("Last prime number : {}", primeresult);
    log.debug("Time taken : {}", time2 - time1);
    System.out.println("Time taken : " + (time2 - time1));

    meta.close();
}

From source file:net.dahanne.gallery.g2.java.client.business.G2Client.java

public void loginToGallery(String galleryUrl, String user, String password) throws ImpossibleToLoginException {
    // we reset the last login
    sessionCookies.clear();/*w ww .  j a  v a 2s .  c  o  m*/
    sessionCookies.add(new BasicClientCookie("", ""));

    List<NameValuePair> sb = new ArrayList<NameValuePair>();
    sb.add(LOGIN_CMD_NAME_VALUE_PAIR);
    sb.add(new BasicNameValuePair("g2_form[uname]", "" + user));
    sb.add(new BasicNameValuePair("g2_form[password]", "" + password));
    HashMap<String, String> properties;
    try {
        properties = sendCommandToGallery(galleryUrl, sb, null);
    } catch (GalleryConnectionException e) {
        throw new ImpossibleToLoginException(e);
    }
    // auth_token retrieval, used by G2 against cross site forgery
    authToken = null;
    if (properties.get("status") != null) {
        if (properties.get("status").equals(GR_STAT_SUCCESS)) {
            authToken = properties.get("auth_token");
        } else {
            throw new ImpossibleToLoginException(properties.get("status_text"));
        }
    }
    //the login request did not return properties; issue #24 
    if (properties.isEmpty()) {
        throw new ImpossibleToLoginException(
                "The Gallery did not return login properties; check your gallery installation and/or your settings");
    }

}

From source file:org.lexevs.dao.database.ibatis.valuesets.IbatisPickListDao.java

@SuppressWarnings("unchecked")
@Override//from   w w w. j  a va  2  s .  c o m
public PickListDefinition resolvePickListByRevision(String pickListId, String revisionId, Integer sortType)
        throws LBRevisionException {

    String prefix = this.getPrefix();
    String tempRevId = revisionId;

    String pickListDefinitionUId = this.getPickListGuidFromPickListId(pickListId);

    if (pickListDefinitionUId == null) {
        throw new LBRevisionException("PickListDefinition " + pickListId + " doesn't exist in lexEVS. "
                + "Please check the pickListId. Its possible that the given pickListDefinition "
                + "has been REMOVEd from the lexEVS system in the past.");
    }

    String plDefRevisionId = this.getLatestRevision(pickListDefinitionUId);

    // 1. If 'revisionId' is null or 'revisionId' is the latest revision of the picklistDefinition
    // then use getPickListDefinitionById to get the pickListDefinition object and return.

    if (StringUtils.isEmpty(revisionId) || StringUtils.isEmpty(plDefRevisionId)
            || revisionId.equals(plDefRevisionId)) {
        return this.getPickListDefinitionById(pickListId);
    }

    // 2. Get the earliest revisionId on which change was applied on given 
    // pickList with reference to given revisionId.

    HashMap revisionIdMap = (HashMap) this.getSqlMapClientTemplate().queryForMap(
            GET_PREV_REV_ID_FROM_GIVEN_REV_ID_FOR_PLDEF_SQL,
            new PrefixedParameterTuple(prefix, pickListId, revisionId), "revId", "revAppliedDate");

    if (revisionIdMap.isEmpty()) {
        revisionId = null;
    } else {

        revisionId = (String) revisionIdMap.keySet().toArray()[0];

        if (plDefRevisionId.equals(revisionId)) {
            return this.getPickListDefinitionById(pickListId);
        }
    }

    // 3. Get the pick list definition data from history.
    PickListDefinition pickListDefinition = null;
    InsertPickListDefinitionBean plDefBean = null;

    plDefBean = (InsertPickListDefinitionBean) this.getSqlMapClientTemplate().queryForObject(
            GET_PICKLIST_DEFINITION_METADATA_FROM_HISTORY_BY_REVISION_SQL,
            new PrefixedParameterTuple(getPrefix(), pickListId, revisionId));

    if (plDefBean != null) {

        pickListDefinition = plDefBean.getPickListDefinition();

        // Get pick list definition source
        List<Source> sourceList = this.getSqlMapClientTemplate().queryForList(
                GET_SOURCE_LIST_FROM_HISTORY_BY_PARENT_ENTRYSTATEGUID_AND_TYPE_SQL, new PrefixedParameterTuple(
                        prefix, plDefBean.getEntryStateUId(), ReferenceType.PICKLISTDEFINITION.name()));

        if (sourceList != null)
            pickListDefinition.setSource(sourceList);

        // Get pick list definition context
        List<String> contextList = this.getSqlMapClientTemplate().queryForList(
                GET_CONTEXT_LIST_FROM_HISTORY_BY_PARENT_ENTRYSTATEGUID_AND_TYPE_SQL, new PrefixedParameterTuple(
                        prefix, plDefBean.getEntryStateUId(), ReferenceType.PICKLISTDEFINITION.name()));

        if (contextList != null)
            pickListDefinition.setDefaultPickContext(contextList);
    }

    // 4. If pick list is not in history, get it from base table.
    if (pickListDefinition == null) {
        pickListDefinition = (PickListDefinition) this.getSqlMapClientTemplate().queryForObject(
                GET_PICKLIST_DEFINITION_BY_PICKLISTID_SQL,
                new PrefixedParameterTuple(prefix, pickListId, revisionId));

        // Get pick list definition source
        List<Source> sourceList = this.getSqlMapClientTemplate()
                .queryForList(GET_SOURCE_LIST_BY_PARENT_GUID_AND_TYPE_SQL, new PrefixedParameterTuple(prefix,
                        pickListDefinitionUId, ReferenceType.PICKLISTDEFINITION.name()));

        if (sourceList != null)
            pickListDefinition.setSource(sourceList);

        // Get pick list definition context
        List<String> contextList = this.getSqlMapClientTemplate()
                .queryForList(GET_CONTEXT_LIST_BY_PARENT_GUID_AND_TYPE_SQL, new PrefixedParameterTuple(prefix,
                        pickListDefinitionUId, ReferenceType.PICKLISTDEFINITION.name()));

        if (contextList != null)
            pickListDefinition.setDefaultPickContext(contextList);
    }

    // 5. Get all pick list entry nodes.
    List<String> entryNodeList = this.getSqlMapClientTemplate().queryForList(
            GET_PL_ENTRY_NODES_LIST_BY_PICKLIST_ID_SQL, new PrefixedParameter(prefix, pickListId));

    for (String plEntryId : entryNodeList) {
        PickListEntryNode pickListEntryNode = null;

        try {
            pickListEntryNode = pickListEntryNodeDao.resolvePLEntryNodeByRevision(pickListId, plEntryId,
                    tempRevId);
        } catch (LBRevisionException e) {
            continue;
        }

        if (pickListEntryNode != null)
            pickListDefinition.addPickListEntryNode(pickListEntryNode);
    }

    // 6. Get all pick list definition properties.

    List<String> propertyList = this.getSqlMapClientTemplate().queryForList(
            GET_PICKLIST_DEF_PROPERTY_LIST_BY_PICKLIST_ID_SQL, new PrefixedParameter(prefix, pickListId));

    Properties properties = new Properties();

    for (String propId : propertyList) {
        Property prop = null;

        try {
            prop = vsPropertyDao.resolveVSPropertyByRevision(pickListDefinitionUId, propId, tempRevId);
        } catch (LBRevisionException e) {
            continue;
        }
        properties.addProperty(prop);
    }

    pickListDefinition.setProperties(properties);

    return pickListDefinition;
}

From source file:org.apache.ddlutils.alteration.ModelComparator.java

/**
 * Checks for changes in the column order between the given source and target table, creates change objects for these and
 * applies them to the given intermediate model.
 * /* ww  w  . java 2 s  . com*/
 * @param sourceModel       The source model
 * @param sourceTable       The source table
 * @param intermediateModel The intermediate model to apply the changes to
 * @param intermediateTable The table from the intermediate model corresponding to the source table
 * @param targetModel       The target model
 * @param targetTable       The target table
 * @return The changes
 */
protected List checkForChangeOfColumnOrder(Database sourceModel, Table sourceTable, Database intermediateModel,
        Table intermediateTable, Database targetModel, Table targetTable) {
    List changes = new ArrayList();
    List targetOrder = new ArrayList();
    int numChangedPKs = 0;

    for (int columnIdx = 0; columnIdx < targetTable.getColumnCount(); columnIdx++) {
        Column targetColumn = targetTable.getColumn(columnIdx);
        Column sourceColumn = intermediateTable.findColumn(targetColumn.getName(), _caseSensitive);

        if (sourceColumn != null) {
            targetOrder.add(sourceColumn);
        }
    }

    HashMap newPositions = new HashMap();

    for (int columnIdx = 0; columnIdx < intermediateTable.getColumnCount(); columnIdx++) {
        Column sourceColumn = intermediateTable.getColumn(columnIdx);
        int targetIdx = targetOrder.indexOf(sourceColumn);

        if ((targetIdx >= 0) && (targetIdx != columnIdx)) {
            newPositions.put(sourceColumn.getName(), new Integer(targetIdx));
            if (sourceColumn.isPrimaryKey()) {
                numChangedPKs++;
            }
        }
    }

    if (!newPositions.isEmpty()) {
        ColumnOrderChange change = new ColumnOrderChange(intermediateTable.getName(), newPositions);

        change.apply(intermediateModel, _caseSensitive);
        if (numChangedPKs > 1) {
            // create pk change that only covers the order change
            // fortunately, the order change will have adjusted the pk order already
            changes.add(new PrimaryKeyChange(intermediateTable.getName(), getIntermediateColumnNamesFor(
                    intermediateTable.getPrimaryKeyColumns(), intermediateTable)));
        }
        changes.add(change);
    }
    return changes;
}