org.postgresql.util.PGobject Java Examples

The following examples show how to use org.postgresql.util.PGobject. 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: DatabaseWriter.java    From xyz-hub with Apache License 2.0 7 votes vote down vote up
protected static PGobject featureToPGobject(final Feature feature) throws SQLException {
    final Geometry geometry = feature.getGeometry();
    feature.setGeometry(null); // Do not serialize the geometry in the JSON object

    final String json;

    try {
        json = feature.serialize();
    } finally {
        feature.setGeometry(geometry);
    }

    final PGobject jsonbObject = new PGobject();
    jsonbObject.setType("jsonb");
    jsonbObject.setValue(json);
    return jsonbObject;
}
 
Example #2
Source File: PostgreSQLRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return Range.integerRange(value);
    } else if("int8range".equals(type)) {
        return Range.longRange(value);
    } else if("numrange".equals(type)) {
        return Range.bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example #3
Source File: PersistentEnumAsPostgreSQLEnum.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
public Object doNullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

	if (!HAS_POSTGRES_DRIVER) {
		return super.doNullSafeGet(rs, names, session, owner);
	}
	
    Object identifier = rs.getObject(names[0]);
    
    if (rs.wasNull()) {
        return null;
    }

    if (identifier instanceof PGobject) {
        PGobject pg = (PGobject) identifier;
        return getValueOfMethod().invoke(getMappedClass(), new Object[] { pg.getValue() });
    } else if (identifier instanceof String) { // some PostgreSQL Dialects / Versions return String not PGObject
        return getValueOfMethod().invoke(getMappedClass(), new Object[] { (String) identifier });
    } else {
        throw new IllegalArgumentException("PersistentEnum type expected PGobject, received " + identifier.getClass().getName() + " with value of '" + identifier + "'");
    }
}
 
Example #4
Source File: PersistentStringMapAsPostgreSQLJson.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
public void doNullSafeSet(PreparedStatement preparedStatement, Map<String, String> value, int index,
		SharedSessionContractImplementor session) throws SQLException {

	if (value == null) {
		preparedStatement.setNull(index, Types.NULL);
	} else {

		String identifier = toString(value);
		;

		PGobject jsonObject = new PGobject();
		jsonObject.setType("json");
		jsonObject.setValue(identifier);

		preparedStatement.setObject(index, jsonObject);
	}
}
 
Example #5
Source File: PersistentStringMapAsPostgreSQLJson.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> doNullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
		throws HibernateException, SQLException {

	Object identifier = rs.getObject(names[0]);

	if (rs.wasNull()) {
		return null;
	}

	final String jsonText;
	if (identifier instanceof PGobject) {
		PGobject pg = (PGobject) identifier;
		jsonText = pg.getValue();
	} else if (identifier instanceof String) { // some PostgreSQL Dialects /
												// Versions return String
												// not PGObject
		jsonText = (String) identifier;
	} else {
		throw new IllegalArgumentException("PersistentJsonObjectAsPostgreSQLJson type expected PGobject, received "
				+ identifier.getClass().getName() + " with value of '" + identifier + "'");
	}

	return toMap(jsonText);
}
 
Example #6
Source File: StringArrayType.java    From hibernate-postgresql with Apache License 2.0 6 votes vote down vote up
@Override
   public void nullSafeSet(PreparedStatement preparedStatement, Object value, int i, SharedSessionContractImplementor sessionImplementor) throws HibernateException, SQLException {
	String[] strings = (String[]) value;

	if (value == null) {
		preparedStatement.setNull(i, java.sql.Types.OTHER);
	} else {
		StringBuffer buffer = new StringBuffer();
		for (int j = 0; j < strings.length; j++) {
			buffer.append("\"" + strings[j] + "\"");
			if (j < strings.length - 1)
				buffer.append(",");
		}

		PGobject object = new PGobject();
		object.setValue("{" + buffer + "}");
		preparedStatement.setObject(i, object);
	}
}
 
Example #7
Source File: PostgreSQLAuthHandler.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean updateAuth(UUID uuid, String username, String accessToken) throws IOException {
    try (Connection c = postgreSQLHolder.getConnection();
         PreparedStatement s = c.prepareStatement(updateAuthSQL)) {
        s.setString(1, username); // Username case
        s.setString(2, accessToken);

        PGobject uuidObject = new PGobject();
        uuidObject.setType("uuid");
        uuidObject.setValue(uuid.toString());
        s.setObject(3, uuidObject);

        // Execute update
        s.setQueryTimeout(PostgreSQLSourceConfig.TIMEOUT);
        return s.executeUpdate() > 0;
    } catch (SQLException e) {
        throw new IOException(e);
    }
}
 
Example #8
Source File: PostgreSQLAuthHandler.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean updateServerID(UUID uuid, String serverID) throws IOException {
    try (Connection c = postgreSQLHolder.getConnection();
         PreparedStatement s = c.prepareStatement(updateServerIDSQL)) {
        s.setString(1, serverID);

        PGobject uuidObject = new PGobject();
        uuidObject.setType("uuid");
        uuidObject.setValue(uuid.toString());
        s.setObject(2, uuidObject);

        // Execute update
        s.setQueryTimeout(PostgreSQLSourceConfig.TIMEOUT);
        return s.executeUpdate() > 0;
    } catch (SQLException e) {
        throw new IOException(e);
    }
}
 
Example #9
Source File: PostgreSQLAuthHandler.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
private Entry query(String sql, UUID value) throws IOException {
    try (Connection c = postgreSQLHolder.getConnection();
         PreparedStatement s = c.prepareStatement(sql)) {
        PGobject uuidObject = new PGobject();
        uuidObject.setType("uuid");
        uuidObject.setValue(value.toString());

        s.setObject(1, uuidObject);

        // Execute query
        s.setQueryTimeout(PostgreSQLSourceConfig.TIMEOUT);
        try (ResultSet set = s.executeQuery()) {
            return constructEntry(set);
        }
    } catch (SQLException e) {
        throw new IOException(e);
    }
}
 
Example #10
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return integerRange(value);
    } else if("int8range".equals(type)) {
        return longRange(value);
    } else if("numrange".equals(type)) {
        return bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example #11
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return integerRange(value);
    } else if("int8range".equals(type)) {
        return longRange(value);
    } else if("numrange".equals(type)) {
        return bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example #12
Source File: PostgreSQLRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return Range.integerRange(value);
    } else if("int8range".equals(type)) {
        return Range.longRange(value);
    } else if("numrange".equals(type)) {
        return Range.bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example #13
Source File: PostgreSQLRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return Range.integerRange(value);
    } else if("int8range".equals(type)) {
        return Range.longRange(value);
    } else if("numrange".equals(type)) {
        return Range.bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example #14
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return integerRange(value);
    } else if("int8range".equals(type)) {
        return longRange(value);
    } else if("numrange".equals(type)) {
        return bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example #15
Source File: SqlRunner.java    From yawp with MIT License 5 votes vote down vote up
protected final PGobject createJsonObject(String json) {
    try {
        PGobject jsonObject = new PGobject();
        jsonObject.setType("jsonb");
        jsonObject.setValue(json);
        return jsonObject;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: PostgisDb.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void initSpatialMetadata( String options ) throws Exception {
    if (!wasInitialized) {
        Connection jdbcConnection = getJdbcConnection();

        if (jdbcConnection instanceof PGConnection) {
            // FIXME how to enter in pooled mode
            PGConnection pgconn = (PGConnection) jdbcConnection;
            pgconn.addDataType("geometry", (Class< ? extends PGobject>) Class.forName("org.postgis.PGgeometry"));
            pgconn.addDataType("box3d", (Class< ? extends PGobject>) Class.forName("org.postgis.PGbox3d"));
            pgconn.addDataType("box2d", (Class< ? extends PGobject>) Class.forName("org.postgis.PGbox2d"));
        }
        wasInitialized = true;
    }
}
 
Example #17
Source File: PersistentJsonObjectAsPostgreSQLJson.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
  public void doNullSafeSet(PreparedStatement preparedStatement, Object value, int index, SharedSessionContractImplementor session) throws SQLException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

  	if (value == null) {
	preparedStatement.setNull(index, Types.NULL);
} else {				
	
	try {
		String identifier = getObjectWriter().writeValueAsString(value);
		
		Object jsonObject;
		if (HAS_POSTGRES_DRIVER) {
		
        	PGobject pgObject = new PGobject();
        	pgObject.setType("json");
        	pgObject.setValue(identifier);
        	jsonObject = pgObject;
		} else {
			jsonObject = identifier;
		}
		
           preparedStatement.setObject(index, jsonObject);
	} catch (JsonProcessingException e) {
		throw new HibernateException("Problem writing JSON String: " + e.getMessage(), e);
	}
}
  }
 
Example #18
Source File: InetAddressType.java    From hibernate-postgresql with Apache License 2.0 5 votes vote down vote up
@Override
   public void nullSafeSet(PreparedStatement preparedStatement, Object value, int i, SharedSessionContractImplementor sessionImplementor) throws HibernateException, SQLException {
	if (value == null) {
		preparedStatement.setNull(i, java.sql.Types.OTHER);
	} else {
		PGobject object = new PGobject();
		object.setValue(((InetAddress) value).getHostAddress());
		object.setType("inet");
		preparedStatement.setObject(i, object);
	}
}
 
Example #19
Source File: JSONTypeHandler.java    From mmpt with MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
        String parameter, JdbcType jdbcType) throws SQLException {
    PGobject jsonObject = new PGobject();
    jsonObject.setType("json");
    jsonObject.setValue(parameter);
    ps.setObject(i, jsonObject);
}
 
Example #20
Source File: CockroachdbDialect.java    From sqlg with MIT License 5 votes vote down vote up
@Override
public void setJson(PreparedStatement preparedStatement, int parameterStartIndex, JsonNode json) {
    PGobject jsonObject = new PGobject();
    jsonObject.setType("jsonb");
    try {
        jsonObject.setValue(json.toString());
        preparedStatement.setObject(parameterStartIndex, jsonObject);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: DatastoreSqlRunner.java    From yawp with MIT License 5 votes vote down vote up
protected final Entity getEntity(ResultSet rs) throws SQLException {
    PGobject keyObject = (PGobject) rs.getObject("key");
    PGobject propertiesObject = (PGobject) rs.getObject("properties");

    Entity entity = new Entity(Key.deserialize(keyObject.getValue()));
    entity.deserializeProperties(propertiesObject.getValue());

    return entity;
}
 
Example #22
Source File: JsonBinaryPlainStringType.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object nullSafeGet( ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner ) throws HibernateException, SQLException
{
    final Object result = rs.getObject( names[0] );

    if ( !rs.wasNull() )
    {
        String content = null;

        if ( result instanceof String )
        {
            content = (String) result;
        }
        else if ( result instanceof PGobject )
        {
            content = ((PGobject) result).getValue();
        }

        // Other types currently ignored

        if ( content != null )
        {
            return content.toString();
        }
    }

    return null;
}
 
Example #23
Source File: PostgresqlDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void storeGrade(PreparedStatement pst, int position, Grading grd) throws SQLException {
	PGobject jsonObject = new PGobject();
	jsonObject.setType("json");
	jsonObject.setValue(serialiser.toJsonElement(grd).toString());
	pst.setObject(position, jsonObject);
}
 
Example #24
Source File: PostgresqlDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void storeCard(PreparedStatement pst, int position, MagicCard mc) throws SQLException {
	
	PGobject jsonObject = new PGobject();
	jsonObject.setType("json");
	jsonObject.setValue(serialiser.toJsonElement(mc).toString());
	pst.setObject(position, jsonObject);
}
 
Example #25
Source File: PostgreSQLDialect.java    From dalesbred with MIT License 5 votes vote down vote up
private @NotNull Object createPgObject(@NotNull String value, @NotNull String typeName) {
    try {
        PGobject object = new PGobject();
        object.setType(typeName);
        object.setValue(value);
        return object;
    } catch (SQLException e) {
        throw convertException(e);
    }
}
 
Example #26
Source File: V2_35_2__Update_data_sync_job_parameters_with_system_setting_value.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void updateJobParamaters( final Context context, int dataValuesPageSize )
    throws JsonProcessingException, SQLException
{
    if ( dataValuesPageSize > 0 )
    {
        Map<Integer, JobParameters> updatedJobParameters = new HashMap<>();

        String sql = "SELECT jobconfigurationid, jsonbjobparameters FROM jobconfiguration " +
            "WHERE jobtype = '" + JobType.DATA_SYNC.name() + "';";
        try ( Statement stmt = context.getConnection().createStatement();
              ResultSet rs = stmt.executeQuery( sql ); )
        {
            while ( rs.next())
            {
                DataSynchronizationJobParameters jobparams = reader
                    .readValue( rs.getString( "jsonbjobparameters" ) );
                jobparams.setPageSize( dataValuesPageSize );

                updatedJobParameters.put( rs.getInt( "jobconfigurationid" ), jobparams );
            }
        }

        for ( Map.Entry<Integer, JobParameters> jobParams : updatedJobParameters.entrySet() )
        {
            try ( PreparedStatement ps = context.getConnection()
                .prepareStatement( "UPDATE jobconfiguration SET jsonbjobparameters = ? where  jobconfigurationid = ?;" ) )
            {
                PGobject pg = new PGobject();
                pg.setType( "jsonb" );
                pg.setValue( writer.writeValueAsString( jobParams.getValue() ) );

                ps.setObject( 1, pg );
                ps.setInt( 2, jobParams.getKey() );

                ps.execute();
            }
        }
    }
}
 
Example #27
Source File: JsonBinaryType.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void nullSafeSet( PreparedStatement ps, Object value, int idx, SharedSessionContractImplementor session ) throws HibernateException, SQLException
{
    if ( value == null )
    {
        ps.setObject( idx, null );
        return;
    }

    PGobject pg = new PGobject();
    pg.setType( "jsonb" );
    pg.setValue( convertObjectToJson( value ) );

    ps.setObject( idx, pg );
}
 
Example #28
Source File: JsonBinaryType.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object nullSafeGet( ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner ) throws HibernateException, SQLException
{
    final Object result = rs.getObject( names[0] );

    if ( !rs.wasNull() )
    {
        String content = null;

        if ( result instanceof String )
        {
            content = (String) result;
        }
        else if ( result instanceof PGobject )
        {
            content = ((PGobject) result).getValue();
        }

        // Other types currently ignored

        if ( content != null )
        {
            return convertJsonToObject( content );
        }
    }

    return null;
}
 
Example #29
Source File: JsonBinaryPlainStringType.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void nullSafeSet( PreparedStatement ps, Object value, int idx, SharedSessionContractImplementor session ) throws HibernateException, SQLException
{
    if ( value == null )
    {
        ps.setObject( idx, null );
        return;
    }

    PGobject pg = new PGobject();
    pg.setType( "jsonb" );
    pg.setValue( value.toString() );

    ps.setObject( idx, pg );
}
 
Example #30
Source File: PostgreSqlClient.java    From presto with Apache License 2.0 5 votes vote down vote up
private static SliceWriteFunction typedVarcharWriteFunction(String jdbcTypeName)
{
    return (statement, index, value) -> {
        PGobject pgObject = new PGobject();
        pgObject.setType(jdbcTypeName);
        pgObject.setValue(value.toStringUtf8());
        statement.setObject(index, pgObject);
    };
}