001 /*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
019 */
020 package org.sonar.batch;
021
022 import org.apache.commons.configuration.BaseConfiguration;
023
024 import org.sonar.api.database.DatabaseSession;
025 import org.sonar.api.database.configuration.Property;
026 import org.sonar.api.database.model.ResourceModel;
027
028 import java.util.List;
029
030 public class ResourceDatabaseConfiguration extends BaseConfiguration {
031 private final DatabaseSession session;
032 private Integer resourceId = null;
033
034 public ResourceDatabaseConfiguration(DatabaseSession session, ResourceModel resource) {
035 this.session = session;
036 if (resource != null) {
037 this.resourceId = resource.getId();
038 }
039 load();
040 }
041
042 public ResourceDatabaseConfiguration(DatabaseSession session, Integer resourceId) {
043 this.session = session;
044 this.resourceId = resourceId;
045 load();
046 }
047
048 public ResourceDatabaseConfiguration(DatabaseSession session, String resourceKey) {
049 this.session = session;
050
051 ResourceModel resource = session.getSingleResult(ResourceModel.class, "key", resourceKey);
052 if (resource != null) {
053 this.resourceId = resource.getId();
054 }
055 load();
056 }
057
058 public void load() {
059 clear();
060
061 loadResourceProperties();
062 }
063
064 private void loadResourceProperties() {
065 if (resourceId != null) {
066 List<Property> properties = session
067 .createQuery("from " + Property.class.getSimpleName() + " p where p.resourceId=:resourceId")
068 .setParameter("resourceId", resourceId)
069 .getResultList();
070
071 registerProperties(properties);
072 }
073 }
074
075 private void registerProperties(List<Property> properties) {
076 if (properties != null) {
077 for (Property property : properties) {
078 setProperty(property.getKey(), property.getValue());
079 }
080 }
081 }
082
083 }