how to create a purchase order using BAPI : BAPI_PO_CREATE1 - sap

I am trying to create a Purchase Order using JCO3. I am able to execute my function without any error but i am not sure whats wrong system is not throwing any error and its not creating PO also in the SAP system.
JCoDestination destination = JCoDestinationManager.getDestination("ABAP_AS_WITHOUT_POOL");
JCoFunction createPurchaseOrderFunction = destination.getRepository().getFunction("BAPI_PO_CREATE1");
JCoFunction functionTransactionCommit = destination.getRepository().getFunction("BAPI_TRANSACTION_COMMIT");
// Input Header
JCoStructure poOrderHeader = createPurchaseOrderFunction.getImportParameterList().getStructure("POHEADER");
System.out.println("Header Structure" + poOrderHeader);
poOrderHeader.setValue("COMP_CODE", "0001");
poOrderHeader.setValue("DOC_TYPE", "NB");
//Date today = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
//String date = dateFormat.format(today);
String dateinString = "20.08.2015";
Date date = dateFormat.parse(dateinString);
System.out.println("Date is: " + date);
poOrderHeader.setValue("CREAT_DATE",date);
poOrderHeader.setValue("VENDOR", "V544100170");
poOrderHeader.setValue("LANGU", "EN");
poOrderHeader.setValue("PURCH_ORG", "0005");
poOrderHeader.setValue("PUR_GROUP", "001");
poOrderHeader.setValue("CURRENCY", "INR");
// PO Items
JCoTable poItems = createPurchaseOrderFunction.getTableParameterList().getTable("POITEM");
poItems.appendRow();
poItems.setValue("PO_ITEM", "1");
poItems.setValue("MATERIAL", "ZZMT_TEST2");
poItems.setValue("PLANT", "Z111");
poItems.setValue("QUANTITY", "100");
poItems.setValue("NET_PRICE", "150");
try
{
JCoContext.begin(destination);
createPurchaseOrderFunction.execute(destination);
functionTransactionCommit.execute(destination);
functionTransactionCommit.getImportParameterList().setValue("WAIT", 10);
JCoContext.end(destination);
}
catch(Exception e)
{
throw e;
}
// Print the Return Structure Message
// JCoStructure returnStructure = createPurchaseOrderFunction.getExportParameterList().getStructure("RETURN");
// if (! (returnStructure.getString("TYPE").equals("")||returnStructure.getString("TYPE").equals("S")) )
// {
// throw new RuntimeException(returnStructure.getString("MESSAGE"));
// }
JCoTable table = createPurchaseOrderFunction.getTableParameterList().getTable("POITEM");
// Iterate over table and print JCOFiled
for(JCoField field : table)
{
System.out.println("Name: "+field.getName() + "----" + "Value:" + field.getValue());
System.out.println("------------------------------------------------------------------");
}
System.out.println("---------------------------------------------------------------------------------");
System.out.println("Table" + table);

You need to call BAPI_TRANSACTION_COMMIT at the end to complete the transaction

Related

BigQueryIO returns TypedRead<TableRow> instead of PCollection<TableRow>. How to get the real data?

I have a problem with retrieving a data from bigquery table inside DoFn. I can't find example to extract values from TypedRead.
This is a simplified pipeline. I would like to check does record with target SSN exists or not in bigquery table. The target SSN will be received via pubsub in real pipeline, I have replaced it with array of strings.
final BigQueryIoTestOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(BigQueryIoTestOptions.class);
final List<String> SSNs = Arrays.asList("775-89-3939");
Pipeline p = Pipeline.create(options);
PCollection<String> ssnCollection = p.apply("GetSSNParams", Create.of(SSNs)).setCoder(StringUtf8Coder.of());
ssnCollection.apply("SelectFromBQ", ParDo.of(new DoFn<String, TypedRead<TableRow>>() {
#ProcessElement
public void processElement(ProcessContext c) throws Exception {
TypedRead<TableRow> tr =
BigQueryIO.readTableRows()
.fromQuery("SELECT pid19PatientSSN FROM dataset.table where pid19PatientSSN = '" + c.element() + "' LIMIT 1");
c.output(tr);
}
}))
.apply("ParseResponseFromBigQuery", ParDo.of(new DoFn<TypedRead<TableRow>, Void>() {
#ProcessElement
public void processElement(ProcessContext c) throws Exception {
System.out.println(c.element().toString());
}
}));
p.run();
Big query returns PCollection only, we can get the result as entry set like the below example or we can serialize to objects as well like mentioned here
If you want to query from BigQuery middle of your pipeline use BigQuery instead of BigQueryIO like mentioned here
BigQueryIO Example:
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
Pipeline pipeline = Pipeline.create(options);
PCollection<TableRow> result = pipeline.apply(BigQueryIO.readTableRows()
.fromQuery("SELECT id, name FROM [project-test:test_data.test] LIMIT 1"));
result.apply(MapElements.via(new SimpleFunction<TableRow, Void>() {
#Override
public Void apply(TableRow obj) {
System.out.println("***" + obj);
obj.entrySet().forEach(
(k)-> {
System.out.println(k.getKey() + " :" + k.getValue());
}
);
return null;
}
}));
pipeline.run().waitUntilFinish();
BigQuery Example:
// [START bigquery_simple_app_client]
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
// [END bigquery_simple_app_client]
// [START bigquery_simple_app_query]
QueryJobConfiguration queryConfig =
QueryJobConfiguration.newBuilder(
"SELECT "
+ "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, "
+ "view_count "
+ "FROM `bigquery-public-data.stackoverflow.posts_questions` "
+ "WHERE tags like '%google-bigquery%' "
+ "ORDER BY favorite_count DESC LIMIT 10")
// Use standard SQL syntax for queries.
// See: https://cloud.google.com/bigquery/sql-reference/
.setUseLegacySql(false)
.build();
// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
// Wait for the query to complete.
queryJob = queryJob.waitFor();
// Check for errors
if (queryJob == null) {
throw new RuntimeException("Job no longer exists");
} else if (queryJob.getStatus().getError() != null) {
// You can also look at queryJob.getStatus().getExecutionErrors() for all
// errors, not just the latest one.
throw new RuntimeException(queryJob.getStatus().getError().toString());
}
// [END bigquery_simple_app_query]
// [START bigquery_simple_app_print]
// Get the results.
QueryResponse response = bigquery.getQueryResults(jobId);
TableResult result = queryJob.getQueryResults();
// Print all pages of the results.
for (FieldValueList row : result.iterateAll()) {
String url = row.get("url").getStringValue();
long viewCount = row.get("view_count").getLongValue();
System.out.printf("url: %s views: %d%n", url, viewCount);
}
// [END bigquery_simple_app_print]

How to insert current date and time when user insert data in database

I am trying to insert data into database. i am basically trying to get current date , I am also hiding that particular field("Update Date) because I do want the user to see. Now all I am wanting is whenever i insert some data to database created date should automatically inserted.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreImageCreateVM StoreImageVM)
{
if (ModelState.IsValid)
{
try
{
StoreImageLogic.Insert(StoreImageVM);
}
catch (Exception e)
{
TempData["Failure"] = "Creation Failed. Image too large.";
return View(StoreImageVM);
}
TempData["Success"] = "Creation Successful";
return RedirectToAction("Index", new { id = StoreImageVM.StoreID });
}
return View(StoreImageVM);
}
savechangesmethod
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = imageVM.uploadDate;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
i just add to change the savechangesmethod by using the DateTime.Now method. see below.
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = DateTime.Now;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
}

ArrayList Double

Im getting this error
java.lang.NumberFormatException: Invalid double: "-20.528899,"
im using a webservice to get latitude and longitude from bd, and show in a map.
I am not able to pass the latitude and longitude values to list
i am saving lat and long at the same column in db, so this field should be "lat, long" eg "-20.528899, -47.438933" and i need to parse this in the list...can i do this?
public List<Localizacoes> buscarLocalizacoes(){
List<Localizacoes> lista = new ArrayList<Localizacoes>();
SoapObject buscarLocalizacoes = new SoapObject(NAMESPACE, BUSCAR);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(buscarLocalizacoes);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("uri:" + BUSCAR, envelope);
Vector<SoapObject> resposta = (Vector<SoapObject>) envelope.getResponse();
for (SoapObject soapObject : resposta){
Localizacoes loc = new Localizacoes();
loc.setId(Integer.parseInt(soapObject.getProperty("id").toString()));
loc.setNome(soapObject.getProperty("nome").toString());
loc.setDescricao(soapObject.getProperty("descricao").toString());
loc.setPosicao(soapObject.getProperty("posicao").toString()); // error in this line
lista.add(loc);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return lista;
}
activity
dao = new LocalizacoesDAO(context);
List<Localizacoes> lista = dao.buscarLocalizacoes();
Log.d("Teste Buscar", lista.toString());
public void setPosicao(LatLng poLatLng) {
this.poLatLng = poLatLng;
this.posicao = String.valueOf(poLatLng.latitude) + " " + String.valueOf(poLatLng.longitude);
}
public void setPosicao(String posicao) {
this.posicao = posicao;
String[] pos = posicao.split(" ");
this.poLatLng = new LatLng(Double.valueOf(pos[0]), Double.valueOf(pos[1]));
}
can anyone help me pls?
Change the following line in your setPosicao(String) method
String[] pos = posicao.split(" ");
INTO
String[] pos = posicao.split(", ");
(Since you have a ',' and a ' ' in the string)

To Get the VM Created Date

I am new to the VMWare Sdk Programming,i have a requirement to get the Virtual Machine (VM) Deployed date.
I have written the below code to get the other required details.
package com.vmware.vim25.mo.samples;
import java.net.URL;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
public class HelloVM {
public static void main(String[] args) throws Exception
{
long start = System.currentTimeMillis();
int i;
ServiceInstance si = new ServiceInstance(new URL("https://bgl-clvs-vc.bgl.com/sdk"), "sbibi", "sibi_123", true);
long end = System.currentTimeMillis();
System.out.println("time taken:" + (end-start));
Folder rootFolder = si.getRootFolder();
String name = rootFolder.getName();
System.out.println("root:" + name);
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
System.out.println("No oF vm:" + mes.length);
if(mes==null || mes.length ==0)
{
return;
}
for(i=0;i<mes.length; i++){
VirtualMachine vm = (VirtualMachine) mes[i];
VirtualMachineConfigInfo vminfo = vm.getConfig();
VirtualMachineCapability vmc = vm.getCapability();
vm.getResourcePool();
System.out.println("VM Name " + vm.getName());
System.out.println("GuestOS: " + vminfo.getGuestFullName());
System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported());
System.out.println("Summary: " + vminfo.getDatastoreUrl());
}
si.getServerConnection().logout();
}
}
Can anyone help me how I can get the VM created date?
I have found the Vm Creation Date using the below codes.
EventFilterSpecByUsername uFilter =
new EventFilterSpecByUsername();
uFilter.setSystemUser(false);
uFilter.setUserList(new String[] {"administrator"});
Event[] events = evtMgr.queryEvents(efs);
// print each of the events
for(int i=0; events!=null && i<events.length; i++)
{
System.out.println("\nEvent #" + i);
printEvent(events[i]);
}
/**
* Only print an event as Event type.
*/
static void printEvent(Event evt)
{
String typeName = evt.getClass().getName();
int lastDot = typeName.lastIndexOf('.');
if(lastDot != -1)
{
typeName = typeName.substring(lastDot+1);
}
System.out.println("Time:" + evt.getCreatedTime().getTime());
}
Hope this code might help others.
private DateTime GetVMCreatedDate(VirtualMachine vm)
{
var date = DateTime. Now;
var userName = new EventFilterSpecByUsername ();
userName . SystemUser = false;
var filter = new EventFilterSpec ();
filter . UserName = userName;
filter . EventTypeId = ( new String [] { "VmCreatedEvent" , "VmBeingDeployedEvent" ,"VmRegisteredEvent" , "VmClonedEvent" });
var collector = vm .GetEntityOnlyEventsCollectorView(filter);
foreach (Event e in collector . ReadNextEvents(1 ))
{
Console .WriteLine(e . GetType(). ToString() + " :" + e. CreatedTime);
date = e. CreatedTime;
}
Console .WriteLine( "---------------------------------------------------" );
return date;
}

How to get modified values from dojo table

I have a Dojo table with list of key value pairs. Both fields are editable, once a value is modified i am doing:
var items = grid.selection.getSelected();
However, the modified value is not picked up only the old value is picked.
I tried the following:
dojo.parser.parse()
dojo.parser.instantiate([dojo.byId("tableDiv")]);
but none of them worked. Can any one sugggest a solution for this.
function getAllItems() {
var returnData = "";
//dojo.parser.parse();
//dojo.parser.instantiate([dojo.byId("tableDiv")]);
//grid._refresh();
var items = grid.selection.getSelected();
function gotItems(items, request) {
var i;
for (i = 0; i < items.length; i++) {
var item = items[i];
var paramName = grid.store.getValues(item, "paramName");
var paramValue = grid.store.getValues(item, "paramValue");
if (returnData == "") {
returnData = paramName + "&" + paramValue;
} else {
returnData = returnData + "#" + paramName + "&"
+ paramValue;
} document.getElementById("returnData").value = returnData;
document.getElementById("successFlag").value = "true";
}
}
//Called when loop fails
function fetchFailed(error, request) {
alert("Error reading table data");
}
//Fetch the data.
jsonStore.fetch({
onComplete : gotItems,
onError : fetchFailed
});
}