Example usage for org.springframework.dao DataAccessResourceFailureException DataAccessResourceFailureException

List of usage examples for org.springframework.dao DataAccessResourceFailureException DataAccessResourceFailureException

Introduction

In this page you can find the example usage for org.springframework.dao DataAccessResourceFailureException DataAccessResourceFailureException.

Prototype

public DataAccessResourceFailureException(String msg, @Nullable Throwable cause) 

Source Link

Document

Constructor for DataAccessResourceFailureException.

Usage

From source file:com.ethlo.geodata.importer.file.FileIpLookupImporter.java

@Override
public long importData() throws IOException {
    final Map.Entry<Date, File> ipDataFile = super.fetchResource(DataType.IP, url);
    final AtomicInteger count = new AtomicInteger(0);

    final File csvFile = ipDataFile.getValue();
    final long total = IoUtils.lineCount(csvFile);
    final ProgressListener prg = new ProgressListener(
            l -> publish(new DataLoadedEvent(this, DataType.IP, Operation.IMPORT, l, total)));

    final IpLookupImporter ipLookupImporter = new IpLookupImporter(csvFile);

    final JsonFactory f = new JsonFactory();
    f.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
    f.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    final ObjectMapper mapper = new ObjectMapper(f);

    final byte newLine = (byte) "\n".charAt(0);

    logger.info("Writing IP data to file {}", getFile().getAbsolutePath());
    try (final OutputStream out = new BufferedOutputStream(new FileOutputStream(getFile()))) {
        ipLookupImporter.processFile(entry -> {
            final String strGeoNameId = findMapValue(entry, "geoname_id", "represented_country_geoname_id",
                    "registered_country_geoname_id");
            final String strGeoNameCountryId = findMapValue(entry, "represented_country_geoname_id",
                    "registered_country_geoname_id");
            final Long geonameId = strGeoNameId != null ? Long.parseLong(strGeoNameId) : null;
            final Long geonameCountryId = strGeoNameCountryId != null ? Long.parseLong(strGeoNameCountryId)
                    : null;//w w w .  j  ava2  s. co  m
            if (geonameId != null) {
                final SubnetUtils u = new SubnetUtils(entry.get("network"));
                final long lower = UnsignedInteger
                        .fromIntBits(InetAddresses
                                .coerceToInteger(InetAddresses.forString(u.getInfo().getLowAddress())))
                        .longValue();
                final long upper = UnsignedInteger
                        .fromIntBits(InetAddresses
                                .coerceToInteger(InetAddresses.forString(u.getInfo().getHighAddress())))
                        .longValue();
                final Map<String, Object> paramMap = new HashMap<>(5);
                paramMap.put("geoname_id", geonameId);
                paramMap.put("geoname_country_id", geonameCountryId);
                paramMap.put("first", lower);
                paramMap.put("last", upper);

                try {
                    mapper.writeValue(out, paramMap);
                    out.write(newLine);
                } catch (IOException exc) {
                    throw new DataAccessResourceFailureException(exc.getMessage(), exc);
                }
            }

            if (count.get() % 100_000 == 0) {
                logger.info("Processed {}", count.get());
            }

            count.getAndIncrement();

            prg.update();
        });
    }

    return total;
}

From source file:org.grails.datastore.mapping.cassandra.engine.CassandraEntityPersister.java

private SuperColumn getSuperColumn(Keyspace keyspace, String family, Serializable id) {
    ColumnParent parent = new ColumnParent();
    parent.setColumn_family(family);/*www.  j  a  v a  2 s.  c  om*/

    final List<SuperColumn> result;
    try {
        SlicePredicate predicate = new SlicePredicate();
        predicate.setSlice_range(new SliceRange(ZERO_LENGTH_BYTE_ARRAY, ZERO_LENGTH_BYTE_ARRAY, false, 1));
        result = keyspace.getSuperSlice(id.toString(), parent, predicate);
    } catch (HectorException e) {
        throw new DataAccessResourceFailureException("Exception occurred invoking Cassandra: " + e.getMessage(),
                e);
    }

    return !result.isEmpty() ? result.get(0) : null;
}

From source file:org.grails.datastore.mapping.redis.util.JedisTemplate.java

public List<Object> pipeline(final RedisCallback<RedisTemplate<Jedis, SortingParams>> pipeline) {
    return (List<Object>) execute(new RedisCallback<Jedis>() {
        public Object doInRedis(Jedis redis) throws IOException {
            if (isInMulti()) {
                // call directly if in a transaction
                return pipeline.doInRedis(JedisTemplate.this);
            }/*www .j a v a  2  s  .  co m*/

            return redis.pipelined(new PipelineBlock() {
                @Override
                public void execute() {
                    try {
                        JedisTemplate.this.pipeline = this;
                        pipeline.doInRedis(JedisTemplate.this);
                    } catch (IOException e) {
                        disconnect();
                        throw new DataAccessResourceFailureException(
                                "I/O exception thrown connecting to Redis: " + e.getMessage(), e);
                    } catch (RuntimeException e) {
                        disconnect();
                        throw e;
                    } finally {
                        JedisTemplate.this.pipeline = null;
                    }
                }
            });
        }
    });
}

From source file:org.dkpro.lab.engine.impl.DefaultTaskContext.java

@Deprecated
@Override//from w w  w.j ava  2  s.  c o  m
public File getStorageLocation(String aKey, AccessMode aMode) {
    StorageKey key;

    StorageService storage = getStorageService();
    Map<String, String> imports = getMetadata().getImports();

    if (storage.containsKey(getId(), aKey)) {
        // If the context contains the key, we do nothing. Locally available data always
        // supersedes imported data.
        key = new StorageKey(getId(), aKey);
    } else if (imports.containsKey(aKey)) {
        URI uri;
        try {
            uri = new URI(imports.get(aKey));
        } catch (URISyntaxException e) {
            throw new DataAccessResourceFailureException(
                    "Imported key [" + aKey + "] resolves to illegal URL [" + imports.get(aKey) + "]", e);
        }

        if ("file".equals(uri.getScheme()) && new File(uri).isDirectory()) {
            if (aMode == AccessMode.READONLY) {
                return new File(uri);
            } else {
                // Here we should probably just copy the imported folder into the context
                throw new DataAccessResourceFailureException(
                        "READWRITE access of imported " + "folders is not implemented yet.");
            }
        } else {
            key = resolve(aKey, aMode, true);
        }
    } else {
        key = resolve(aKey, aMode, true);
    }

    return getStorageService().getStorageFolder(key.contextId, key.key);
}

From source file:org.gageot.excel.core.ExcelTemplate.java

/**
 * Read the content of an Excel file for a given sheet name.
 * The content of the sheet is extracted using SheetExtractor.
 * @param sheetName name of the excel sheet
 * @param sheetExtractor object that will extract results
 * @return an arbitrary result object, as returned by the ResultSetExtractor
 * @throws DataAccessException if there is any problem
 *///from   w  ww  .j a v  a2  s .  co m
public <T> T read(final String sheetName, final SheetExtractor<T> sheetExtractor) throws DataAccessException {
    checkNotNull(sheetExtractor, "SheetExtractor must not be null");
    checkNotNull(sheetName, "sheetName must not be null");

    return read(new Function<HSSFWorkbook, T>() {
        @Override
        public T apply(HSSFWorkbook workbook) {
            HSSFSheet sheet = workbook.getSheet(sheetName);
            try {
                return sheetExtractor.extractData(sheet);
            } catch (IOException e) {
                throw new DataAccessResourceFailureException("Problem reading file", e);
            }
        }
    });
}

From source file:org.testng.spring.test.AbstractTransactionalDataSourceSpringContextTests.java

/**
 * Execute the given SQL script. Will be rolled back by default,
 * according to the fate of the current transaction.
 * @param sqlResourcePath Spring resource path for the SQL script.
 * Should normally be loaded by classpath. There should be one statement
 * per line. Any semicolons will be removed.
 * <b>Do not use this method to execute DDL if you expect rollback.</b>
 * @param continueOnError whether or not to continue without throwing
 * an exception in the event of an error
 * @throws DataAccessException if there is an error executing a statement
 * and continueOnError was false/*from  w  w w  .  jav  a  2  s .  co  m*/
 */
protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException {
    if (logger.isInfoEnabled()) {
        logger.info("Executing SQL script '" + sqlResourcePath + "'");
    }

    long startTime = System.currentTimeMillis();
    List statements = new LinkedList();
    Resource res = getApplicationContext().getResource(sqlResourcePath);
    try {
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(res.getInputStream()));
        String currentStatement = lnr.readLine();
        while (currentStatement != null) {
            currentStatement = StringUtils.replace(currentStatement, ";", "");
            statements.add(currentStatement);
            currentStatement = lnr.readLine();
        }

        for (Iterator itr = statements.iterator(); itr.hasNext();) {
            String statement = (String) itr.next();
            try {
                int rowsAffected = this.jdbcTemplate.update(statement);
                if (logger.isDebugEnabled()) {
                    logger.debug(rowsAffected + " rows affected by SQL: " + statement);
                }
            } catch (DataAccessException ex) {
                if (continueOnError) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("SQL: " + statement + " failed", ex);
                    }
                } else {
                    throw ex;
                }
            }
        }
        long elapsedTime = System.currentTimeMillis() - startTime;
        logger.info("Done executing SQL script '" + sqlResourcePath + "' in " + elapsedTime + " ms");
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Failed to open SQL script '" + sqlResourcePath + "'", ex);
    }
}

From source file:ru.adios.budgeter.BundleProvider.java

private static SingleConnectionDataSource createDataSource(String url) {
    final SingleConnectionDataSource dataSource = new SingleConnectionDataSource(url, true) {
        @Override//  w  ww.  ja  va 2  s.  com
        protected Connection getCloseSuppressingConnectionProxy(Connection target) {
            return new DelegatingConnectionProxy(target);
        }
    };
    dataSource.setAutoCommit(true);
    dataSource.setDriverClassName("org.sqldroid.SQLDroidDriver");
    try {
        dataSource.initConnection();
    } catch (SQLException ex) {
        throw new DataAccessResourceFailureException("Unable to initialize SingleConnectionDataSource", ex);
    }
    return dataSource;
}

From source file:org.gageot.excel.core.ExcelTemplate.java

private <T> T read(Function<HSSFWorkbook, T> transform) {
    checkNotNull(getResource(), "resource must not be null");

    InputStream in = null;/*from   w  ww  . j a v  a 2  s.c  om*/
    try {
        in = new BufferedInputStream(getResource().getInputStream());

        return transform.apply(new HSSFWorkbook(in, false));
    } catch (IOException e) {
        throw new DataAccessResourceFailureException("Problem reading file", e);
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                throw new CleanupFailureDataAccessException("Problem closing file", e);
            }
        }
    }
}

From source file:org.opennms.ng.dao.support.ResourceTypeUtils.java

/**
 * <p>getProperties</p>//  ww  w  . ja  va  2s  .  c  o m
 *
 * @param file a {@link java.io.File} object.
 * @return a {@link java.util.Properties} object.
 */
public static Properties getProperties(File file) {
    try {
        return s_cache.findProperties(file);
    } catch (IOException e) {
        String message = "loadProperties: Error opening properties file " + file.getAbsolutePath() + ": " + e;
        LOG.warn(message, e);
        throw new DataAccessResourceFailureException(message, e);
    }
}

From source file:com.jpeterson.littles3.dao.je.JeS3ObjectDao.java

public void storeS3Object(S3Object s3Object) throws DataAccessException {
    DatabaseEntry theKey;/*from   ww  w .j  av  a  2s  .co m*/
    DatabaseEntry theData;

    // store the object meta data

    // Environment myDbEnvironment = null;
    Database database = null;
    try {

        theKey = new DatabaseEntry();
        s3ObjectBucketKeyBinding.objectToEntry(s3Object, theKey);
        theData = new DatabaseEntry();
        fileS3ObjectBinding.objectToEntry(s3Object, theData);

        // TODO: generalize this
        /*
         * EnvironmentConfig envConfig = new EnvironmentConfig();
         * envConfig.setAllowCreate(true); myDbEnvironment = new
         * Environment(new File( "C:/temp/StorageEngine/db"), envConfig);
         * 
         * DatabaseConfig dbConfig = new DatabaseConfig();
         * dbConfig.setAllowCreate(true); database =
         * myDbEnvironment.openDatabase(null, "sampleDatabase", dbConfig);
         */

        database = jeCentral.getDatabase(JeCentral.OBJECT_DB_NAME);

        database.put(null, theKey, theData);
    } catch (DatabaseException e) {
        throw new DataAccessResourceFailureException("Unable to store a database record", e);
    } finally {
        /*
         * if (database != null) { try { database.close(); } catch
         * (DatabaseException e) { // do nothing } } database = null;
         * 
         * if (myDbEnvironment != null) { try { myDbEnvironment.close(); }
         * catch (DatabaseException e) { // do nothing } } myDbEnvironment =
         * null;
         */
    }
}