SQL conflict with mysql(MariaDB) in Gaia Environment - mysql

I am a bit confused with my situation as i am new to Gaia environment.
The situation is,
I have 2 databases one is Oracle(External Database) and another is Mysql in Mariadb platform. The ultimate goal is to transfer the data from Oracle to MariaDB through Springboot application.
I have a Issue now, I am able to get through Connections through GaiaConfig file,
package com.jpmc.pulsar.config;
#Configuration
#Profile({"gaia"})
public class GaiaConfig {
#Autowired
private Environment env;
private static final Logger LOG = LoggerFactory.getLogger(GaiaConfig.class);
#Autowired
private DataSource oracleDataSource;
#Autowired
private DataSource mysqlDataSource;
#Bean
public Cloud cloud() {
return new CloudFactory().getCloud();
}
#Bean(name = "oracleDb")
public DataSource oracleDataSource(final Cloud cloud) {
return createDataSource("external-database", cloud);
}
#Bean(name = "oracleJdbcTemplate")
public JdbcTemplate oracleJdbcTemplate() {
return new JdbcTemplate(oracleDataSource);
}
private DataSource createDataSource(final String serviceName, final Cloud cloud) {
final ExternalDependency externalDependency = cloud
.getServiceConnector(serviceName, ExternalDependency.class, null);
if (externalDependency == null) {
throw new InvalidConfigurationException(
String.format("Error getting ServiceConnector for External Dependency with serviceName=[%s]", serviceName)
);
}
HikariDataSource dataSource = null;
try {
final HikariConfig config = new HikariConfig();
config.setDriverClassName(requiredStringProperty("driverClassName", externalDependency, serviceName));
config.setJdbcUrl(requiredStringProperty("jdbcUrl", externalDependency, serviceName));
config.setUsername(requiredStringProperty("username", externalDependency, serviceName));
config.setPassword(requiredStringProperty("password", externalDependency, serviceName));
config.setConnectionTestQuery(requiredStringProperty("connectionTestQuery", externalDependency, serviceName));
config.setMinimumIdle(intProperty("minimumIdle", externalDependency, serviceName, 1));
config.setMaximumPoolSize(intProperty("maximumPoolSize", externalDependency, serviceName, 5));
dataSource = new HikariDataSource(config);
String dataSourceDetails = dataSourceDetails(dataSource);
LOG.info("Available DataSource: [{}]", dataSourceDetails);
} catch (Exception e) {
LOG.info("{}", e);
}
return dataSource;
}
private String dataSourceDetails(final HikariDataSource dataSource) {
final StringBuilder sb = new StringBuilder();
sb.append("driverClassName=[").append(dataSource.getDriverClassName()).append("],");
sb.append("jdbcUrl=[").append(dataSource.getJdbcUrl()).append("],");
sb.append("username=[").append(dataSource.getUsername()).append("],");
sb.append("connectionTestQuery=[").append(dataSource.getConnectionTestQuery()).append("],");
sb.append("validationTimeout=[").append(dataSource.getValidationTimeout()).append("],");
sb.append("maximumPoolSize=[").append(dataSource.getMaximumPoolSize()).append("],");
sb.append("minimumIdle=[").append(dataSource.getMinimumIdle()).append("],");
sb.append("connectionTimeout=[").append(dataSource.getConnectionTimeout()).append("],");
sb.append("connectionInitSql=[").append(dataSource.getConnectionInitSql()).append("],");
sb.append("maxLifetime=[").append(dataSource.getMaxLifetime()).append("]");
return sb.toString();
}
private Boolean booleanProperty(final String propertyName, final ExternalDependency externalDependency) {
final String value = externalDependency.getCredential(propertyName);
if (value != null) {
return Boolean.parseBoolean(value);
}
return Boolean.FALSE;
}
private Integer intProperty(final String propertyName, final ExternalDependency externalDependency,
String serviceName, final int defaultValue) {
final String value = externalDependency.getCredential(propertyName);
if (value != null) {
try {
return Integer.valueOf(value);
} catch (NumberFormatException ex) {
throw new InvalidConfigurationException(
String.format("Property [%s] is not a valid int in External Dependency with serviceId=[%s]",
propertyName, serviceName), ex);
}
}
return defaultValue;
}
private String requiredStringProperty(final String propertyName, final ExternalDependency externalDependency,
String serviceName) {
final String value = stringProperty(propertyName, externalDependency);
if (value == null || value.trim().length() == 0) {
throw new InvalidConfigurationException(
String.format("No property [%s] defined as part of External Dependency with serviceId=[%s]",
propertyName, serviceName));
} else {
return value;
}
}
private String stringProperty(final String propertyName, final ExternalDependency externalDependency) {
return externalDependency.getCredential(propertyName);
}
//MySQL Bean and jdbcTemplate Working Fine
#Primary
#Bean(name = "mysqlDb")
public DataSource mysqlDataSource(final Cloud cloud) {
final String serviceId = "bsc-mariadb";
// https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html
final Properties mysqlProperties = new Properties();
mysqlProperties.setProperty("cachePrepStmts", "true");
mysqlProperties.setProperty("prepStmtCacheSize", "250");
mysqlProperties.setProperty("prepStmtCacheSqlLimit", "2048");
mysqlProperties.setProperty("useServerPrepStmts", "true");
mysqlProperties.setProperty("useLegacyDatetimeCode", "false");
mysqlProperties.setProperty("serverTimezone", "UTC");
mysqlProperties.setProperty("connectionCollation", "utf8mb4_unicode_ci");
// https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby
final Map<String, Object> poolProperties = new HashMap<>();
poolProperties.put("poolName", serviceId + "-pool");
poolProperties.put("maximumPoolSize", 10);
poolProperties.put("maxLifetime", Duration.ofMinutes(5).toMillis());
poolProperties.put("connectionInitSql", "SET character_set_client = utf8mb4;");
poolProperties.put("dataSourceProperties", mysqlProperties);
final DataSourceConfig serviceConfig = new DataSourceConfig(poolProperties);
final DataSource dataSource = cloud.getServiceConnector(serviceId, DataSource.class, serviceConfig);
LOG.info("Available DataSource: [{}]", dataSource);
return dataSource;
}
#Bean(name = "mysqlJdbcTemplate")
public JdbcTemplate jdbcTemplate(#Qualifier("mysqlDb") DataSource dsMySQL) {
return new JdbcTemplate(dsMySQL);
}
}
and My Repository class looks like this,
#Autowired
private JdbcTemplate mysqlJdbcTemplate;
#Autowired
private JdbcTemplate oracleJdbcTemplate;
private String tableName = "BSC_INCIDENT_STG";
private String sql = "INSERT INTO `BSC_INCIDENT_STG`(`INCIDENT_NUMBER`,`APPLICATION_ID`,`CATEGORY`,`OPEN_TIME`,`SEVERITY_CODE`,`ASSIGNMENT`,`STATUS`,`CLOSE_TIME`,`ELAPSED_TIME`,`RESOLUTION_CODE`,`TYPE`,`OPEN_GROUP`,`RESOLVED_GROUP`,`RESOLVED_TIME`,`USER_PRIORITY`,`JP_ACCT_LOB`,`JP_ACCT_APP_RTO`,`JP_IMPACT`,`JP_IMPACT_DURATION_MIN`,`JP_OUTAGE_DURATION_MIN`,`JP_TTR_D1`,`JP_TTR_D2`,`JP_TTR_R1`,`JP_TTR_R2`,`JP_TTR_D2R2`,`LOGICAL_NAME`,`JP_EXTERNAL_ID`,`JP_EXTERNAL_SYSTEM`,`JP_CONFIG_ITEM`,`JP_MASTER_HOST`,`JP_SITE`,`JP_APPSERVICE_NAME`,`JP_APPSERVICE_ID`,`JP_VERUMIDENTIFIER`)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
public boolean truncateAndLoad(final List<Incident> incidentList) {
mysqlJdbcTemplate.execute("TRUNCATE BSC_INCIDENT_STG");
mysqlJdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, incidentList.get(i).getIncidentNumber());
ps.setString(2, incidentList.get(i).getApplicationId());
ps.setString(3, incidentList.get(i).getCategory());
ps.setString(4, incidentList.get(i).getOpenTime());
ps.setString(5, incidentList.get(i).getSeverityCode());
ps.setString(6, incidentList.get(i).getAssignment());
ps.setString(7, incidentList.get(i).getStatus());
ps.setString(8, incidentList.get(i).getCloseTime());
ps.setString(9, incidentList.get(i).getElapsedTime());
ps.setString(10, incidentList.get(i).getResolutionCode());
ps.setString(11, incidentList.get(i).getType());
ps.setString(12, incidentList.get(i).getOpenGroup());
ps.setString(13, incidentList.get(i).getResolvedGroup());
ps.setString(14, incidentList.get(i).getResolvedTime());
ps.setString(15, incidentList.get(i).getUserPriority());
ps.setString(16, incidentList.get(i).getJpAcctLob());
ps.setString(17, incidentList.get(i).getJpAcctAppRto());
ps.setString(18, incidentList.get(i).getJpImpact());
ps.setString(19, incidentList.get(i).getJpImpactDurationMin());
ps.setString(20, incidentList.get(i).getJpOutageDurationMin());
ps.setString(21, incidentList.get(i).getJpTtrD1());
ps.setString(22, incidentList.get(i).getJpTtrD2());
ps.setString(23, incidentList.get(i).getJpTtrR1());
ps.setString(24, incidentList.get(i).getJpTtrR2());
ps.setString(25, incidentList.get(i).getJpTtrD2R2());
ps.setString(26, incidentList.get(i).getLogicalName());
ps.setString(27, incidentList.get(i).getJpExternalId());
ps.setString(28, incidentList.get(i).getJpExternalSystem());
ps.setString(29, incidentList.get(i).getJpConfigItem());
ps.setString(30, incidentList.get(i).getJpMasterHost());
ps.setString(31, incidentList.get(i).getJpSite());
ps.setString(32, incidentList.get(i).getJpAppserviceName());
ps.setString(33, incidentList.get(i).getJpAppserviceId());
ps.setString(34, incidentList.get(i).getJpVerumidentifier());
}
#Override
public int getBatchSize() {
return incidentList.size();
}
});
return true;
}
public String getTableName() {
return tableName;
}
public List<Incident> listAll() {
String cprSql = "SELECT a.NUMBERPRGN as INCIDENT_NUMBER,"
+ "a.JP_ACCT_APP_APPID as APPLICATION_ID,"
+ "a.CATEGORY,"
+ "to_char(a.OPEN_TIME_EST,'DD-MON-YYYY hh24:mi:ss') OPEN_TIME,"
+ "a.SEVERITY_CODE,"
+ "a.ASSIGNMENT,"
+ "a.STATUS,"
+ "to_char(a.CLOSE_TIME_EST,'DD-MON-YYYY hh24:mi:ss') CLOSE_TIME,"
+ "to_char(a.ELAPSED_TIME,'DD-MON-YYYY hh24:mi:ss') ELAPSED_TIME,"
+ "a.RESOLUTION_CODE,"
+ "a.TYPE,"
+ "a.OPEN_GROUP,"
+ "a.RESOLVED_GROUP,"
+ "to_char(a.RESOLVED_TIME,'DD-MON-YYYY hh24:mi:ss') RESOLVED_TIME,"
+ "a.USER_PRIORITY,"
+ "a.JP_ACCT_LOB,"
+ "a.JP_ACCT_APP_RTO,"
+ "a.JP_IMPACT,"
+ "a.jp_impact_duration_min,"
+ "a.JP_OUTAGE_DURATION_MIN,"
+ "a.JP_TTR_D1,"
+ "a.JP_TTR_D2,"
+ "a.JP_TTR_R1,"
+ "a.JP_TTR_R2,"
+ "a.JP_TTR_D2R2,"
+ "a.LOGICAL_NAME,"
+ "b.JP_EXTERNAL_ID,"
+ "b.JP_EXTERNAL_SYSTEM,"
+ "b.JP_CONFIG_ITEM,"
+ "b.JP_MASTER_HOST,"
+ "b.JP_SITE,"
+ "b.JP_APPSERVICE_NAME,"
+ "b.JP_APPSERVICE_ID,"
+ "b.JP_VERUMIDENTIFIER "
+ "FROM SCUSER.PROBSUMMARYM1 a LEFT JOIN SCUSER.DEVICEM1 b ON (DECODE(a.LOGICAL_NAME,b.LOGICAL_NAME,1,0)=1) "
+ "where a.SEVERITY_CODE IN ('P1/S1','P1/S2','P1/S3') "
+ "and a.CPR_BUSINESS_OPERATIONS = 'f' "
+ "and a.ASSIGNMENT like 'X%' "
+ "and (TRUNC(OPEN_TIME_EST) >=TRUNC(SYSDATE-30) OR TRUNC(CLOSE_TIME_EST) >=TRUNC(SYSDATE-30)) and (a.JP_CONFIDENTIAL IS NULL OR a.JP_CONFIDENTIAL= 'f')";
logger.info(cprSql);
return oracleJdbcTemplate.query(cprSql, new IncidentMapper());
The issue is when i am running these files in local i am able to get the data from oracle to mysql(MariaDB) but when i deploy the same in cloud(Gaia) I am getting a conflict. The Conflict is that the cprSql query in Repository class is connecting to mysql in gaia environment.
Below is the issue when i access the url
Mon Oct 15 12:21:49 UTC 2018
There was an unexpected error (type=Internal Server Error, status=500).
StatementCallback; bad SQL grammar [
SELECT a.NUMBERPRGN as INCIDENT_NUMBER,a.JP_ACCT_APP_APPID as APPLICATION_ID,
a.CATEGORY,to_char(a.OPEN_TIME_EST,'DD-MON-YYYY hh24:mi:ss') OPEN_TIME,
a.SEVERITY_CODE,a.ASSIGNMENT,a.STATUS,
to_char(a.CLOSE_TIME_EST, 'DD-MON-YYYY hh24:mi:ss') CLOSE_TIME,
to_char(a.ELAPSED_TIME, 'DD-MON-YYYY hh24:mi:ss') ELAPSED_TIME,
a.RESOLUTION_CODE, a.TYPE,a.OPEN_GROUP,a.RESOLVED_GROUP,
to_char(a.RESOLVED_TIME, 'DD-MON-YYYY hh24:mi:ss') RESOLVED_TIME,
a.USER_PRIORITY, a.JP_ACCT_LOB,a.JP_ACCT_APP_RTO,a.JP_IMPACT,
a.jp_impact_duration_min, a.JP_OUTAGE_DURATION_MIN,a.JP_TTR_D1,
a.JP_TTR_D2,a.JP_TTR_R1, a.JP_TTR_R2,a.JP_TTR_D2R2,a.LOGICAL_NAME,
b.JP_EXTERNAL_ID, b.JP_EXTERNAL_SYSTEM,b.JP_CONFIG_ITEM,b.JP_MASTER_HOST,
b.JP_SITE,b.JP_APPSERVICE_NAME,b.JP_APPSERVICE_ID,b.JP_VERUMIDENTIFIER
FROM SCUSER.PROBSUMMARYM1 a
LEFT JOIN SCUSER.DEVICEM1 b ON (DECODE(a.LOGICAL_NAME,b.LOGICAL_NAME,
1,0)=1
)
where a.SEVERITY_CODE IN ('P1/S1','P1/S2','P1/S3')
and a.CPR_BUSINESS_OPERATIONS = 'f'
and a.ASSIGNMENT like 'X%'
and (TRUNC(OPEN_TIME_EST) >=TRUNC(SYSDATE-30)
OR TRUNC(CLOSE_TIME_EST) >=TRUNC(SYSDATE-30)
)
and (a.JP_CONFIDENTIAL IS NULL
OR a.JP_CONFIDENTIAL= 'f'
)
]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Incorrect parameter count in the call to native function 'DECODE'
Could someone please help ..I am stuck with this from morning!!..

Related

trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc

NetworkUtilities.java
public class NetworkUtilities {
private static final String TAG = NetworkUtilities.class.getSimpleName();
public static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
}catch (MalformedURLException e){
Log.v(TAG, "Problem building the Url");
}
return url;
}
public static String httpRequest(URL url) throws IOException{
String jsonResponse = "";
if(url ==null){
Log.v(TAG, "Url is null");
return jsonResponse;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200){
inputStream = httpURLConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
else{
Log.e(TAG, "Error response code" + httpURLConnection.getResponseCode());
}
}catch (IOException e){
Log.v(TAG, "Problem retrieving the json result", e);
}finally {
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
if(inputStream != null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader in = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bf = new BufferedReader(in);
String line = bf.readLine();
while(line != null){
output.append(line);
line = bf.readLine();
}
}
return output.toString();
}
public static List<String> extractFromJson(String jsonResponse){
if(TextUtils.isEmpty(jsonResponse)){
return null;
}
List<String> newsStories = new ArrayList<>();
try{
JSONObject baseObj = new JSONObject(jsonResponse);
JSONArray articlesArray = baseObj.getJSONArray("data");
for(int i=0;i<articlesArray.length();i++){
JSONObject currentArticle = articlesArray.getJSONObject(i);
JSONObject source = currentArticle.getJSONObject("source");
String sourceName = source.getString("name");
String title = currentArticle.getString("title");
String description = currentArticle.getString("description");
String newsStory = "Source" + sourceName + "/n" + title + "/n" + description;
newsStories.add(newsStory);
}
}catch (JSONException e){
Log.e(TAG, " Problem parsing the json string", e);
}
return newsStories;
}
NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context mContext;
private List<String> mNewsArticles;
NewsAdapter(Context context){
mContext = context;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(mContext)
.inflate(R.layout.news_list_item,parent, false);
view.setFocusable(true);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder( NewsViewHolder holder, int position) {
String currentArticle = mNewsArticles.get(position);
holder.mTextView.setText(currentArticle);
}
#Override
public int getItemCount() {
if(mNewsArticles != null){
return mNewsArticles.size();
}
return 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position :" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
}
public void setNewsData(List<String> newsData){
mNewsArticles = newsData;
notifyDataSetChanged();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private NewsAdapter mNewsAdapter;
private static final String BASE_URL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=13f428d687714c33a24f34ad6c5***87";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
mNewsAdapter = new NewsAdapter(this);
mRecyclerView.setAdapter(mNewsAdapter);
new FetchNewsArticle().execute(BASE_URL);
}
public class FetchNewsArticle extends AsyncTask<String, Void, List<String>>{
#Override
protected List<String> doInBackground(String... strings) {
String stringUrl = strings[0];
URL url = NetworkUtilities.createUrl(stringUrl);
String json = "";
try{
json = NetworkUtilities.httpRequest(url);
List<String> articles = NetworkUtilities.extractFromJson(json);
return articles;
}catch (Exception e){
e.printStackTrace();
Log.v(TAG, "Problem retrieving data");
return null;
}
}
#Override
protected void onPostExecute(List<String> strings) {
if(strings != null){
mNewsAdapter.setNewsData(strings);
}
}
}
Error
W/Zygote: Unable to open libbeluga.so: dlopen failed: library "libbeluga.so" not found.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/xample.newsfee: Accessing hidden method Landroid/view/View; >computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.newsfee: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
com.example.newsfeed V/NetworkUtilities: Problem retrieving the json result
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:46)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
2021-03-11 22:53:28.124 9391-9391/com.example.newsfeed W/Looper: PerfMonitor looperActivity : package=com.example.newsfeed/.MainActivity time=1ms latency=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running=212ms runnable=80ms io=11ms late=91ms h=android.app.ActivityThread$H w=159)
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM build : 979eaa0, I11632bc865
Build Date : 11/18/20
OpenGL ES Shader Compiler Version: EV031.32.02.00
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R1.11.00.00.604.067
Remote Branch : NONE
Reconstruct Branch : NOTHING
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Build Config : S P 10.0.6 AArch64
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
2021-03-11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: fail to open file: No such file or directory
The error seems to be: java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted.
Starting from Android 9, clear text http communication is disabled by default.
Check out the official Android documentation for this and also this question for further information.

Get data array from sqlite database and post to API via json object... can be possible?

newbie here... i was developing app that send my data to api via retrofit. my code was working but it sends 1 data input only at the time.... in my case, i've like to do is I want to get more saved data in my sqlite (example 5 data saved) and send it all on api via json object.
This is my Activity:
DatabaseHelper databaseHelper2 = new
DatabaseHelper(getApplicationContext());
SQLiteDatabase db2 =
databaseHelper2.getWritableDatabase();
Cursor cursor =
databaseHelper2.retrieveSettingFromLocalDatabase(db2);
while (cursor.moveToNext()) {
ADDRESS =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL=cursor.getString
(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
}
portInts=Integer.parseInt(PORT);
MapDetails mapDetails = new MapDetails(gg, lat, lon,
well, "0", portInts); //Datas ive get to send in api
List<MapDetails> data = new ArrayList<>();
data.add(mapDetails);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://" + ADDRESS + ":" + PORT)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Api locate = retrofit.create(Api.class);
Call<MapDetails> call = locate.mapDetailLocation(data);
call.enqueue(new Callback<MapDetails>() {
#Override
public void onResponse(Call<MapDetails> call, Response<MapDetails> response) {
Snackbar.make(view, "" + response,
Snackbar.LENGTH_INDEFINITE)
.setAction("Action", null).show();
}
#Override
public void onFailure(Call call, Throwable t) {
Snackbar.make(view, "" + t.getMessage(),
Snackbar.LENGTH_INDEFINITE)
.setAction("Action", null).show();
}
});
This is my code in API:
public interface Api {
#POST("/api/Database/NewLocation")
Call<MapDetails> mapDetailLocation(#Body List<MapDetails> mapDetails)
}
This is my sample Client:
public class MapDetails {
#SerializedName("SerialNumber")
#Expose
private String SerialNumber;
#SerializedName("Coordinate1")
#Expose
private String Coordinate1;
#SerializedName("Coordinate2")
#Expose
private String Coordinate2;
#SerializedName("DateTime")
#Expose
private String DateTime;
#SerializedName("Speed")
#Expose
private String Speed;
#SerializedName("Port")
#Expose
private int Port;
public MapDetails(String serialNumber, String coordinate1, String
coordinate2, String dateTime, String speed, int port) {
SerialNumber = serialNumber;
Coordinate1 = coordinate1;
Coordinate2 = coordinate2;
DateTime = dateTime;
Speed = speed;
Port = port;
}
public String getSerialNumber() {
return SerialNumber;
}
public void setSerialNumber(String serialNumber) {
SerialNumber = serialNumber;
}
public String getCoordinate1() {
return Coordinate1;
}
public void setCoordinate1(String coordinate1) {
Coordinate1 = coordinate1;
}
public String getCoordinate2() {
return Coordinate2;
}
public void setCoordinate2(String coordinate2) {
Coordinate2 = coordinate2;
}
public String getDateTime() {
return DateTime;
}
public void setDateTime(String dateTime) {
DateTime = dateTime;
}
public String getSpeed() {
return Speed;
}
public void setSpeed(String speed) {
Speed = speed;
}
public int getPort() {
return Port;
}
public void setPort(int port) {
Port = port;
}
}
this is my sqlite database ive like to retrieve:
this is the sample posting ive created at the top
but in my case, ive like to do is this one, getting the saved data from my database and send it like this,:
The reason why only one is being sent is that you are sending outside of the while loop that traverses the Cursor, so only the last is sent.
That is you have :-
while (cursor.moveToNext()) {
ADDRESS = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
}
So say the query extracted a Cursor with 10 rows as address 1,2,3....10 (for explantory purposes) then
The loop is entered ADDRESS is set to 1, the next iteration sets it to 2, the next to 3 ..... and finally ADDRESS is set to 10 (same for PORT and TIMEINTERVAL)
After the loop the data is sent so only one is sent (ADDRESS 10).
What you need is along the lines of :-
List<MapDetails> data = new ArrayList<>();
MapDetails mapDetails
Retrofit.Builder builder;
Retrofit retrofit;
Call<MapDetails> call;
Api locate;
while (cursor.moveToNext()) {
ADDRESS = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
portInts=Integer.parseInt(PORT);
mapDetails = new MapDetails(gg, lat, lon, well, "0", portInts);
data.clear(); //<<<<<<<< remove previous entries if required????
data.add(mapDetails);
builder = new Retrofit.Builder()
.baseUrl("http://" + ADDRESS + ":" + PORT)
.addConverterFactory(GsonConverterFactory.create());
retrofit = builder.build();
locate = retrofit.create(Api.class);
call = locate.mapDetailLocation(data);
call.enqueue(new Callback<MapDetails>() {
#Override
public void onResponse(Call<MapDetails> call, Response<MapDetails> response) {
Snackbar.make(view, "" + response,
Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
#Override
public void onFailure(Call call, Throwable t) {
Snackbar.make(view, "" + t.getMessage(),
Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
}
Note the above is in-principle code. it has not been checked or tested and may therefore contain some errors.
It may be that you can send an entire set e.g. data with populated in which case you may only need up to data.add(mapDetails); in the loop and then have the following code outside the loop.
If I understood your question properly, you need to send JSONArray as payload for the request. But, you made a little mistake while preparing payload from SQLite database. #Mike T pointed out that mistake in his answer to your question.
Follow these codes to fix the problem.
DatabaseHelper databaseHelper2 = new DatabaseHelper(getApplicationContext());
SQLiteDatabase db2 = databaseHelper2.getWritableDatabase();
Cursor cursor = databaseHelper2.retrieveSettingFromLocalDatabase(db2);
List<MapDetails> data = new ArrayList<>(); // declare ArrayList outside and before while loop
while (cursor.moveToNext()) {
ADDRESS = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
// pass arguments to MapDetails class constructor
portInts = Integer.parseInt(PORT);
MapDetails mapDetails = new MapDetails(gg, lat, lon, well, "0", portInts); //Datas ive get to send in api
// add prepared data to ArrayList
data.add(mapDetails);
}
// and finally execute network call
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://" + ADDRESS + ":" + PORT)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Api locate = retrofit.create(Api.class);
Call<MapDetails> call = locate.mapDetailLocation(data);
call.enqueue(new Callback<MapDetails>() {
#Override
public void onResponse(Call<MapDetails> call, Response<MapDetails> response) {
Snackbar.make(view, "" + response, Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
#Override
public void onFailure(Call call, Throwable t) {
Snackbar.make(view, "" + t.getMessage(), Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
});
PS: I'm not sure why are you taking ADDRESS and PORT from SQLite database. If they're same in every single row you don't need to take it from database right?

Hibernate in JSF Social Application runs out of connections

I'm currently writing a JSF based Social Application. I'm also using Hibernate to persist, update and merge data. But at some point my application stops responding with following error.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
at sun.reflect.GeneratedConstructorAccessor848.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1114)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2502)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2535)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2320)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.GeneratedConstructorAccessor822.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 127 more
the java code that executes transactions is here:
public class TransactionManager {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public TransactionManager() {
}
public IEntity validateUser(String userName, String userPassword) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = "FROM AccountEntity";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IAccountEntity> results = query.list();
for (IAccountEntity user : results) {
if (user.getUserName().equals(userName) && user.getPassword().equals(userPassword)) {
session.close();
sessionFactory.close();
return user;
}
}
session.close();
sessionFactory.close();
return null;
}
public IEntity retrieveUserByName(String userName) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = "FROM AccountEntity A WHERE A.userName = '" + userName + "'";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IAccountEntity> results = query.list();
session.close();
sessionFactory.close();
if (!results.isEmpty()) {
return results.get(0);
}
return null;
}
public IEntity retrievePageByName(String pageName) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = "FROM PageEntity A WHERE A.pageName = '" + pageName + "'";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IAccountEntity> results = query.list();
session.close();
sessionFactory.close();
if (!results.isEmpty()) {
return results.get(0);
}
return null;
}
public Map<IEntity, Integer> save(Object... objects) {
Map<IEntity, Integer> savedMap = new HashMap<IEntity, Integer>();
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
for (Object object : objects) {
session.save(object);
savedMap.put((IEntity) object, ((IEntity) object).getId());
}
session.getTransaction().commit();
session.close();
sessionFactory.close();
return savedMap;
}
public void merge(IEntity entity) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.update(entity);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
// SELECT * FROM `commententity` WHERE id BETWEEN 3 and 5 and
// accountEntityId = 1 ORDER BY id DESC
// SELECT * FROM `commententity` WHERE targetAccountEntity_id='1' ORDER BY
// id LIMIT 5 OFFSET 0
// FROM dao.CommentEntity D WHERE targetAccountEntity_id='1' ORDER BY D.id
// DESC
public List<IEntity> retrievePaginatedById(String classType, String targetId, String status, int id, int offset,
int limit, boolean forContactRequestNotification) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = null;
if (forContactRequestNotification) {
hql = "FROM " + classType + " D WHERE " + targetId + "=" + "'" + id + "' AND D.status = '" + status
+ "' ORDER BY D.id DESC";
} else {
hql = "FROM " + classType + " D WHERE " + targetId + "=" + "'" + id + "'" + " ORDER BY D.id DESC";
}
Query query = session.createQuery(hql).setFirstResult(offset).setMaxResults(limit);
#SuppressWarnings("unchecked")
List<IEntity> results = query.list();
session.close();
sessionFactory.close();
return results;
}
public List<IEntity> retrieveMultipleById(String classType, String targetId, String status, int id,
boolean forContactRequestNotification) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = null;
if (forContactRequestNotification) {
// SONDERFALL
hql = "FROM " + classType + " D WHERE D.status = '" + status + "' and " + targetId + "= " + id;
} else {
hql = "FROM " + classType + " D WHERE " + targetId + "= " + id;
}
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IEntity> results = query.list();
session.close();
sessionFactory.close();
return results;
}
public IEntity retrieveById(Class<?> c, int id) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
IEntity entity = (IEntity) session.get(c, id);
session.close();
sessionFactory.close();
return entity;
}
public void delete(IEntity obj) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.delete(obj);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
and this is a sample image of how a profile looks like, I'm supporting lazy loading to avoid big transactions.
I just dont get what am I doing so wrong here. I read somewhere I have to close every connection. But that doesn't seem to solve the problem.
Please increase the mysql connection size.
Go to mysql console and run below
SHOW VARIABLES LIKE "max_connections";
You will see the maximum allowed connections. You can change them using
SET GLOBAL max_connections = 200;
Restart mysql server, and it should be working fine.

How to hit the database from junit using JPA

I am writing junit test case, how to hit the database from junit using jpa.
I wrote the code for but got the following exception
javax.persistence.PersistenceException: No Persistence provider for EntityManager named smsPU
I added provide in src/test/resources/META-INF/persistent.xml file, But i got the that error.
I am posting the my code also please check where is the wrong in this code.
public class SmsBeanTest {
private SmsBean smsBean;
private SmsNotification notification;
private EntityManagerFactory entity;
private EntityManager em;
#Before
public void setUp() throws Exception {
String CONFIG_ATTR_NAME = "webappConfig";
smsBean = new SmsBean();
ServletContext ctx = mock(ServletContext.class);
Configuration config = new Configuration();
config.initProperties("syniverse-sms.properties");
when(ctx.getAttribute(CONFIG_ATTR_NAME)).thenReturn(config);
smsBean.setServletContext(ctx);
**//em = mock(EntityManager.class);
Properties prop = new Properties();
// Ensure RESOURCE_LOCAL transactions is used.
prop.put(TRANSACTION_TYPE,
PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Configure the internal connection pool
prop.put(JDBC_DRIVER, "com.mysql.jdbc.Driver");
prop.put(JDBC_URL, "jdbc:mysql://localhost:3306/platform_service_db");
prop.put(JDBC_USER, "root");
prop.put(JDBC_PASSWORD, "root");
prop.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
"src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar");
entity = Persistence.createEntityManagerFactory("smsPU", prop);
System.out.println(entity);
em = entity.createEntityManager(prop);
smsBean.setEm(em);**
// doNothing().when(em).persist(notification);
smsBean.init();
notification = new SmsNotification();
}
#After
public void tearDown() throws Exception {
smsBean = null;
notification = null;
//entity.close();
//em.close();
}
#Test
public void testSendSms() {
SmsNotificationDTO sms = new SmsNotificationDTO();
sms.setToAddress("9985291980");
sms.setMessage("Sending Message...");
try {
SyniverseDispatcher disp = mock(SyniverseDispatcher.class);
SyniverseResponse resp = new SyniverseResponse();
resp.setResponseStr("1234");
String smsTo = notification.getDestination();
String smsMsg = notification.getMessage() + new Date().getTime();
String urlStr = smsBean.getHostname() + "?user=" + smsBean.getUser() + "&pass=" + smsBean.getPass() + "&smsfrom=" + smsBean.getShortCode() + "&smsto=" + sms.getToAddress() + "&smsmsg=" + sms.getMessage();
SyniverseRequest req = new SyniverseRequest();
req.setRequestURL(urlStr);
when(disp.dispatch(req)).thenReturn(resp);
smsBean.sendSms(sms);
assertNotNull(sms.getToAddress());
assertEquals(10, sms.getToAddress().length());
assertNotNull(sms.getMessage());
assertEquals("1234", resp.getResponseStr());
} catch (SmsException e) {
fail(e.getMessage());
}
}
}
please help me,
it can't find the persistance.xml because you have it incorrectly defined. "src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar" the jar file shouldn't be listed.

How to Seed DB after DontDropDbJustCreateTablesIfModelChanged

Recently I've had my DB rights reduced so that I can't drop and recreate databases. This has led to me using the DontDropDbJustCreateTablesIfModelChanged Database initialisation from nuget.
However I'm now stuck as to how I should seed data as the Seed function is not in the initialisation so I can't override it. This is what I'd like to be able to do.
public class MyDBInitialiser : DontDropDbJustCreateTablesIfModelChanged<MyContext>
{
protected override void Seed(MyContext context)
{
base.Seed(context);
context.Item.Add(new Item() { ItemId = 1, Name = "Item 1"});
context.Item.Add(new Item() { ItemId = 2, Name = "Item 2"});
context.Item.Add(new Item() { ItemId = 3, Name = "Item 3"});
}
}
Is there another way of seeding data in this situation.
Simply,
public class DontDropDbJustCreateTablesIfModelChanged<T>
: IDatabaseInitializer<T> where T : DbContext
{
private EdmMetadata _edmMetaData;
public void InitializeDatabase(T context)
{
ObjectContext objectContext =
((IObjectContextAdapter)context).ObjectContext;
string modelHash = GetModelHash(objectContext);
if (CompatibleWithModel(modelHash, context, objectContext))
return;
DeleteExistingTables(objectContext);
CreateTables(objectContext);
SaveModelHashToDatabase(context, modelHash, objectContext);
Seed(context);
}
protected virtual void Seed(T context) { }
private void SaveModelHashToDatabase(T context, string modelHash,
ObjectContext objectContext)
{
if (_edmMetaData != null) objectContext.Detach(_edmMetaData);
_edmMetaData = new EdmMetadata();
context.Set<EdmMetadata>().Add(_edmMetaData);
_edmMetaData.ModelHash = modelHash;
context.SaveChanges();
}
private void CreateTables(ObjectContext objectContext)
{
string dataBaseCreateScript =
objectContext.CreateDatabaseScript();
objectContext.ExecuteStoreCommand(dataBaseCreateScript);
}
private void DeleteExistingTables(ObjectContext objectContext)
{
objectContext.ExecuteStoreCommand(Dropallconstraintsscript);
objectContext.ExecuteStoreCommand(Deletealltablesscript);
}
private string GetModelHash(ObjectContext context)
{
var csdlXmlString = GetCsdlXmlString(context).ToString();
return ComputeSha256Hash(csdlXmlString);
}
private bool CompatibleWithModel(string modelHash, DbContext context,
ObjectContext objectContext)
{
var isEdmMetaDataInStore =
objectContext.ExecuteStoreQuery<int>(LookupEdmMetaDataTable)
.FirstOrDefault();
if (isEdmMetaDataInStore == 1)
{
_edmMetaData = context.Set<EdmMetadata>().FirstOrDefault();
if (_edmMetaData != null)
{
return modelHash == _edmMetaData.ModelHash;
}
}
return false;
}
private string GetCsdlXmlString(ObjectContext context)
{
if (context != null)
{
var entityContainerList = context.MetadataWorkspace
.GetItems<EntityContainer>(DataSpace.SSpace);
if (entityContainerList != null)
{
var entityContainer = entityContainerList.FirstOrDefault();
var generator =
new EntityModelSchemaGenerator(entityContainer);
var stringBuilder = new StringBuilder();
var xmlWRiter = XmlWriter.Create(stringBuilder);
generator.GenerateMetadata();
generator.WriteModelSchema(xmlWRiter);
xmlWRiter.Flush();
return stringBuilder.ToString();
}
}
return string.Empty;
}
private static string ComputeSha256Hash(string input)
{
byte[] buffer = new SHA256Managed()
.ComputeHash(Encoding.ASCII.GetBytes(input));
var builder = new StringBuilder(buffer.Length * 2);
foreach (byte num in buffer)
{
builder.Append(num.ToString("X2",
CultureInfo.InvariantCulture));
}
return builder.ToString();
}
private const string Dropallconstraintsscript =
#"select
'ALTER TABLE ' + so.table_name + ' DROP CONSTRAINT '
+ so.constraint_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS so";
private const string Deletealltablesscript =
#"declare #cmd varchar(4000)
declare cmds cursor for
Select
'drop table [' + Table_Name + ']'
From
INFORMATION_SCHEMA.TABLES
open cmds
while 1=1
begin
fetch cmds into #cmd
if ##fetch_status != 0 break
print #cmd
exec(#cmd)
end
close cmds
deallocate cmds";
private const string LookupEdmMetaDataTable =
#"Select COUNT(*)
FROM INFORMATION_SCHEMA.TABLES T
Where T.TABLE_NAME = 'EdmMetaData'";
}
&
public class Population : DontDropDbJustCreateTablesIfModelChanged</* DbContext */>
{
protected override void Seed(Syndication Context)
{
/* Seeding :) */
}
}
&
Database.SetInitializer</* DbContext */>(new Population());
I my projects I split the db initialization from the db seeding. If you use inversion of control, you should be able to do something like this in your composition root (Application_Start if you are consuming the DbContext from a web app):
var seeder = ServiceLocatorPattern
.ServiceProviderLocator.Current.GetService<ISeedDb>();
if (seeder != null) seeder.Seed();
The interface:
public interface ISeedDb, IDisposable
{
void Seed();
}
A possible implementation:
public class MyDbSeeder : ISeedDb
{
private readonly MyContext _context;
public MyDbSeeder(MyContext context)
{
_context = context;
}
public void Seed()
{
_context.Item.Add(new Item { ItemId = 1, Name = "Item 1" });
// ... etc
}
public void Dispose()
{
_context.Dispose();
}
}