问:
Tensorflow - Retrieving weights/biases of the trained feedforward neural network after training
I'm currently trying to create a simple web application for interactive neural network training with Flask. What I'm struggling with is retrieving the weights of the hidden layers after a feedforward neural network has been trained - my goal is to make a real back-end for the Tensorflow's Playground.

Take into consideration the following weights initialisation:

```<code># Weight initializations
tW1 = init_weights(shape=(n_features, hidden_nodes))
tW2 = init_weights(shape=(hidden_nodes, output_nodes))
</code>```

How does one go about retrieving the calculated weights of tW1 and tW2 after the training has been completed in Tensorflow?

Here's a sample of the code:

```<code>def retrieve_data():
    """Retrieves the data - to be expanded for custom database access + S3 retrieval + URL"""

    result = pd.read_csv('snp_data.csv', parse_dates=['Date'], index_col=['Date'])
    return result

def get_columns(data, columns):
    features = data.ix[:, columns]
    return features

def preprocess(data):
    """Data preprocessing"""
    result = (data - data.mean()) / data.std(ddof=0)
    result = result.fillna(0)
    return result

def init_weights(shape):
    """ Weights initialization """
    weights = tf.random_normal(shape=shape, stddev=0.1)
    return tf.Variable(weights)

def forwardprop(X, w_1, w_2):
    """Forward propagation"""
    h = tf.nn.relu(tf.matmul(X, w_1))
    y_hat = tf.matmul(h, w_2)
    return y_hat

# @app.route('/train')
def train():
    data = retrieve_data()

    train_x = get_columns(data, columns=['Open', 'Close'])
    train_x = preprocess(data=train_x).as_matrix().astype(np.float32)
    train_x = train_x[:(len(train_x) - (len(train_x) % 32))]

    train_y = get_columns(data, columns=['Adj Close']).as_matrix().astype(np.float32)
    train_y = train_y[:(len(train_y) - (len(train_y) % 32))]

    # Number of input nodes
    n_features = train_x.shape[1]

    # Number of output nodes
    output_nodes = train_y.shape[1]

    # Number of hidden nodes
    hidden_nodes = 20

    # TF Placeholders for the inputs and outputs
    tx = tf.placeholder(tf.float32, shape=(None, n_features))
    ty = tf.placeholder(tf.float32, shape=(None, output_nodes))

    # Weight initializations
    tW1 = init_weights(shape=(n_features, hidden_nodes))
    tW2 = init_weights(shape=(hidden_nodes, output_nodes))

    # Forward propagation
    y_hat = forwardprop(tx, tW1, tW2)

    # Backward Propagation
    tMSE = tf.reduce_mean(tf.square(y_hat - ty))
    learning_rate = 0.001
    tOptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    tOptimize = tOptimizer.minimize(tMSE)

    batch_size = 32
    n_epochs = 8

    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        for i_e in range(n_epochs):
            for i in range(0, train_x.shape[0], batch_size):
                batch_X = train_x[i:i + batch_size, ...]
                batch_y = train_y[i:i + batch_size]

                _, loss = sess.run([tOptimize, tMSE], feed_dict={tx: batch_X, ty: batch_y})
                print(i, loss)
    return 'Flask Dockerized'
</code>```

答: This should be as simple as final_tW1, final_tW2 = sess.run([tW1, tW2]) after the for loop has completed.  You don't need to feed anything because the variables maintain their own values that don't depend on placeholders.

Body:
I'm currently trying to create a simple web application for interactive neural network training with Flask. What I'm struggling with is retrieving the weights of the hidden layers after a feedforward neural network has been trained - my goal is to make a real back-end for the Tensorflow's Playground.

Take into consideration the following weights initialisation:

# Weight initializations
tW1 = init_weights(shape=(n_features, hidden_nodes))
tW2 = init_weights(shape=(hidden_nodes, output_nodes))

How does one go about retrieving the calculated weights of tW1 and tW2 after the training has been completed in Tensorflow?

Here's a sample of the code:

def retrieve_data():
    """Retrieves the data - to be expanded for custom database access + S3 retrieval + URL"""

    result = pd.read_csv('snp_data.csv', parse_dates=['Date'], index_col=['Date'])
    return result

def get_columns(data, columns):
    features = data.ix[:, columns]
    return features

def preprocess(data):
    """Data preprocessing"""
    result = (data - data.mean()) / data.std(ddof=0)
    result = result.fillna(0)
    return result

def init_weights(shape):
    """ Weights initialization """
    weights = tf.random_normal(shape=shape, stddev=0.1)
    return tf.Variable(weights)

def forwardprop(X, w_1, w_2):
    """Forward propagation"""
    h = tf.nn.relu(tf.matmul(X, w_1))
    y_hat = tf.matmul(h, w_2)
    return y_hat

# @app.route('/train')
def train():
    data = retrieve_data()

    train_x = get_columns(data, columns=['Open', 'Close'])
    train_x = preprocess(data=train_x).as_matrix().astype(np.float32)
    train_x = train_x[:(len(train_x) - (len(train_x) % 32))]

    train_y = get_columns(data, columns=['Adj Close']).as_matrix().astype(np.float32)
    train_y = train_y[:(len(train_y) - (len(train_y) % 32))]

    # Number of input nodes
    n_features = train_x.shape[1]

    # Number of output nodes
    output_nodes = train_y.shape[1]

    # Number of hidden nodes
    hidden_nodes = 20

    # TF Placeholders for the inputs and outputs
    tx = tf.placeholder(tf.float32, shape=(None, n_features))
    ty = tf.placeholder(tf.float32, shape=(None, output_nodes))

    # Weight initializations
    tW1 = init_weights(shape=(n_features, hidden_nodes))
    tW2 = init_weights(shape=(hidden_nodes, output_nodes))

    # Forward propagation
    y_hat = forwardprop(tx, tW1, tW2)

    # Backward Propagation
    tMSE = tf.reduce_mean(tf.square(y_hat - ty))
    learning_rate = 0.001
    tOptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    tOptimize = tOptimizer.minimize(tMSE)

    batch_size = 32
    n_epochs = 8

    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        for i_e in range(n_epochs):
            for i in range(0, train_x.shape[0], batch_size):
                batch_X = train_x[i:i + batch_size, ...]
                batch_y = train_y[i:i + batch_size]

                _, loss = sess.run([tOptimize, tMSE], feed_dict={tx: batch_X, ty: batch_y})
                print(i, loss)
    return 'Flask Dockerized'


来源: stackexchange

问:
How to retrieve Name from Email Address
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? </p>

```<code>var string = "johndoe@yahoo.com";
</code>```

<p>Will be just "johdoe"? I tried with split but it did not end well. thanks. </p>

答:
You can try with the replace() and regular expression. You can read more about replace() using regex here

```<code>var myEmail = 'johndoe@yahoo.com';
var name= myEmail.replace(/@.*/, "");
console.log(name);
</code>```

This returns the string before @

ContentLicense: CC BY-SA 3.0

Title: How to retrieve Name from Email Address

Body:
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name?

var string = "johndoe@yahoo.com";

Will be just "johdoe"? I tried with split but it did not end well. thanks.

Body:
You can try with the replace() and regular expression. You can read more about replace() using regex here

var myEmail = 'johndoe@yahoo.com';
var name= myEmail.replace(/@.*/, "");
console.log(name);

This returns the string before @

ContentLicense: CC BY-SA 4.0


问:
C++ Iterator declare from typedef std::map as template argument
How can I declare an iterator for template argument map?

I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it?

```<code>template< typename container >
int print_data( container map )
{
    map::iterator iter; // this is wrong
    return 0;
}

int main()
{
    typedef std::map< int, double > Map;
    Map new_map;

    print_data< Map >( new_map );
}
</code>```

答:
While

```<code>map::iterator iter; // this is wrong
</code>```

is true. That's only because you use the scope resolution operator on an object, instead of something that designates a scope, like a class name or a namespace. So this:

```<code>typename container::iterator iter;
</code>```

Would be correct. Note the typename keyword is important and mandatory. You must let the compiler know this dependent name you are accessing is a type, so the line would be parsed as a declaration.

Body:
How can I declare an iterator for template argument map?

I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it?

template< typename container >
int print_data( container map )
{
    map::iterator iter; // this is wrong
    return 0;
}

int main()
{
    typedef std::map< int, double > Map;
    Map new_map;

    print_data< Map >( new_map );
}

Body:
While

map::iterator iter; // this is wrong

is true. That's only because you use the scope resolution operator on an object, instead of something that designates a scope, like a class name or a namespace. So this:

typename container::iterator iter;

Would be correct. Note the typename keyword is important and mandatory. You must let the compiler know this dependent name you are accessing is a type, so the line would be parsed as a declaration.


问:
PHP. Function that returns form post
Below is a sample of my function

```<code>function form ($data){
'<form action="url.php" method="POST">
<!-- Input fields -->
</form>';
return  //submit the form;
}
</code>```

When the above function is called the form data gets encrypted and posted. The idea is to hide the form data altogether and post it as an encrypted value when being submitted.

I am looking for a way to programmatically execute the POST method within the function.

答:
If you want to hide the POST url, the you can use curl like below example:

```<code><form action="" method="POST">
    <!-- Other input -->
    <button name="submit">
        Send Data!
    </button>
</form>
</code>```

Here's the PHP with cURL:

```<code>if(isset($_POST["submit"])){
    $var = $_POST["input_name"];

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,"http://www.example.com/url.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
                "postvar1=" . $var);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch); //Here's are the reponse (Maybe JSON or text base)

    curl_close ($ch);

    if ($server_output == "OK") { ... } else { ... }
}
</code>```

These above example works for sending POST Request internally (on server-side) so public cannot view the POST URL. You might also encrypt the $var before the curl_exec();

Title: PHP. Function that returns form post

Body:
Below is a sample of my function

function form ($data){
'<form action="url.php" method="POST">

</form>';
return  //submit the form;
}

When the above function is called the form data gets encrypted and posted. The idea is to hide the form data altogether and post it as an encrypted value when being submitted.

I am looking for a way to programmatically execute the POST method within the function.

Body:
If you want to hide the POST url, the you can use curl like below example:

<form action="" method="POST">
    <!-- Other input -->
    <button name="submit">
        Send Data!
    </button>
</form>

Here's the PHP with cURL:

if(isset($_POST["submit"])){
    $var = $_POST["input_name"];

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,"http://www.example.com/url.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
                "postvar1=" . $var);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch); //Here's are the reponse (Maybe JSON or text base)

    curl_close ($ch);

    if ($server_output == "OK") { ... } else { ... }
}

These above example works for sending POST Request internally (on server-side) so public cannot view the POST URL. You might also encrypt the $var before the curl_exec();


问:
Create a Hibernate schema not automatically, but with SQL script
In my project I use h2 in memory database, and I want it to be created not by Hibernate, but with by a SQL script. Here is my hibernate.properties

I made

```<code>hibernate.hbm2ddl.auto=none
</code>```

none to disable autocreation of database, and added

```<code>hibernate.hbm2ddl.import_files=schema.sql,insert-users.sql
</code>```

schema.sql contains SQL code to create schema, and then to insert-users.sql and it contains the initial data.

The project builds successfully, but when I try to hit database, I get
a Table <tablename> not found exception.

答:
Since Hibernate won't do this for you unless you use create or create-drop hbm2ddl, there are other ways to achieve what you want.

Specialized tools

There are tools that are created specifically for this: Flyway, LiquiBase. These are often configured to be run when the app is deployed and allow you to version DB scheme. They are applicable not only for testing (and mainly - not for testing), but for production as well. They can ensure that the scheme on all your envs is the same. If you use these tools, then it's better to set hbm2ddl to validate.

Spring's support

Less widespread way is to use Spring's support for embedded DBs:

```<code><jdbc:embedded-database id="dataSource">
    <jdbc:script location="classpath:schema.sql"/>
    <jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
</code>```

Data for testing

If the intention is to create data for testing (not scheme), then it's better to create entities and use your DAO/Repository layer to persist those in tests. This way you don't duplicate mechanisms of persisting data.

Body:
In my project I use h2 in memory database, and I want it to be created not by Hibernate, but with by a SQL script. Here is my hibernate.properties

I made

hibernate.hbm2ddl.auto=none

none to disable autocreation of database, and added

hibernate.hbm2ddl.import_files=schema.sql,insert-users.sql

schema.sql contains SQL code to create schema, and then to insert-users.sql and it contains the initial data.

The project builds successfully, but when I try to hit database, I get
a Table <tablename> not found exception.

Body:
Since Hibernate won't do this for you unless you use create or create-drop hbm2ddl, there are other ways to achieve what you want.

Specialized tools

There are tools that are created specifically for this: Flyway, LiquiBase. These are often configured to be run when the app is deployed and allow you to version DB scheme. They are applicable not only for testing (and mainly - not for testing), but for production as well. They can ensure that the scheme on all your envs is the same. If you use these tools, then it's better to set hbm2ddl to validate.

Spring's support

Less widespread way is to use Spring's support for embedded DBs:

<jdbc:embedded-database id="dataSource">
    <jdbc:script location="classpath:schema.sql"/>
    <jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>

Data for testing

If the intention is to create data for testing (not scheme), then it's better to create entities and use your DAO/Repository layer to persist those in tests. This way you don't duplicate mechanisms of persisting data.


问:
C# Not able to serialize class with List<CustomObject> as property
Hi
I am trying to serialize

```<code>FileStream fileStream = new FileStream("batches.xml", FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>));
List<Batche> listOfBatches = new List<Batche>();

[Serializable]
[XmlRoot("Batch")]
public class Batche
{

    [XmlElement("Title")]
    public string Title
    {
        get;set;
    }

    [XmlArray("ListOfLinks"),XmlArrayItem("Link",Type = typeof(Link))]
    public List<Link> Links
    {
        get;set;
    }
}

[Serializable]
[XmlRoot("Link")]
public class Link
{
   [XmlElement("Uri")]
   public Uri Uri
   {
       get;
       set;
   }

   [XmlElement("Status")]
   public string Status
   {
       get;
       set;
   }

}
</code>```

Getting following error :
There was an error reflecting type 'System.Collections.Generic.List`1[DownloadTRON.Entities.Batche]'.

been trying this since last 4 hours,
can any body point out what i am doing Wrong !

Regards
Pravin

答:
You have to pass extra types that are in xml,to XmlSerializer, in your case Link type.
Use this </p>

```<code>XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>), new Type[] {typeof(Link)});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi
I am trying to serialize

FileStream fileStream = new FileStream("batches.xml", FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>));
List<Batche> listOfBatches = new List<Batche>();

[Serializable]
[XmlRoot("Batch")]
public class Batche
{

    [XmlElement("Title")]
    public string Title
    {
        get;set;
    }

    [XmlArray("ListOfLinks"),XmlArrayItem("Link",Type = typeof(Link))]
    public List<Link> Links
    {
        get;set;
    }
}

[Serializable]
[XmlRoot("Link")]
public class Link
{
   [XmlElement("Uri")]
   public Uri Uri
   {
       get;
       set;
   }

   [XmlElement("Status")]
   public string Status
   {
       get;
       set;
   }

}

Getting following error :
There was an error reflecting type 'System.Collections.Generic.List`1[DownloadTRON.Entities.Batche]'.

been trying this since last 4 hours,
can any body point out what i am doing Wrong !

Regards
Pravin

Body:
You have to pass extra types that are in xml,to XmlSerializer, in your case Link type.
Use this

XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>), new Type[] {typeof(Link)});


问:
Insert data from Apache Storm to Azure Cosmos DB

Am Trying to insert data from storm into cosmos db - Mongo db

```<code>    MongoClient mongoClient = null;

    mongoClient = new MongoClient(new MongoClientURI("mongodb uri from azure portal"));

   // Get database
   MongoDatabase database = mongoClient.getDatabase("toystore");

   // Get collection
   MongoCollection<Document> collection = database.getCollection("order");
   this.productid = tuple.getIntegerByField("productid");
   this.quantity = tuple.getIntegerByField("quantity");
   this.sales = tuple.getIntegerByField("sales");
   this.refund = tuple.getIntegerByField("refund");
   this.orderdate = tuple.getStringByField("orderdate");

   // Insert documents
   Document document = new Document();
   document.append("productid", this.productid);
   document.append("quantity", this.quantity);
   document.append("sales", this.sales);
   document.append("refund", this.refund);
   document.append("orderdate", this.orderdate);

   collection.insertOne(document);
</code>```

The data should get inserted into Cosmos db. I am able to use the same code to insert into cosmos db from a separate JAVA program other than storm.

```<code>2017-12-05 03:45:03.345 o.a.s.d.executor [INFO] Opened spout eventhub-spout:(4)
2017-12-05 03:45:03.346 o.a.s.d.executor [INFO] Activating spout eventhub-spout:(4)
2017-12-05 03:45:09.618 o.m.d.cluster [INFO] Cluster created with settings {hosts=[toystore.documents.azure.com:10255], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='globaldb'}
2017-12-05 03:45:09.619 o.m.d.cluster [INFO] Adding discovered server toystore.documents.azure.com:10255 to client view of cluster
2017-12-05 03:45:09.629 o.a.s.util [ERROR] Async loop died!
java.lang.ExceptionInInitializerError: null
    at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41) ~[stormjar.jar:?]
    at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68) ~[stormjar.jar:?]
    at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360) ~[stormjar.jar:?]
    at com.mongodb.connection.MultiServerCluster.addServer(MultiServerCluster.java:305) ~[stormjar.jar:?]
    at com.mongodb.connection.MultiServerCluster.<init>(MultiServerCluster.java:83) ~[stormjar.jar:?]
    at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:116) ~[stormjar.jar:?]
    at com.mongodb.Mongo.createCluster(Mongo.java:744) ~[stormjar.jar:?]
    at com.mongodb.Mongo.createCluster(Mongo.java:728) ~[stormjar.jar:?]
    at com.mongodb.Mongo.createCluster(Mongo.java:702) ~[stormjar.jar:?]
    at com.mongodb.Mongo.<init>(Mongo.java:310) ~[stormjar.jar:?]
    at com.mongodb.Mongo.<init>(Mongo.java:306) ~[stormjar.jar:?]
    at com.mongodb.MongoClient.<init>(MongoClient.java:284) ~[stormjar.jar:?]
    at com.microsoft.example.CosmosDBBolt.execute(CosmosDBBolt.java:108) ~[stormjar.jar:?]
    at org.apache.storm.daemon.executor$fn__9841$tuple_action_fn__9843.invoke(executor.clj:730) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.daemon.executor$mk_task_receiver$fn__9762.invoke(executor.clj:462) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.disruptor$clojure_handler$reify__874.onEvent(disruptor.clj:40) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:472) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:451) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:73) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.daemon.executor$fn__9841$fn__9854$fn__9907.invoke(executor.clj:849) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.util$async_loop$fn__558.invoke(util.clj:484) [storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at clojure.lang.AFn.run(AFn.java:22) [clojure-1.7.0.jar:?]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_151]
Caused by: java.lang.NullPointerException
    at com.mongodb.connection.ClientMetadataHelper.getDriverVersion(ClientMetadataHelper.java:118) ~[stormjar.jar:?]
    at com.mongodb.connection.ClientMetadataHelper.getDriverInformation(ClientMetadataHelper.java:201) ~[stormjar.jar:?]
    at com.mongodb.connection.ClientMetadataHelper.addDriverInformation(ClientMetadataHelper.java:182) ~[stormjar.jar:?]
    at com.mongodb.connection.ClientMetadataHelper.<clinit>(ClientMetadataHelper.java:64) ~[stormjar.jar:?]
    ... 23 more
</code>```

It connects to cosmos db, however the connection then dies.

Thanks,
Ahmad

答:
This was answered by Larry from Microsoft on the MSDN Forum
Here's the link to the answer
https://social.msdn.microsoft.com/Forums/azure/en-US/1eb4f5af-a4b7-4bab-8e3d-9dfaa736e7bd/insert-data-from-hdinsight-storm-to-azure-cosmos-db?forum=hdinsight

Here's the code: https://github.com/Blackmist/hdinsight-java-storm-mongodb

Body:
Am Trying to insert data from storm into cosmos db - Mongo db

    MongoClient mongoClient = null;

    mongoClient = new MongoClient(new MongoClientURI("mongodb uri from azure portal"));

   // Get database
   MongoDatabase database = mongoClient.getDatabase("toystore");

   // Get collection
   MongoCollection<Document> collection = database.getCollection("order");
   this.productid = tuple.getIntegerByField("productid");
   this.quantity = tuple.getIntegerByField("quantity");
   this.sales = tuple.getIntegerByField("sales");
   this.refund = tuple.getIntegerByField("refund");
   this.orderdate = tuple.getStringByField("orderdate");

   // Insert documents
   Document document = new Document();
   document.append("productid", this.productid);
   document.append("quantity", this.quantity);
   document.append("sales", this.sales);
   document.append("refund", this.refund);
   document.append("orderdate", this.orderdate);

   collection.insertOne(document);

The data should get inserted into Cosmos db. I am able to use the same code to insert into cosmos db from a separate JAVA program other than storm.

2017-12-05 03:45:03.345 o.a.s.d.executor [INFO] Opened spout eventhub-spout:(4)
2017-12-05 03:45:03.346 o.a.s.d.executor [INFO] Activating spout eventhub-spout:(4)
2017-12-05 03:45:09.618 o.m.d.cluster [INFO] Cluster created with settings {hosts=[toystore.documents.azure.com:10255], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='globaldb'}
2017-12-05 03:45:09.619 o.m.d.cluster [INFO] Adding discovered server toystore.documents.azure.com:10255 to client view of cluster
2017-12-05 03:45:09.629 o.a.s.util [ERROR] Async loop died!
java.lang.ExceptionInInitializerError: null
    at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41) ~[stormjar.jar:?]
    at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68) ~[stormjar.jar:?]
    at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360) ~[stormjar.jar:?]
    at com.mongodb.connection.MultiServerCluster.addServer(MultiServerCluster.java:305) ~[stormjar.jar:?]
    at com.mongodb.connection.MultiServerCluster.<init>(MultiServerCluster.java:83) ~[stormjar.jar:?]
    at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:116) ~[stormjar.jar:?]
    at com.mongodb.Mongo.createCluster(Mongo.java:744) ~[stormjar.jar:?]
    at com.mongodb.Mongo.createCluster(Mongo.java:728) ~[stormjar.jar:?]
    at com.mongodb.Mongo.createCluster(Mongo.java:702) ~[stormjar.jar:?]
    at com.mongodb.Mongo.<init>(Mongo.java:310) ~[stormjar.jar:?]
    at com.mongodb.Mongo.<init>(Mongo.java:306) ~[stormjar.jar:?]
    at com.mongodb.MongoClient.<init>(MongoClient.java:284) ~[stormjar.jar:?]
    at com.microsoft.example.CosmosDBBolt.execute(CosmosDBBolt.java:108) ~[stormjar.jar:?]
    at org.apache.storm.daemon.executor$fn__9841$tuple_action_fn__9843.invoke(executor.clj:730) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.daemon.executor$mk_task_receiver$fn__9762.invoke(executor.clj:462) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.disruptor$clojure_handler$reify__874.onEvent(disruptor.clj:40) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:472) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:451) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:73) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.daemon.executor$fn__9841$fn__9854$fn__9907.invoke(executor.clj:849) ~[storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at org.apache.storm.util$async_loop$fn__558.invoke(util.clj:484) [storm-core-1.1.0.2.6.2.3-1.jar:1.1.0.2.6.2.3-1]
    at clojure.lang.AFn.run(AFn.java:22) [clojure-1.7.0.jar:?]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_151]
Caused by: java.lang.NullPointerException
    at com.mongodb.connection.ClientMetadataHelper.getDriverVersion(ClientMetadataHelper.java:118) ~[stormjar.jar:?]
    at com.mongodb.connection.ClientMetadataHelper.getDriverInformation(ClientMetadataHelper.java:201) ~[stormjar.jar:?]
    at com.mongodb.connection.ClientMetadataHelper.addDriverInformation(ClientMetadataHelper.java:182) ~[stormjar.jar:?]
    at com.mongodb.connection.ClientMetadataHelper.<clinit>(ClientMetadataHelper.java:64) ~[stormjar.jar:?]
    ... 23 more

It connects to cosmos db, however the connection then dies.

Thanks,
Ahmad


问:
RestTemplate response.getBody throws exception on 4** and 5** errors for put and post request but works fine for get requests
I am trying to intercept and log all the request-responses. To make requests i am using RestTemplate.exchange().

When i make a GET request and get an 4** error i can call the ClientHttpResponse.getBody() and can access the response body but for PUT and POST requests ClientHttpResponse.getBody() method throws an exception.

What might be causing this and how can i get the response body for POST and PUT requests as well?

This is where i make the request:

```<code>apiResponse = restTemplate.exchange(url, vCloudRequest.getHttpMethod(), entity, responseType);
</code>```

This is the part of the interceptor that gets the exception:

```<code>@Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, body);

        String requestString = new String(body);

        String responseString = new
// Below line throws exception
String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"));
</code>```

This is the stack.

```<code>Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://176.235.57.11/api/admin/org/bd154aaf-2e7c-446d-91be-f0a45138476b/users
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at org.springframework.http.client.SimpleClientHttpResponse.getBody(SimpleClientHttpResponse.java:85)
    at org.springframework.http.client.BufferingClientHttpResponseWrapper.getBody(BufferingClientHttpResponseWrapper.java:69)
    at roma.api_utils.model.Interceptors.RequestLoggingInterceptor.intercept(RequestLoggingInterceptor.java:39)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86)
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:70)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:652)
</code>```

Update :

When i call response.getStatusCode() before calling response.getBody() it doesn't throw IOException.

答:
I had a similar requirement of logging every request and response. I wrote a filter and hooked into the filter chain.

The code looks like something below:

```<code>public class CustomRequestFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    //No custom initialisation required
  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    try {

      HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
      HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        Map<String, String> requestMap = this
            .getTypesafeRequestMap(httpServletRequest);
        BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(
            httpServletRequest);
        BufferedResponseWrapper bufferedResponse = new BufferedResponseWrapper(
            httpServletResponse);

        final StringBuilder logMessage = new StringBuilder(
            "REST Request - ").append("[HTTP METHOD:")
            .append(httpServletRequest.getMethod())
            .append("] [PATH INFO:")
            .append(httpServletRequest.getServletPath())
            .append("] [REQUEST PARAMETERS:").append(requestMap)
            .append("] [REQUEST BODY:")
            .append(bufferedRequest.getRequestBody())
            .append("] [REMOTE ADDRESS:")
            .append(httpServletRequest.getRemoteAddr()).append("]");
        log.info("=======================REQUEST PAYLOAD=================================");
        log.info(bufferedRequest.getRequestBody());
        log.info("========================================================");
        filterChain.doFilter(bufferedRequest, bufferedResponse);
        logMessage.append(" [RESPONSE:")
            .append(bufferedResponse.getContent()).append("]");
        log.info("=======================REST RESPONSE=================================");
        log.info(bufferedResponse.getContent());
        log.info("========================================================");
             } catch (Exception a) {
      log.error("Error while filtering ", a);
    }
  }

  private Map<String, String> getTypesafeRequestMap(HttpServletRequest request) {
    Map<String, String> typesafeRequestMap = new HashMap<>();
    Enumeration<?> requestParamNames = request.getParameterNames();
    while (requestParamNames.hasMoreElements()) {
      String requestParamName = (String) requestParamNames.nextElement();
      String requestParamValue;
      if ("password".equalsIgnoreCase(requestParamName)) {
        requestParamValue = "********";
      } else {
        requestParamValue = request.getParameter(requestParamName);
      }
      typesafeRequestMap.put(requestParamName, requestParamValue);
    }
    return typesafeRequestMap;
  }

  @Override
  public void destroy() {
    //not yet implemented
  }

  private static final class BufferedRequestWrapper extends
      HttpServletRequestWrapper {

    private ByteArrayInputStream bais = null;
    private ByteArrayOutputStream baos = null;
    private BufferedServletInputStream bsis = null;
    private byte[] buffer = null;

    public BufferedRequestWrapper(HttpServletRequest req)
        throws IOException {
      super(req);
      // Read InputStream and store its content in a buffer.
      InputStream is = req.getInputStream();
      this.baos = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      int read;
      while ((read = is.read(buf)) > 0) {
        this.baos.write(buf, 0, read);
      }
      this.buffer = this.baos.toByteArray();
    }

    @Override
    public ServletInputStream getInputStream() {
      this.bais = new ByteArrayInputStream(this.buffer);
      this.bsis = new BufferedServletInputStream(this.bais);
      return this.bsis;
    }

    String getRequestBody() throws IOException {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          this.getInputStream()));
      String line;
      StringBuilder inputBuffer = new StringBuilder();
      do {
        line = reader.readLine();
        if (null != line) {
          inputBuffer.append(line.trim());
        }
      } while (line != null);
      reader.close();
      return inputBuffer.toString().trim();
    }

  }

  private static final class BufferedServletInputStream extends
      ServletInputStream {

    private ByteArrayInputStream bais;

    public BufferedServletInputStream(ByteArrayInputStream bais) {
      this.bais = bais;
    }

    @Override
    public int available() {
      return this.bais.available();
    }

    @Override
    public int read() {
      return this.bais.read();
    }

    @Override
    public int read(byte[] buf, int off, int len) {
      return this.bais.read(buf, off, len);
    }

    @Override
    public boolean isFinished() {
      return false;
    }

    @Override
    public boolean isReady() {
      return true;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
        //No specific readListener changes required
    }
  }

  public class TeeServletOutputStream extends ServletOutputStream {

    private final TeeOutputStream targetStream;

    public TeeServletOutputStream(OutputStream one, OutputStream two) {
      targetStream = new TeeOutputStream(one, two);
    }

    @Override
    public void write(int arg0) throws IOException {
      this.targetStream.write(arg0);
    }

    @Override
    public void flush() throws IOException {
      super.flush();
      this.targetStream.flush();
    }

    @Override
    public void close() throws IOException {
      super.close();
      this.targetStream.close();
    }

    @Override
    public boolean isReady() {
      return false;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
      //not yet implemented
    }
  }

  public class BufferedResponseWrapper implements HttpServletResponse {

    HttpServletResponse original;
    TeeServletOutputStream tee;
    ByteArrayOutputStream bos;

    public BufferedResponseWrapper(HttpServletResponse response) {
      original = response;
    }

    public String getContent() {
      return bos.toString();
    }

    @Override
    public PrintWriter getWriter() throws IOException {
      return original.getWriter();
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
      if (tee == null) {
        bos = new ByteArrayOutputStream();
        tee = new TeeServletOutputStream(original.getOutputStream(),
            bos);
      }
      return tee;

    }

    @Override
    public String getCharacterEncoding() {
      return original.getCharacterEncoding();
    }

    @Override
    public String getContentType() {
      return original.getContentType();
    }

    @Override
    public void setCharacterEncoding(String charset) {
      original.setCharacterEncoding(charset);
    }

    @Override
    public void setContentLength(int len) {
      original.setContentLength(len);
    }

    @Override
    public void setContentLengthLong(long l) {
      original.setContentLengthLong(l);
    }

    @Override
    public void setContentType(String type) {
      original.setContentType(type);
    }

    @Override
    public void setBufferSize(int size) {
      original.setBufferSize(size);
    }

    @Override
    public int getBufferSize() {
      return original.getBufferSize();
    }

    @Override
    public void flushBuffer() throws IOException {
      tee.flush();
    }

    @Override
    public void resetBuffer() {
      original.resetBuffer();
    }

    @Override
    public boolean isCommitted() {
      return original.isCommitted();
    }

    @Override
    public void reset() {
      original.reset();
    }

    @Override
    public void setLocale(Locale loc) {
      original.setLocale(loc);
    }

    @Override
    public Locale getLocale() {
      return original.getLocale();
    }

    @Override
    public void addCookie(Cookie cookie) {
      original.addCookie(cookie);
    }

    @Override
    public boolean containsHeader(String name) {
      return original.containsHeader(name);
    }

    @Override
    public String encodeURL(String url) {
      return original.encodeURL(url);
    }

    @Override
    public String encodeRedirectURL(String url) {
      return original.encodeRedirectURL(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public String encodeUrl(String url) {
      return original.encodeUrl(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public String encodeRedirectUrl(String url) {
      return original.encodeRedirectUrl(url);
    }

    @Override
    public void sendError(int sc, String msg) throws IOException {
      original.sendError(sc, msg);
    }

    @Override
    public void sendError(int sc) throws IOException {
      original.sendError(sc);
    }

    @Override
    public void sendRedirect(String location) throws IOException {
      original.sendRedirect(location);
    }

    @Override
    public void setDateHeader(String name, long date) {
      original.setDateHeader(name, date);
    }

    @Override
    public void addDateHeader(String name, long date) {
      original.addDateHeader(name, date);
    }

    @Override
    public void setHeader(String name, String value) {
      original.setHeader(name, value);
    }

    @Override
    public void addHeader(String name, String value) {
      original.addHeader(name, value);
    }

    @Override
    public void setIntHeader(String name, int value) {
      original.setIntHeader(name, value);
    }

    @Override
    public void addIntHeader(String name, int value) {
      original.addIntHeader(name, value);
    }

    @Override
    public void setStatus(int sc) {
      original.setStatus(sc);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void setStatus(int sc, String sm) {
      original.setStatus(sc, sm);
    }

    @Override
    public String getHeader(String arg0) {
      return original.getHeader(arg0);
    }

    @Override
    public Collection<String> getHeaderNames() {
      return original.getHeaderNames();
    }

    @Override
    public Collection<String> getHeaders(String arg0) {
      return original.getHeaders(arg0);
    }

    @Override
    public int getStatus() {
      return original.getStatus();
    }

  }
}
</code>```

Body:
I am trying to intercept and log all the request-responses. To make requests i am using RestTemplate.exchange().

When i make a GET request and get an 4** error i can call the ClientHttpResponse.getBody() and can access the response body but for PUT and POST requests ClientHttpResponse.getBody() method throws an exception.

What might be causing this and how can i get the response body for POST and PUT requests as well?

This is where i make the request:

apiResponse = restTemplate.exchange(url, vCloudRequest.getHttpMethod(), entity, responseType);

This is the part of the interceptor that gets the exception:

@Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, body);

        String requestString = new String(body);

        String responseString = new
// Below line throws exception
String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"));

This is the stack.

Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://176.235.57.11/api/admin/org/bd154aaf-2e7c-446d-91be-f0a45138476b/users
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at org.springframework.http.client.SimpleClientHttpResponse.getBody(SimpleClientHttpResponse.java:85)
    at org.springframework.http.client.BufferingClientHttpResponseWrapper.getBody(BufferingClientHttpResponseWrapper.java:69)
    at roma.api_utils.model.Interceptors.RequestLoggingInterceptor.intercept(RequestLoggingInterceptor.java:39)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86)
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:70)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:652)

Update :

When i call response.getStatusCode() before calling response.getBody() it doesn't throw IOException.

Body:
I had a similar requirement of logging every request and response. I wrote a filter and hooked into the filter chain.

The code looks like something below:

public class CustomRequestFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    //No custom initialisation required
  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    try {

      HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
      HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        Map<String, String> requestMap = this
            .getTypesafeRequestMap(httpServletRequest);
        BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(
            httpServletRequest);
        BufferedResponseWrapper bufferedResponse = new BufferedResponseWrapper(
            httpServletResponse);

        final StringBuilder logMessage = new StringBuilder(
            "REST Request - ").append("[HTTP METHOD:")
            .append(httpServletRequest.getMethod())
            .append("] [PATH INFO:")
            .append(httpServletRequest.getServletPath())
            .append("] [REQUEST PARAMETERS:").append(requestMap)
            .append("] [REQUEST BODY:")
            .append(bufferedRequest.getRequestBody())
            .append("] [REMOTE ADDRESS:")
            .append(httpServletRequest.getRemoteAddr()).append("]");
        log.info("=======================REQUEST PAYLOAD=================================");
        log.info(bufferedRequest.getRequestBody());
        log.info("========================================================");
        filterChain.doFilter(bufferedRequest, bufferedResponse);
        logMessage.append(" [RESPONSE:")
            .append(bufferedResponse.getContent()).append("]");
        log.info("=======================REST RESPONSE=================================");
        log.info(bufferedResponse.getContent());
        log.info("========================================================");
             } catch (Exception a) {
      log.error("Error while filtering ", a);
    }
  }

  private Map<String, String> getTypesafeRequestMap(HttpServletRequest request) {
    Map<String, String> typesafeRequestMap = new HashMap<>();
    Enumeration<?> requestParamNames = request.getParameterNames();
    while (requestParamNames.hasMoreElements()) {
      String requestParamName = (String) requestParamNames.nextElement();
      String requestParamValue;
      if ("password".equalsIgnoreCase(requestParamName)) {
        requestParamValue = "********";
      } else {
        requestParamValue = request.getParameter(requestParamName);
      }
      typesafeRequestMap.put(requestParamName, requestParamValue);
    }
    return typesafeRequestMap;
  }

  @Override
  public void destroy() {
    //not yet implemented
  }

  private static final class BufferedRequestWrapper extends
      HttpServletRequestWrapper {

    private ByteArrayInputStream bais = null;
    private ByteArrayOutputStream baos = null;
    private BufferedServletInputStream bsis = null;
    private byte[] buffer = null;

    public BufferedRequestWrapper(HttpServletRequest req)
        throws IOException {
      super(req);
      // Read InputStream and store its content in a buffer.
      InputStream is = req.getInputStream();
      this.baos = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      int read;
      while ((read = is.read(buf)) > 0) {
        this.baos.write(buf, 0, read);
      }
      this.buffer = this.baos.toByteArray();
    }

    @Override
    public ServletInputStream getInputStream() {
      this.bais = new ByteArrayInputStream(this.buffer);
      this.bsis = new BufferedServletInputStream(this.bais);
      return this.bsis;
    }

    String getRequestBody() throws IOException {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          this.getInputStream()));
      String line;
      StringBuilder inputBuffer = new StringBuilder();
      do {
        line = reader.readLine();
        if (null != line) {
          inputBuffer.append(line.trim());
        }
      } while (line != null);
      reader.close();
      return inputBuffer.toString().trim();
    }

  }

  private static final class BufferedServletInputStream extends
      ServletInputStream {

    private ByteArrayInputStream bais;

    public BufferedServletInputStream(ByteArrayInputStream bais) {
      this.bais = bais;
    }

    @Override
    public int available() {
      return this.bais.available();
    }

    @Override
    public int read() {
      return this.bais.read();
    }

    @Override
    public int read(byte[] buf, int off, int len) {
      return this.bais.read(buf, off, len);
    }

    @Override
    public boolean isFinished() {
      return false;
    }

    @Override
    public boolean isReady() {
      return true;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
        //No specific readListener changes required
    }
  }

  public class TeeServletOutputStream extends ServletOutputStream {

    private final TeeOutputStream targetStream;

    public TeeServletOutputStream(OutputStream one, OutputStream two) {
      targetStream = new TeeOutputStream(one, two);
    }

    @Override
    public void write(int arg0) throws IOException {
      this.targetStream.write(arg0);
    }

    @Override
    public void flush() throws IOException {
      super.flush();
      this.targetStream.flush();
    }

    @Override
    public void close() throws IOException {
      super.close();
      this.targetStream.close();
    }

    @Override
    public boolean isReady() {
      return false;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
      //not yet implemented
    }
  }

  public class BufferedResponseWrapper implements HttpServletResponse {

    HttpServletResponse original;
    TeeServletOutputStream tee;
    ByteArrayOutputStream bos;

    public BufferedResponseWrapper(HttpServletResponse response) {
      original = response;
    }

    public String getContent() {
      return bos.toString();
    }

    @Override
    public PrintWriter getWriter() throws IOException {
      return original.getWriter();
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
      if (tee == null) {
        bos = new ByteArrayOutputStream();
        tee = new TeeServletOutputStream(original.getOutputStream(),
            bos);
      }
      return tee;

    }

    @Override
    public String getCharacterEncoding() {
      return original.getCharacterEncoding();
    }

    @Override
    public String getContentType() {
      return original.getContentType();
    }

    @Override
    public void setCharacterEncoding(String charset) {
      original.setCharacterEncoding(charset);
    }

    @Override
    public void setContentLength(int len) {
      original.setContentLength(len);
    }

    @Override
    public void setContentLengthLong(long l) {
      original.setContentLengthLong(l);
    }

    @Override
    public void setContentType(String type) {
      original.setContentType(type);
    }

    @Override
    public void setBufferSize(int size) {
      original.setBufferSize(size);
    }

    @Override
    public int getBufferSize() {
      return original.getBufferSize();
    }

    @Override
    public void flushBuffer() throws IOException {
      tee.flush();
    }

    @Override
    public void resetBuffer() {
      original.resetBuffer();
    }

    @Override
    public boolean isCommitted() {
      return original.isCommitted();
    }

    @Override
    public void reset() {
      original.reset();
    }

    @Override
    public void setLocale(Locale loc) {
      original.setLocale(loc);
    }

    @Override
    public Locale getLocale() {
      return original.getLocale();
    }

    @Override
    public void addCookie(Cookie cookie) {
      original.addCookie(cookie);
    }

    @Override
    public boolean containsHeader(String name) {
      return original.containsHeader(name);
    }

    @Override
    public String encodeURL(String url) {
      return original.encodeURL(url);
    }

    @Override
    public String encodeRedirectURL(String url) {
      return original.encodeRedirectURL(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public String encodeUrl(String url) {
      return original.encodeUrl(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public String encodeRedirectUrl(String url) {
      return original.encodeRedirectUrl(url);
    }

    @Override
    public void sendError(int sc, String msg) throws IOException {
      original.sendError(sc, msg);
    }

    @Override
    public void sendError(int sc) throws IOException {
      original.sendError(sc);
    }

    @Override
    public void sendRedirect(String location) throws IOException {
      original.sendRedirect(location);
    }

    @Override
    public void setDateHeader(String name, long date) {
      original.setDateHeader(name, date);
    }

    @Override
    public void addDateHeader(String name, long date) {
      original.addDateHeader(name, date);
    }

    @Override
    public void setHeader(String name, String value) {
      original.setHeader(name, value);
    }

    @Override
    public void addHeader(String name, String value) {
      original.addHeader(name, value);
    }

    @Override
    public void setIntHeader(String name, int value) {
      original.setIntHeader(name, value);
    }

    @Override
    public void addIntHeader(String name, int value) {
      original.addIntHeader(name, value);
    }

    @Override
    public void setStatus(int sc) {
      original.setStatus(sc);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void setStatus(int sc, String sm) {
      original.setStatus(sc, sm);
    }

    @Override
    public String getHeader(String arg0) {
      return original.getHeader(arg0);
    }

    @Override
    public Collection<String> getHeaderNames() {
      return original.getHeaderNames();
    }

    @Override
    public Collection<String> getHeaders(String arg0) {
      return original.getHeaders(arg0);
    }

    @Override
    public int getStatus() {
      return original.getStatus();
    }

  }
}


问:
how to print project id number using project table in Laravel 5.2
I have collaboration model in My laravel app and consider following form

```<code><div class="container">
      @if($collaboration)
        <div class="row">
        @foreach ($collaboration as $proj)
<div class="col-md-3" style="border:1px solid #ccc;margin-left:5px;">

         <h2><a href="/collaborators/{{ $proj->project_id }}/">{!! $proj->project_id !!}</a></h2>
               <p>Due : {!! date_format(new DateTime($proj->due_date), "D, m Y") !!}</p>
               <p>Status: {!! $proj->project_status !!}</p>
               <p>Tasks: 0</p>
               <p>Comments: 0</p>
               <p>Attachments: 0</p>
               </div>
                @endforeach
         </div>
      @endif
</code>```

my collaboration model as following.

```<code>id project_id collaborator_id
 1     1            1
 2     1            2
 3     2            1
</code>```

now I need print project_name instinct project_id

this is my project model

```<code>id  project_name
 1       kiu
 2       jhy
 3       juh
</code>```

how can I do this?

答:
Use Eloquent Relationships

Collaboration model:

```<code>public function project()
{
    return $this->belongsTo('App\Project');
}
</code>```

Project Model:

```<code>public function collaborators()
{
    return $this->hasMany('App\Collaboration', 'collaborator_id');
}
</code>```

in your controller use eager loading to prefetch collaborations with their related projects

```<code>$collaborations = Collaboration::with('project')->get();
</code>```

Then in your views you can simply get project name with

```<code>$proj->project->project_name
</code>```

Body:
I have collaboration model in My laravel app and consider following form

      @if($collaboration)

        @foreach ($collaboration as $proj)

project_id }}/">{!! $proj->project_id !!}

Due : {!! date_format(new DateTime($proj->due_date), "D, m Y") !!}

Status: {!! $proj->project_status !!}

Tasks: 0

Comments: 0

Attachments: 0

                @endforeach

      @endif

my collaboration model as following.

id project_id collaborator_id
 1     1            1
 2     1            2
 3     2            1

now I need print project_name instinct project_id

this is my project model

id  project_name
 1       kiu
 2       jhy
 3       juh

how can I do this?

Body:
Use Eloquent Relationships

Collaboration model:

public function project()
{
    return $this->belongsTo('App\Project');
}

Project Model:

public function collaborators()
{
    return $this->hasMany('App\Collaboration', 'collaborator_id');
}

in your controller use eager loading to prefetch collaborations with their related projects

$collaborations = Collaboration::with('project')->get();

Then in your views you can simply get project name with

$proj->project->project_name


问:
Read two bytes into an integer?
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

```<code>byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist
</code>```

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

答:
You should just opt for the simple:

```<code>int val = ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff);
</code>```

You could even write your own helper function getBytesAsWord (byte[] bytes, int start) to give you the functionality if you didn't want the calculations peppering your code but I think that would probably be overkill.

Title: Read two bytes into an integer?

Body:
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

Body:
You should just opt for the simple:

int val = ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff);

You could even write your own helper function getBytesAsWord (byte[] bytes, int start) to give you the functionality if you didn't want the calculations peppering your code but I think that would probably be overkill.


问:
Get specific href values or link from email which is parsed as html in c#
I am processing emails in my C# service. I need to extract certain links present in the same to add to DB. I am using HtmlagilityPack. The div and p tags turn out interchangeable in the parsed email. I have to extract the links present below the tags 'Scheduler Link', 'Data Path' and 'Link' from the email. After cleaning it up, a sample data is as follows :

```<code><html>
 <body>
   ......//contains some other tags which i dont need, may include hrefs but
         //i dont need them
   <div align="justify" style="margin:0;"></div>
   <div align="justify" style="margin:0;"></div>
   <div align="justify" style="margin:0;">Scheduler link :</div>
   <div align="justify" style="margin:0;"></div>
   <div style="margin:0;"><a href="https://something.com/requests/26428">
   https://something.com/requests/26428</a>
   </div>
   <div style="margin:0;"></div>
   <div style="margin:0;"></div>
   <div style="margin:0;"></div>
   <div align="justify" style="margin:0;">Data path :</div>
   <div align="left" style="text-align:justify;margin:0;"><a
   href="file:///\\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui">
   \\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui</a>
   </div>
   <div align="left" style="text-align:justify;margin:0;"><a
   href="file:///\\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui">
   \\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui</a>
   </div>
   <div align="justify" style="margin:0;"></div>
   <div align="justify" style="margin:0;">Link :</div>
   <div align="justify" style="margin:0;"><a
   href="https://Thisisanotherlink.abcdef/sites/this/498592/rkjfb/3874y">
   This is some text</a></div>
   <div align="justify" style="margin:0 0 5pt 0;">This is another text</div>

   ......//contains some other tags which i dont need
 </body>
</html>
</code>```

I am looking for the div tag of 'Scheduler Link', 'Data Path' and 'Link' using regular expressions as follows :

```<code>HtmlNode schedulerLink = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["scheduler"]).Value.ToString() + "')]]");
HtmlNode dataPath = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["datapath"]).Value.ToString() + "')]]");
HtmlNode link = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["link"]).Value.ToString() + "')]]");
</code>```

The div tags are returning me the respective nodes. The number of links present against the three in each email varies and so does the order of the tags. I need to capture the links against each in a list. I am using the following code :

```<code> foreach (HtmlNode link in schedulerLink.Descendants())
        {
        string hrefValue = link.GetAttributeValue("href", string.Empty);

            if (!(link.InnerText.Contains("\r\n")))
            {
                if (link.InnerText.Contains("/"))
                {
                    schedulersList.Add(link.InnerText.Trim());
                }
            }
        }
</code>```

The descendants sometimes is not returning the correct number of nodes. Also how do i get the specific links against the 3 tags in 3 different lists since descendants usually return all the nodes present below.

答:
As you have mentioned different hrefs in your question,

one way of doing it is by following:

```<code>   var html = @"<html> <body> <div align='justify' style='margin:0;'></div> <div align='justify' style='margin:0;'></div> <div align='justify' style='margin:0;'>Scheduler link :</div> <div align='justify' style='margin:0;'></div> <div style='margin:0;'><a href='https://something.com/requests/26428'> https://something.com/requests/26428</a> </div> <div style='margin:0;'></div> <div style='margin:0;'></div> <div style='margin:0;'></div> <div align='justify' style='margin:0;'>Data path :</div> <div align='left' style='text-align:justify;margin:0;'><a href='file:///\\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui'> \\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui</a> </div> <div align='left' style='text-align:justify;margin:0;'><a href='file:///\\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui'> \\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui</a> </div> <div align='justify' style='margin:0;'></div> <div align='justify' style='margin:0;'>Link :</div> <div align='justify' style='margin:0;'><a href='https://Thisisanotherlink.abcdef/sites/this/498592/rkjfb/3874y'> This is some text</a></div> <div align='justify' style='margin:0 0 5pt 0;'>This is another text</div> </body></html>";
        var document = new HtmlDocument();
        document.LoadHtml(html);

        var schedulerNodes = document.DocumentNode.SelectNodes("//a[contains(@href, \"something\")]");
        var dataPathNodes = document.DocumentNode.SelectNodes("//a[contains(@href, \"mycompany\")]");
        var linkNodes = document.DocumentNode.SelectNodes("//a[contains(@href, \"Thisisanotherlink\")]");

        foreach (var item in schedulerNodes)
        {
            Debug.WriteLine(item.GetAttributeValue("href", ""));
            Debug.WriteLine(item.InnerText);
        }
        foreach (var item in dataPathNodes)
        {
            Debug.WriteLine(item.GetAttributeValue("href", ""));
            Debug.WriteLine(item.InnerText);
        }
        foreach (var item in linkNodes)
        {
            Debug.WriteLine(item.GetAttributeValue("href", ""));
            Debug.WriteLine(item.InnerText);
        }
</code>```

Hope that helps !!

EDIT ::

```<code>    var result = document.DocumentNode.SelectNodes("//div//text()[normalize-space()] | //a");
// select all textnodes and a tags
            string sch = "Scheduler link :";
            string dataLink = "Data path :";
            string linkpath = "Link :";
            foreach (var item in result)
            {
                if (item.InnerText.Trim().Contains(sch))
                {
                        var processResult = result.SkipWhile(x => !x.InnerText.Trim().Equals(sch)).Skip(1);
// skip the result till we reache to Scheduler.
                        Debug.WriteLine("====================Scheduler link=========================");
                        foreach (var subitem in processResult)
                        {
                            Debug.WriteLine(subitem.GetAttributeValue("href", ""));
// if href then add to list TODO
                            if (subitem.InnerText.Contains(dataLink)) // break when data link appears.
                            {
                                break;
                            }
                        }
                    }
                    if (item.InnerText.Trim().Contains(dataLink))
                    {
                        var processResult = result.SkipWhile(x => !x.InnerText.Trim().Equals(dataLink)).Skip(1);
                        Debug.WriteLine("====================Data link=========================");

                        foreach (var subitem in processResult)
                        {
                            Debug.WriteLine(subitem.GetAttributeValue("href", ""));
                            if (subitem.InnerText.Contains(dataLink))
                            {
                                break;
                            }
                        }
                    }
                    if (item.InnerText.Trim().Contains("Link :"))
                    {
                        var processResult = result.SkipWhile(x => !x.InnerText.Trim().Equals(linkpath)).Skip(1);
                        Debug.WriteLine("====================Link=========================");
                        foreach (var subitem in processResult)
                        {
                            var hrefValue = subitem.GetAttributeValue("href", "");
                            Debug.WriteLine(hrefValue);
                            if (subitem.InnerText.Contains(dataLink))
                            {
                                break;
                            }
                        }
                    }
                }
</code>```

I have mentioned logic in code commments.

Hope that helps

Body:
I am processing emails in my C# service. I need to extract certain links present in the same to add to DB. I am using HtmlagilityPack. The div and p tags turn out interchangeable in the parsed email. I have to extract the links present below the tags 'Scheduler Link', 'Data Path' and 'Link' from the email. After cleaning it up, a sample data is as follows :

   ......//contains some other tags which i dont need, may include hrefs but
         //i dont need them

Scheduler link :

   https://something.com/requests/26428

Data path :

   \\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui

   \\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui

Link :

   This is some text

This is another text

   ......//contains some other tags which i dont need

I am looking for the div tag of 'Scheduler Link', 'Data Path' and 'Link' using regular expressions as follows :

HtmlNode schedulerLink = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["scheduler"]).Value.ToString() + "')]]");
HtmlNode dataPath = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["datapath"]).Value.ToString() + "')]]");
HtmlNode link = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["link"]).Value.ToString() + "')]]");

The div tags are returning me the respective nodes. The number of links present against the three in each email varies and so does the order of the tags. I need to capture the links against each in a list. I am using the following code :

 foreach (HtmlNode link in schedulerLink.Descendants())
        {
        string hrefValue = link.GetAttributeValue("href", string.Empty);

            if (!(link.InnerText.Contains("\r\n")))
            {
                if (link.InnerText.Contains("/"))
                {
                    schedulersList.Add(link.InnerText.Trim());
                }
            }
        }

The descendants sometimes is not returning the correct number of nodes. Also how do i get the specific links against the 3 tags in 3 different lists since descendants usually return all the nodes present below.

Body:
As you have mentioned different hrefs in your question,

one way of doing it is by following:

   var html = @"<html> <body> <div align='justify' style='margin:0;'></div> <div align='justify' style='margin:0;'></div> <div align='justify' style='margin:0;'>Scheduler link :</div> <div align='justify' style='margin:0;'></div> <div style='margin:0;'><a href='https://something.com/requests/26428'> https://something.com/requests/26428</a> </div> <div style='margin:0;'></div> <div style='margin:0;'></div> <div style='margin:0;'></div> <div align='justify' style='margin:0;'>Data path :</div> <div align='left' style='text-align:justify;margin:0;'><a href='file:///\\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui'> \\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui</a> </div> <div align='left' style='text-align:justify;margin:0;'><a href='file:///\\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui'> \\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui</a> </div> <div align='justify' style='margin:0;'></div> <div align='justify' style='margin:0;'>Link :</div> <div align='justify' style='margin:0;'><a href='https://Thisisanotherlink.abcdef/sites/this/498592/rkjfb/3874y'> This is some text</a></div> <div align='justify' style='margin:0 0 5pt 0;'>This is another text</div> </body></html>";
        var document = new HtmlDocument();
        document.LoadHtml(html);

        var schedulerNodes = document.DocumentNode.SelectNodes("//a[contains(@href, \"something\")]");
        var dataPathNodes = document.DocumentNode.SelectNodes("//a[contains(@href, \"mycompany\")]");
        var linkNodes = document.DocumentNode.SelectNodes("//a[contains(@href, \"Thisisanotherlink\")]");

        foreach (var item in schedulerNodes)
        {
            Debug.WriteLine(item.GetAttributeValue("href", ""));
            Debug.WriteLine(item.InnerText);
        }
        foreach (var item in dataPathNodes)
        {
            Debug.WriteLine(item.GetAttributeValue("href", ""));
            Debug.WriteLine(item.InnerText);
        }
        foreach (var item in linkNodes)
        {
            Debug.WriteLine(item.GetAttributeValue("href", ""));
            Debug.WriteLine(item.InnerText);
        }

Hope that helps !!

EDIT ::

    var result = document.DocumentNode.SelectNodes("//div//text()[normalize-space()] | //a");
// select all textnodes and a tags
            string sch = "Scheduler link :";
            string dataLink = "Data path :";
            string linkpath = "Link :";
            foreach (var item in result)
            {
                if (item.InnerText.Trim().Contains(sch))
                {
                        var processResult = result.SkipWhile(x => !x.InnerText.Trim().Equals(sch)).Skip(1);
// skip the result till we reache to Scheduler.
                        Debug.WriteLine("====================Scheduler link=========================");
                        foreach (var subitem in processResult)
                        {
                            Debug.WriteLine(subitem.GetAttributeValue("href", ""));
// if href then add to list TODO
                            if (subitem.InnerText.Contains(dataLink)) // break when data link appears.
                            {
                                break;
                            }
                        }
                    }
                    if (item.InnerText.Trim().Contains(dataLink))
                    {
                        var processResult = result.SkipWhile(x => !x.InnerText.Trim().Equals(dataLink)).Skip(1);
                        Debug.WriteLine("====================Data link=========================");

                        foreach (var subitem in processResult)
                        {
                            Debug.WriteLine(subitem.GetAttributeValue("href", ""));
                            if (subitem.InnerText.Contains(dataLink))
                            {
                                break;
                            }
                        }
                    }
                    if (item.InnerText.Trim().Contains("Link :"))
                    {
                        var processResult = result.SkipWhile(x => !x.InnerText.Trim().Equals(linkpath)).Skip(1);
                        Debug.WriteLine("====================Link=========================");
                        foreach (var subitem in processResult)
                        {
                            var hrefValue = subitem.GetAttributeValue("href", "");
                            Debug.WriteLine(hrefValue);
                            if (subitem.InnerText.Contains(dataLink))
                            {
                                break;
                            }
                        }
                    }
                }

I have mentioned logic in code commments.

Hope that helps


问:
My Maven Module isn't generating a JAR
I have the following hierarchy:

```<code>my-app
  \__ pom.xml
  \__ jar-module
        \__ pom.xml
  \__ webapp-module
        \__ pom.xml
  \__ core-module
        \__ pom.xml
</code>```

Where core-module acts as a library providing common code for webapp-module and jar-module.

webapp-module works just fine, it's generating a war as expected and the code from core-module is being used.

The problem is with jar-module. I have no idea why, but jar-module isn't outputting a jar, even when I select to run (in IntelliJ IDEA) a simple main with a println() it does run, but there's no jar on the target folder.

How can I solve this and make the jar-module output a jar?

I am not very experienced with Maven, my goal is to be able to use the same Jersey code on a local Glassfish and in a jar to be deployed at AWS Lambda Serverless Java Container so I can easily test it locally before deployment.

I would appreciate any corrections on my hierarchy and on pom errors as well.

my-app pom.xml has a packaging of pom, but core-module and jar-module have a packaging of jar and webapp-module has a packaging of war.

here are the POMs:

my-app POM:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example.myapp</groupId>
    <artifactId>myapp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>core-module</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>
</code>```

core-module POM:
(I also tried it with <packaging>pom</packaging> and no jar skip properties, it didn't work)

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>myapp</artifactId>
        <groupId>com.example.myapp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>webservice-core</artifactId>
    <packaging>jar</packaging>
    <modules>
        <module>../jar-module</module>
        <module>../webapp-module</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.deploy.skip>true</maven.deploy.skip>
        <jar.skipIfEmpty>true</jar.skipIfEmpty>
        <maven.install.skip>true</maven.install.skip>
        <javax-ws-rs-version.version>2.1</javax-ws-rs-version.version>
        <jersey.version>2.26</jersey.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>${javax-ws-rs-version.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>
</project>
</code>```

webapp-module POM:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>core-module</artifactId>
        <groupId>com.example.myapp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>webapp-module</artifactId>
    <packaging>war</packaging>
    <name>webapp Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <jersey.version>2.26</jersey.version>
    </properties>
    <dependencies>
        <dependency>
            <artifactId>core-module</artifactId>
            <groupId>com.example.myapp</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>webapp</finalName>
    </build>
</project>
</code>```

jar-module POM:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>core-module</artifactId>
        <groupId>com.example.myapp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>jar-module</artifactId>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <jersey.version>2.26</jersey.version>
        <maven-shade-plugin.version>3.1.0</maven-shade-plugin.version>
    </properties>
    <dependencies>
        <dependency>
            <artifactId>core-module</artifactId>
            <groupId>com.example.myapp</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws.serverless</groupId>
            <artifactId>aws-serverless-java-container-jersey</artifactId>
            <version>0.8</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>${maven-shade-plugin.version}</version>
                <configuration>                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
my-app is your parent module and rest are child so provide a dependencies order in parent project pom so that when you build the project ,maven will provide the dependencies as you provided in parent module.

```<code><modules>
    <module>core-module</module>
</modules>
</code>```

Provide the proper ordering like parent and child modules to understand the maven for building.

Title: My Maven Module isn't generating a JAR

Body:
I have the following hierarchy:

my-app
  \__ pom.xml
  \__ jar-module
        \__ pom.xml
  \__ webapp-module
        \__ pom.xml
  \__ core-module
        \__ pom.xml

Where core-module acts as a library providing common code for webapp-module and jar-module.

webapp-module works just fine, it's generating a war as expected and the code from core-module is being used.

The problem is with jar-module. I have no idea why, but jar-module isn't outputting a jar, even when I select to run (in IntelliJ IDEA) a simple main with a println() it does run, but there's no jar on the target folder.

How can I solve this and make the jar-module output a jar?

I am not very experienced with Maven, my goal is to be able to use the same Jersey code on a local Glassfish and in a jar to be deployed at AWS Lambda Serverless Java Container so I can easily test it locally before deployment.

I would appreciate any corrections on my hierarchy and on pom errors as well.

my-app pom.xml has a packaging of pom, but core-module and jar-module have a packaging of jar and webapp-module has a packaging of war.

here are the POMs:

my-app POM:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example.myapp</groupId>
    <artifactId>myapp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>core-module</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>

core-module POM:
(I also tried it with <packaging>pom</packaging> and no jar skip properties, it didn't work)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>myapp</artifactId>
        <groupId>com.example.myapp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>webservice-core</artifactId>
    <packaging>jar</packaging>
    <modules>
        <module>../jar-module</module>
        <module>../webapp-module</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.deploy.skip>true</maven.deploy.skip>
        <jar.skipIfEmpty>true</jar.skipIfEmpty>
        <maven.install.skip>true</maven.install.skip>
        <javax-ws-rs-version.version>2.1</javax-ws-rs-version.version>
        <jersey.version>2.26</jersey.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>${javax-ws-rs-version.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>
</project>

webapp-module POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>core-module</artifactId>
        <groupId>com.example.myapp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>webapp-module</artifactId>
    <packaging>war</packaging>
    <name>webapp Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <jersey.version>2.26</jersey.version>
    </properties>
    <dependencies>
        <dependency>
            <artifactId>core-module</artifactId>
            <groupId>com.example.myapp</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>webapp</finalName>
    </build>
</project>

jar-module POM:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>core-module</artifactId>
        <groupId>com.example.myapp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>jar-module</artifactId>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <jersey.version>2.26</jersey.version>
        <maven-shade-plugin.version>3.1.0</maven-shade-plugin.version>
    </properties>
    <dependencies>
        <dependency>
            <artifactId>core-module</artifactId>
            <groupId>com.example.myapp</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws.serverless</groupId>
            <artifactId>aws-serverless-java-container-jersey</artifactId>
            <version>0.8</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>${maven-shade-plugin.version}</version>
                <configuration>                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Body:
my-app is your parent module and rest are child so provide a dependencies order in parent project pom so that when you build the project ,maven will provide the dependencies as you provided in parent module.

<modules>
    <module>core-module</module>
</modules>

Provide the proper ordering like parent and child modules to understand the maven for building.


问:
Finding last word in a string
I'm trying to return the last word in a string but am having trouble with the for loops. When I try to test the function I am only getting empty strings. Not really sure what the problem is. Any help is much appreciated.</p>

```<code>string getLastWord(string text)

{
    string revLastWord = "";
    string lastWord = "";
    if(text == "")
    {
        return text;
    }

    for(size_t i = text.size()-1; i > -1; i--)
    {

        if((isalpha(text[i])))
        {
             revLastWord+=text[i];
        }
        if(revLastWord.size()>=1 && !isalpha(text[i-1]))
        {
             break;
        }
    }

    for(size_t k = revLastWord.size()-1; k > -1; k--)
    {
        lastWord+=revLastWord[k];
    }

    return lastWord;
}
</code>```

答:
I was coding up another solution until I checked back and read the comments; they are extremely helpful. Moreover, the suggestion from @JustinRandall was incredibly helpful. I find that find_last_of()
and substr() better state the intent of the function--easier to write and easier to read. Thanks! Hope this helps! It helped me.

```<code>std::string get_last_word(std::string s) {
  auto index = s.find_last_of(' ');
  std::string last_word = s.substr(++index);
  return last_word;
}

/**
 * Here I have edited the above function IAW
 * the recommendations.
 * @param s is a const reference to a std::string
 * @return the substring directly
 */
std::string get_last_word(const std::string& s) {
  auto index = s.find_last_of(' ');
  return s.substr(++index);
}
</code>```

Title: Finding last word in a string

Body:
I'm trying to return the last word in a string but am having trouble with the for loops. When I try to test the function I am only getting empty strings. Not really sure what the problem is. Any help is much appreciated.

string getLastWord(string text)

{
    string revLastWord = "";
    string lastWord = "";
    if(text == "")
    {
        return text;
    }

    for(size_t i = text.size()-1; i > -1; i--)
    {

        if((isalpha(text[i])))
        {
             revLastWord+=text[i];
        }
        if(revLastWord.size()>=1 && !isalpha(text[i-1]))
        {
             break;
        }
    }

    for(size_t k = revLastWord.size()-1; k > -1; k--)
    {
        lastWord+=revLastWord[k];
    }

    return lastWord;
}

Body:
I was coding up another solution until I checked back and read the comments; they are extremely helpful. Moreover, the suggestion from @JustinRandall was incredibly helpful. I find that find_last_of()
and substr() better state the intent of the function--easier to write and easier to read. Thanks! Hope this helps! It helped me.

std::string get_last_word(std::string s) {
  auto index = s.find_last_of(' ');
  std::string last_word = s.substr(++index);
  return last_word;
}

/**
 * Here I have edited the above function IAW
 * the recommendations.
 * @param s is a const reference to a std::string
 * @return the substring directly
 */
std::string get_last_word(const std::string& s) {
  auto index = s.find_last_of(' ');
  return s.substr(++index);
}